context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using Windows.Foundation.Metadata; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Core; using Windows.ApplicationModel.Core; using Windows.UI; using System.Globalization; using System.Collections.ObjectModel; using Windows.UI.Popups; using Windows.UI.Notifications; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Diagnostics; using WinIRC.Ui; using WinIRC.Views; using WinIRC.Handlers; using WinIRC.Utils; using Template10.Services.SerializationService; using Windows.UI.Xaml.Data; using WinIRC.Net; using IrcClientCore; using WinIrcServer = WinIRC.Net.WinIrcServer; using IrcClientCore.Handlers.BuiltIn; using Windows.UI.WindowManagement; using Windows.UI.Xaml.Hosting; using Microsoft.AppCenter.Analytics; using System.Numerics; using System.Threading.Tasks; namespace WinIRC { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : INotifyPropertyChanged { public string currentChannel { get; set; } = ""; public string currentServer { get; set; } = ""; public ObservableCollection<String> servers { get; set; } public List<WinIrcServer> serversList { get; set; } public bool SettingsLoaded = false; public string currentTopic { get; set; } public bool ShowTopic { get; set; } = true; public event EventHandler UiUpdated; public Visibility _TabsVisible = Visibility.Visible; public Visibility TabsVisible { get => _TabsVisible; set { _TabsVisible = value; NotifyPropertyChanged(); } } public bool _ShowingUsers; public bool ShowingUsers { get => _ShowingUsers; set { if (currentChannel == "" || currentServer == "" || !IrcHandler.connectedServers.ContainsKey(currentServer)) { this.NotifyPropertyChanged(); return; } SidebarFrame.BackStack.Clear(); ShouldPin(); if (value) { IrcHandler.UpdateUsers(SidebarFrame, currentServer, currentChannel); UpdateInfo(currentServer, currentChannel); SidebarSplitView.IsPaneOpen = true; } _ShowingUsers = SidebarFrame.Content is UsersView && SidebarSplitView.IsPaneOpen; this.NotifyPropertyChanged(); } } private Style _ListBoxItemStyle; public Style ListBoxItemStyle { get { return this._ListBoxItemStyle; } set { if (value == this._ListBoxItemStyle) return; this._ListBoxItemStyle = value; NotifyPropertyChanged(); } } internal IrcUiHandler IrcHandler { get; private set; } public static MainPage instance; private bool lastAuto; private SolidColorBrush _AccentColor; public SolidColorBrush AccentColor { get { return _AccentColor; } set { this._AccentColor = value; NotifyPropertyChanged(); } } private SolidColorBrush _AccentColorAlt; private ICollectionView _contents; public SolidColorBrush AccentColorAlt { get { return _AccentColorAlt; } set { this._AccentColorAlt = value; NotifyPropertyChanged(); } } public ICollectionView ServerContents { get { return _contents; } set { if (_contents != value) { _contents = value; NotifyPropertyChanged(); } } } public MainPage() { var uiSettings = new Windows.UI.ViewManagement.UISettings(); AccentColor = new SolidColorBrush(uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Accent)); AccentColorAlt = new SolidColorBrush(uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.AccentDark1)); this.InitializeComponent(); this.IrcHandler = new IrcUiHandler(); this.LoadSettings(); this.DataContext = IrcHandler; currentChannel = ""; currentServer = ""; currentTopic = ""; var inputPane = InputPane.GetForCurrentView(); inputPane.Showing += this.InputPaneShowing; inputPane.Hiding += this.InputPaneHiding; Window.Current.SizeChanged += Current_SizeChanged; WindowStates.CurrentStateChanged += WindowStates_CurrentStateChanged; WindowStates.CurrentStateChanging += WindowStates_CurrentStateChanging; ; this.ListBoxItemStyle = Application.Current.Resources["ListBoxItemStyle"] as Style; instance = this; } private void WindowStates_CurrentStateChanging(object sender, VisualStateChangedEventArgs e) { var sidebarColor = Config.GetBoolean(Config.DarkTheme) ? ColorUtils.ParseColor("#FF111111") : ColorUtils.ParseColor("#FFEEEEEE"); // SplitView.PaneBackground = new SolidColorBrush(sidebarColor); } private void WindowStates_CurrentStateChanged(object sender, VisualStateChangedEventArgs e) { UpdateUi(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { try { CreateNewTab("Welcome"); if (!Config.Contains(Config.DefaultUsername) || Config.GetString(Config.DefaultUsername) == "") { var dialog = new PromptDialog ( title: "Set default username", text: "WinIRC allows you to set a default username now, please set it below. This can be changed later", placeholder: "Username", confirmButton: "Set", def: "winircuser-" + (new Random()).Next(100, 1000) ); var result = await dialog.Show(); if (result == ContentDialogResult.Primary) { Config.SetString(Config.DefaultUsername, dialog.Result); } else { Config.SetString(Config.DefaultUsername, ""); } } if (!Config.Contains(Config.AnalyticsAsked)) { AnalyticsPopup.IsOpen = true; } UpdateUi(); //ChannelFrame.Navigate(typeof(PlaceholderView)); // blank the frame } catch (Exception ex) { var dialog = new MessageDialog("Error when loading saved servers: " + ex.Message); await dialog.ShowAsync(); } IrcServers.Instance.Servers.CollectionChanged += (sender, ex) => RefreshSubMenu(); RefreshSubMenu(); CollectionViewSource collectionViewSource = new CollectionViewSource(); collectionViewSource.IsSourceGrouped = true; collectionViewSource.Source = IrcHandler.Servers; ServerContents = collectionViewSource.View; if (e.Parameter != null) { var serv = SerializationService.Json; var launchEvent = serv.Deserialize<String>(e.Parameter as String); this.ConnectViaName(launchEvent); } if (ApiInformation.IsTypePresent("Windows.UI.WindowManagement.AppWindow")) { ContentShadow.Receivers.Add(SplitView); ContentShadow.Receivers.Add(mainGrid); ContentShadow.Receivers.Add(sidebarGrid); Tabs.Translation += new Vector3(0, 0, 16); openWindowButton.Visibility = Visibility.Visible; openWindowButton.Click += OpenWindowButton_Click; } } private void RefreshSubMenu() { var items = ConnectSubMenu.Items; items.Clear(); foreach (var server in IrcServers.Instance.Servers) { var item = new MenuFlyoutItem() { Text = server.Name, DataContext = server }; item.Click += MenuBarItem_Click; items.Add(item); } } private async void OpenWindowButton_Click(object sender, RoutedEventArgs e) { var currentView = GetCurrentChannelView(); if (currentView != null) { var window = await AppWindow.TryCreateAsync(); ChannelView view = new ChannelView(currentView.Server, currentView.Channel, window); ElementCompositionPreview.SetAppWindowContent(window, view); window.Title = $"{currentView.Channel} | {currentView.Server}"; window.TitleBar.ExtendsContentIntoTitleBar = true; window.TitleBar.ButtonBackgroundColor = Colors.Transparent; CloseTab_Click(sender, e); await window.TryShowAsync(); } } public void ConnectViaName(string args) { if (args == "") return; var server = IrcServers.Instance.Get(args); Connect(IrcServers.Instance.CreateConnection(server)); } private void MenuBarItem_Click(object sender, RoutedEventArgs e) { var button = sender as MenuFlyoutItem; var server = button.DataContext as Net.WinIrcServer; Connect(IrcServers.Instance.CreateConnection(server)); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void LoadSettings() { if (Config.Contains(Config.DarkTheme)) { var darktheme = Config.GetBoolean(Config.DarkTheme); this.RequestedTheme = darktheme ? ElementTheme.Dark : ElementTheme.Light; } else { Config.SetBoolean(Config.DarkTheme, true); this.RequestedTheme = ElementTheme.Dark; } if (!Config.Contains(Config.UseTabs)) { Config.SetBoolean(Config.UseTabs, true); } ManageTitleBar(); SettingsLoaded = true; } public void ManageTitleBar() { var uiSettings = new Windows.UI.ViewManagement.UISettings(); AccentColor = new SolidColorBrush(uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Accent)); AccentColorAlt = new SolidColorBrush(uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.AccentDark1)); CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar; coreTitleBar.ExtendViewIntoTitleBar = true; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; Window.Current.SetTitleBar(TitleBarPadding); var titleBar = ApplicationView.GetForCurrentView().TitleBar; var darkTheme = Config.GetBoolean(Config.DarkTheme); var background = ColorUtils.ParseColor("#FF1F1F1F"); var backgroundInactive = ColorUtils.ParseColor("#FF2B2B2B"); var foreground = ColorUtils.ParseColor("#FFFFFFFF"); var inactive = AccentColorAlt.Color; inactive.A = 128; titleBar.BackgroundColor = _AccentColor.Color; titleBar.InactiveBackgroundColor = backgroundInactive; titleBar.ButtonHoverBackgroundColor = AccentColorAlt.Color; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = inactive; titleBar.ButtonForegroundColor = AccentColor.Color; // Menu.Background = AccentColor; } internal void UpdateUi() { if (Config.Contains(Config.ReducedPadding)) { int height; if (Config.GetBoolean(Config.ReducedPadding)) { height = 28; } else { height = 42; } var res = new ResourceDictionary { Source = new Uri("ms-appx:///Styles/Styles.xaml", UriKind.Absolute) }; var style = res["ListBoxItemStyle"] as Style; foreach (var item in style.Setters.Cast<Setter>().Where(item => item.Property == HeightProperty)) style.Setters.Remove(item); style.Setters.Add(new Setter(HeightProperty, height)); this.channelList.ItemContainerStyle = style; } if (Config.Contains(Config.HideStatusBar)) { if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1, 0)) { StatusBar statusBar = StatusBar.GetForCurrentView(); if (Config.GetBoolean(Config.HideStatusBar)) statusBar.HideAsync(); else statusBar.ShowAsync(); } } var sidebarColor = Config.GetBoolean(Config.DarkTheme) ? ColorUtils.ParseColor("#FF111111") : ColorUtils.ParseColor("#FFEEEEEE"); Brush brush; try { var miniView = WindowStates.CurrentState != WideState; if (miniView) { if (Config.GetBoolean(Config.Blurred, true) && ApiInformation.IsTypePresent("Microsoft.UI.Xaml.Media.AcrylicBrush")) { var source = Microsoft.UI.Xaml.Media.AcrylicBackgroundSource.Backdrop; brush = new Microsoft.UI.Xaml.Media.AcrylicBrush { FallbackColor = sidebarColor, BackgroundSource = source, TintColor = sidebarColor, TintOpacity = 0.55 }; } else { brush = new SolidColorBrush(sidebarColor); } SplitView.PaneBackground = brush; SidebarSplitView.PaneBackground = brush; } else { SplitView.PaneBackground = null; SidebarSplitView.PaneBackground = null; } } catch (Exception e) { brush = new SolidColorBrush(sidebarColor); SplitView.PaneBackground = brush; SidebarSplitView.PaneBackground = brush; } if (Config.Contains(Config.UseTabs)) { TabsVisible = Config.GetBoolean(Config.UseTabs) ? Visibility.Visible : Visibility.Collapsed; } UiUpdated?.Invoke(this, new EventArgs()); } public PivotItem GetCurrentItem() { return Tabs.SelectedItem as PivotItem; } public ChannelView GetCurrentChannelView() { if (GetCurrentItem() == null) return null; var item = GetCurrentItem().Content as ChannelView; return item; } public TextBox GetInputBox() { if (GetCurrentChannelView() != null) return GetCurrentChannelView().GetInputBox(); else return null; } public ListView GetChannelList() { return channelList; } private void Current_SizeChanged(object sender, WindowSizeChangedEventArgs e) { var bounds = Window.Current.Bounds; double height = bounds.Height; } private void InputPaneHiding(InputPane sender, InputPaneVisibilityEventArgs args) { this.mainGrid.Margin = new Thickness(); } private void InputPaneShowing(InputPane sender, InputPaneVisibilityEventArgs args) { if (GetInputBox() == null) return; if (GetInputBox().FocusState != FocusState.Unfocused) { this.mainGrid.Margin = new Thickness(0, -70, 0, args.OccludedRect.Height); args.EnsuredFocusedElementInView = true; } } private void ChannelList_ItemClick(object sender, ItemClickEventArgs e) { channelList.SelectedItem = e.ClickedItem; try { if (channelList.SelectedItem == null) return; var channel = channelList.SelectedItem.ToString(); currentServer = ((Channel)channelList.SelectedItem).Server; SwitchChannel(currentServer, channel, false); IrcHandler.UpdateUsers(SidebarFrame, currentServer, channel); } catch (Exception ex) { var toast = IrcUWPBase.CreateBasicToast(ex.Message, ex.StackTrace); toast.ExpirationTime = DateTime.Now.AddDays(2); ToastNotificationManager.CreateToastNotifier().Show(toast); Debug.WriteLine(ex); } } public void SwitchChannel(string server, string channel, bool auto) { if (channel == "Server") { if (Tabs.Items.Cast<PivotItem>().Any(item => item.Header as string == channel)) { Tabs.SelectedItem = Tabs.Items.Cast<PivotItem>().First(item => item.Header as string == channel); } else { CreateNewTab(server, channel); } return; } if ((auto || lastAuto || !Config.GetBoolean(Config.UseTabs)) && (GetCurrentItem() != null)) { var item = GetCurrentItem(); lastAuto = auto; item.Header = channel; if (item.Content is ChannelView) { (item.Content as ChannelView).SetChannel(server, channel); } else { item.Content = new ChannelView(server, channel); } } else if (Tabs.Items.Cast<PivotItem>().Any(item => item.Header as string == channel)) { Tabs.SelectedItem = Tabs.Items.Cast<PivotItem>().First(item => item.Header as string == channel && (item.Content as ChannelView).Server == server ); } else { CreateNewTab(server, channel); } UpdateInfo(server, channel); } private PlaceholderView CreateNewTab(String header) { PivotItem p = new PivotItem(); p.Header = header; PlaceholderView view = new PlaceholderView(); p.Margin = new Thickness(0, 0, 0, -2); p.Content = view; Tabs.Items.Add(p); Tabs.SelectedItem = p; return view; } private ChannelView CreateNewTab(String server, String channel) { PivotItem p = new PivotItem(); p.Header = channel; ChannelView view = new ChannelView(server, channel); p.Margin = new Thickness(0, 0, 0, -2); p.Content = view; Tabs.Items.Add(p); Tabs.SelectedItem = p; return view; } internal ChannelListView ShowChannelsList(List<IrcClientCore.Handlers.BuiltIn.ChannelListItem> obj) { if (obj == null) { ContentDialog noChannels = new ContentDialog() { Title = "Unable to list channels", Content = "No channels were found or there's no publically viewable channels.", CloseButtonText = "OK" }; noChannels.ShowAsync(); return null; } PivotItem p = new PivotItem(); p.Header = "Channels"; ChannelListView view = new ChannelListView(obj); p.Margin = new Thickness(0, 0, 0, -2); p.Content = view; Tabs.Items.Add(p); Tabs.SelectedItem = p; return view; } public void UpdateInfo(string server, string channel) { if (currentServer != server) { currentServer = server; } if (IrcHandler.connectedServers.ContainsKey(currentServer)) { IrcHandler.connectedServers[currentServer].SwitchChannel(channel); } currentChannel = channel; if (SplitView.DisplayMode == SplitViewDisplayMode.Overlay) SplitView.IsPaneOpen = false; channelList.SelectedValue = channel; IrcHandler.UpdateUsers(SidebarFrame, currentServer, currentChannel); } public IrcUWPBase GetCurrentServer() { try { return IrcHandler.connectedServers[currentServer]; } catch { return null; } } public IrcUWPBase GetServer(string server) { try { return IrcHandler.connectedServers[server]; } catch { return null; } } public void MentionReply(string ircserver, string channel, string message) { IrcHandler.connectedServers[ircserver].SendMessage(channel, message); } private void ToggleSplitView(object sender, RoutedEventArgs e) { SplitView.IsPaneOpen = !SplitView.IsPaneOpen; } private void ShowConnectPopup(object sender, RoutedEventArgs e) { new ConnectDialog().ShowAsync(); } public async void Connect(IrcUWPBase irc) { if (IrcHandler.connectedServersList.Contains(irc.Server.Name)) return; if (IrcHandler.connectedServersList.Contains(irc.Server.Hostname)) return; irc.Initialise(); // connect if (Tabs.Items.Count != 0) { if ((Tabs.Items[0] as PivotItem).Content is PlaceholderView) Tabs.Items.RemoveAt(0); } irc.Connect(); // link the server up to the lists IrcHandler.connectedServers.Add(irc.Server.Name, irc); IrcHandler.connectedServersList.Add(irc.Server.Name); currentServer = irc.Server.Name; if (Config.GetBoolean(Config.UseTabs)) CreateNewTab(irc.Server.Name, "Server"); lastAuto = Config.GetBoolean(Config.UseTabs); } public async Task CloseServer(IrcUWPBase irc) { irc.DisconnectAsync(attemptReconnect: false); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (IrcHandler.connectedServersList.Count > 1) { currentServer = IrcHandler.connectedServersList[0]; //channelList.ItemsSource = IrcHandler.connectedServers.Values.First().channelList; } foreach (var channel in IrcHandler.connectedServers[irc.Server.Name].ChannelList) { (channel.Buffers as UWPBuffer).Collection.Clear(); } var name = irc.Server.Name; IrcHandler.connectedServers[irc.Server.Name].ChannelList.Clear(); IrcHandler.connectedServers.Remove(irc.Server.Name); IrcHandler.connectedServersList.Remove(irc.Server.Name); irc.Dispose(); List<PivotItem> Temp = new List<PivotItem>(); Debug.WriteLine("All tabs: " + Tabs.Items.Count); var count = Tabs.Items.Count; for (var i = 0; i < count; i++) { Debug.WriteLine("Tabs seen: " + i); var item = Tabs.Items[0] as PivotItem; var content = item.Content; if (content is ChannelView && (content as ChannelView).Server == name) { item.Content = null; Tabs.Items.Remove(item); } } Debug.WriteLine(Tabs.Items.Count); if (Tabs.Items.Count == 0) { PivotItem p = new PivotItem(); lastAuto = true; p.Header = "Welcome"; Frame frame = new Frame(); p.Margin = new Thickness(0, 0, 0, -2); p.Content = frame; Tabs.Items.Add(p); Tabs.SelectedIndex = Tabs.Items.Count - 1; frame.Navigate(typeof(PlaceholderView)); } }); } private void AppearanceSettings_Click(object sender, RoutedEventArgs e) { ShowSettings(typeof(DisplaySettingsView)); } private void AboutPage_Click(object sender, RoutedEventArgs e) { ShowSettings(typeof(AboutView)); } private void ShowSettings(Type type) { var dialog = new SettingsDialog(type); dialog.UpdateUi += UpdateUi; dialog.ShowAsync(); } private void BehaviourSettings_Click(object sender, RoutedEventArgs e) { ShowSettings(typeof(BehaviourSettingsView)); } private void PinSidebar(object sender, RoutedEventArgs e) { if (!SidebarPinned()) { SidebarSplitView.DisplayMode = SplitViewDisplayMode.Inline; } else { SidebarSplitView.DisplayMode = SplitViewDisplayMode.Overlay; SidebarSplitView.IsPaneOpen = false; } ShowingUsers = false; } private bool SidebarPinned() { return SidebarSplitView.DisplayMode == SplitViewDisplayMode.Inline; } private void ToggleSidebar() { ShouldPin(); if (!SidebarPinned() || (SidebarPinned() && !SidebarSplitView.IsPaneOpen)) { SidebarSplitView.IsPaneOpen = !SidebarSplitView.IsPaneOpen; } } private void ShouldPin() { if (WindowStates.CurrentState == WideState) { SidebarSplitView.DisplayMode = SplitViewDisplayMode.Inline; } else { SidebarSplitView.DisplayMode = SplitViewDisplayMode.Overlay; } } private void ChannelListItem_ChannelCloseClicked(object sender, EventArgs e) { var channelArgs = e as ChannelEventArgs; var channel = channelArgs.Channel; GetServer(channelArgs.Server).PartChannel(channel); } private void ChannelListItem_ChannelJoinClicked(object sender, EventArgs e) { var channelArgs = e as ChannelEventArgs; var channel = channelArgs.Channel; GetServer(channelArgs.Server).JoinChannel(channel); } internal void CloseConnectView() { //serverConnect.IsModal = !serverConnect.IsModal; } public async void IrcPrompt(WinIrcServer server) { if (!Config.Contains(Config.DefaultUsername) || Config.GetString(Config.DefaultUsername) == "") { var dialog = new PromptDialog ( title: "Set a username", text: "To connect to irc servers, enter in a username first.", placeholder: "Username", confirmButton: "Set", def: "winircuser-" + (new Random()).Next(100, 1000) ); var result = await dialog.Show(); if (result == ContentDialogResult.Primary) { Config.SetString(Config.DefaultUsername, dialog.Result); } } server.Username = Config.GetString(Config.DefaultUsername); var irc = new Net.IrcUWPBase(server); MainPage.instance.Connect(irc); } private void CloseTab_Click(object sender, RoutedEventArgs e) { if (GetCurrentItem() != null) { GetCurrentItem().Content = null; Tabs.Items.Remove(GetCurrentItem()); } } private void Tabs_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (GetCurrentChannelView() != null) UpdateInfo(GetCurrentChannelView().Server, GetCurrentChannelView().Channel); } private void ChannelListItem_ServerRightClickEvent(object sender, EventArgs e) { var args = e as ServerRightClickArgs; var server = IrcHandler.connectedServers[args.server]; if (args.type == ServerRightClickType.RECONNECT) server.DisconnectAsync(attemptReconnect: true); else if (args.type == ServerRightClickType.DISCONNECT) server.DisconnectAsync(attemptReconnect: false); else if (args.type == ServerRightClickType.CLOSE) CloseServer(server); } private void MenuBarToggleItem_Click(object sender, RoutedEventArgs e) { UpdateUi(); } private void SidebarSplitView_PaneClosed(SplitView sender, object args) { ShowingUsers = false; } private void ConnectionSettings_Click(object sender, RoutedEventArgs e) { ShowSettings(typeof(ConnectionSettingsView)); } private void ChannelListItem_ServerClickEvent(object sender, EventArgs e) { var header = sender as Ui.ChannelListItem; SwitchChannel(header.Server.Server.Name, "Server", false); } private async void QuitClient_Click(object sender, RoutedEventArgs e) { ContentDialog confirmExit = new ContentDialog() { Title = "Are you sure?", Content = "This will close WinIRC and end all current connections.", PrimaryButtonText = "Yes", SecondaryButtonText = "No" }; var result = await confirmExit.ShowAsync(); if (result == ContentDialogResult.Primary) { foreach (var item in IrcHandler.connectedServers.ToList()) { await CloseServer(item.Value); } Application.Current.Exit(); } } public void ShowTeachingTip() { if (Config.GetBoolean(Config.HideBackgroundTip)) { return; } BackgroundTeachingTip.IsOpen = true; } private void BackgroundTeachingTip_ActionButtonClick(Microsoft.UI.Xaml.Controls.TeachingTip sender, object args) { Config.SetBoolean(Config.HideBackgroundTip, true); BackgroundTeachingTip.IsOpen = false; } private void AnalyticsPopup_ActionButtonClick(Microsoft.UI.Xaml.Controls.TeachingTip sender, object args) { Config.SetBoolean(Config.AnalyticsAsked, true); Analytics.SetEnabledAsync(false); AnalyticsPopup.IsOpen = false; } private void AnalyticsPopup_Closed(Microsoft.UI.Xaml.Controls.TeachingTip sender, Microsoft.UI.Xaml.Controls.TeachingTipClosedEventArgs args) { Config.SetBoolean(Config.AnalyticsAsked, true); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']" [global::Android.Runtime.Register ("org/webrtc/EglBase", DoNotGenerateAcw=true)] public sealed partial class EglBase : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']" [global::Android.Runtime.Register ("org/webrtc/EglBase$ConfigType", DoNotGenerateAcw=true)] public sealed partial class ConfigType : global::Java.Lang.Enum { static IntPtr PIXEL_BUFFER_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='PIXEL_BUFFER']" [Register ("PIXEL_BUFFER")] public static global::Org.Webrtc.EglBase.ConfigType PixelBuffer { get { if (PIXEL_BUFFER_jfieldId == IntPtr.Zero) PIXEL_BUFFER_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "PIXEL_BUFFER", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, PIXEL_BUFFER_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr PLAIN_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='PLAIN']" [Register ("PLAIN")] public static global::Org.Webrtc.EglBase.ConfigType Plain { get { if (PLAIN_jfieldId == IntPtr.Zero) PLAIN_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "PLAIN", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, PLAIN_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr RECORDABLE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/field[@name='RECORDABLE']" [Register ("RECORDABLE")] public static global::Org.Webrtc.EglBase.ConfigType Recordable { get { if (RECORDABLE_jfieldId == IntPtr.Zero) RECORDABLE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "RECORDABLE", "Lorg/webrtc/EglBase$ConfigType;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, RECORDABLE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/EglBase$ConfigType", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (ConfigType); } } internal ConfigType (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/EglBase$ConfigType;", "")] public static unsafe global::Org.Webrtc.EglBase.ConfigType ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/EglBase$ConfigType;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.EglBase.ConfigType __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.EglBase.ConfigType> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase.ConfigType']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/EglBase$ConfigType;", "")] public static unsafe global::Org.Webrtc.EglBase.ConfigType[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/EglBase$ConfigType;"); try { return (global::Org.Webrtc.EglBase.ConfigType[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.EglBase.ConfigType)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/EglBase", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (EglBase); } } internal EglBase (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/constructor[@name='EglBase' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe EglBase () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (EglBase)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } static IntPtr id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/constructor[@name='EglBase' and count(parameter)=2 and parameter[1][@type='android.opengl.EGLContext'] and parameter[2][@type='org.webrtc.EglBase.ConfigType']]" [Register (".ctor", "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", "")] public unsafe EglBase (global::Android.Opengl.EGLContext p0, global::Org.Webrtc.EglBase.ConfigType p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); if (GetType () != typeof (EglBase)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V", __args); return; } if (id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_ == IntPtr.Zero) id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/opengl/EGLContext;Lorg/webrtc/EglBase$ConfigType;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Landroid_opengl_EGLContext_Lorg_webrtc_EglBase_ConfigType_, __args); } finally { } } static IntPtr id_getContext; public unsafe global::Android.Opengl.EGLContext Context { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='getContext' and count(parameter)=0]" [Register ("getContext", "()Landroid/opengl/EGLContext;", "GetGetContextHandler")] get { if (id_getContext == IntPtr.Zero) id_getContext = JNIEnv.GetMethodID (class_ref, "getContext", "()Landroid/opengl/EGLContext;"); try { return global::Java.Lang.Object.GetObject<global::Android.Opengl.EGLContext> (JNIEnv.CallObjectMethod (Handle, id_getContext), JniHandleOwnership.TransferLocalRef); } finally { } } } static IntPtr id_hasSurface; public unsafe bool HasSurface { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='hasSurface' and count(parameter)=0]" [Register ("hasSurface", "()Z", "GetHasSurfaceHandler")] get { if (id_hasSurface == IntPtr.Zero) id_hasSurface = JNIEnv.GetMethodID (class_ref, "hasSurface", "()Z"); try { return JNIEnv.CallBooleanMethod (Handle, id_hasSurface); } finally { } } } static IntPtr id_isEGL14Supported; public static unsafe bool IsEGL14Supported { // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='isEGL14Supported' and count(parameter)=0]" [Register ("isEGL14Supported", "()Z", "GetIsEGL14SupportedHandler")] get { if (id_isEGL14Supported == IntPtr.Zero) id_isEGL14Supported = JNIEnv.GetStaticMethodID (class_ref, "isEGL14Supported", "()Z"); try { return JNIEnv.CallStaticBooleanMethod (class_ref, id_isEGL14Supported); } finally { } } } static IntPtr id_createDummyPbufferSurface; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createDummyPbufferSurface' and count(parameter)=0]" [Register ("createDummyPbufferSurface", "()V", "")] public unsafe void CreateDummyPbufferSurface () { if (id_createDummyPbufferSurface == IntPtr.Zero) id_createDummyPbufferSurface = JNIEnv.GetMethodID (class_ref, "createDummyPbufferSurface", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_createDummyPbufferSurface); } finally { } } static IntPtr id_createPbufferSurface_II; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createPbufferSurface' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='int']]" [Register ("createPbufferSurface", "(II)V", "")] public unsafe void CreatePbufferSurface (int p0, int p1) { if (id_createPbufferSurface_II == IntPtr.Zero) id_createPbufferSurface_II = JNIEnv.GetMethodID (class_ref, "createPbufferSurface", "(II)V"); try { JValue* __args = stackalloc JValue [2]; __args [0] = new JValue (p0); __args [1] = new JValue (p1); JNIEnv.CallVoidMethod (Handle, id_createPbufferSurface_II, __args); } finally { } } static IntPtr id_createSurface_Landroid_view_Surface_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='createSurface' and count(parameter)=1 and parameter[1][@type='android.view.Surface']]" [Register ("createSurface", "(Landroid/view/Surface;)V", "")] public unsafe void CreateSurface (global::Android.Views.Surface p0) { if (id_createSurface_Landroid_view_Surface_ == IntPtr.Zero) id_createSurface_Landroid_view_Surface_ = JNIEnv.GetMethodID (class_ref, "createSurface", "(Landroid/view/Surface;)V"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); JNIEnv.CallVoidMethod (Handle, id_createSurface_Landroid_view_Surface_, __args); } finally { } } static IntPtr id_makeCurrent; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='makeCurrent' and count(parameter)=0]" [Register ("makeCurrent", "()V", "")] public unsafe void MakeCurrent () { if (id_makeCurrent == IntPtr.Zero) id_makeCurrent = JNIEnv.GetMethodID (class_ref, "makeCurrent", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_makeCurrent); } finally { } } static IntPtr id_release; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='release' and count(parameter)=0]" [Register ("release", "()V", "")] public unsafe void Release () { if (id_release == IntPtr.Zero) id_release = JNIEnv.GetMethodID (class_ref, "release", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_release); } finally { } } static IntPtr id_releaseSurface; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='releaseSurface' and count(parameter)=0]" [Register ("releaseSurface", "()V", "")] public unsafe void ReleaseSurface () { if (id_releaseSurface == IntPtr.Zero) id_releaseSurface = JNIEnv.GetMethodID (class_ref, "releaseSurface", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_releaseSurface); } finally { } } static IntPtr id_swapBuffers; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='EglBase']/method[@name='swapBuffers' and count(parameter)=0]" [Register ("swapBuffers", "()V", "")] public unsafe void SwapBuffers () { if (id_swapBuffers == IntPtr.Zero) id_swapBuffers = JNIEnv.GetMethodID (class_ref, "swapBuffers", "()V"); try { JNIEnv.CallVoidMethod (Handle, id_swapBuffers); } finally { } } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using System.IO; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Router; using Couchbase.Lite.Storage; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using NUnit.Framework; using Org.Apache.Commons.IO; using Sharpen; namespace Couchbase.Lite { public abstract class LiteTestCase : TestCase { public const string Tag = "LiteTestCase"; private static bool initializedUrlHandler = false; protected internal ObjectWriter mapper = new ObjectWriter(); protected internal Manager manager = null; protected internal Database database = null; protected internal string DefaultTestDb = "cblite-test"; /// <exception cref="System.Exception"></exception> protected override void SetUp() { Log.V(Tag, "setUp"); base.SetUp(); //for some reason a traditional static initializer causes junit to die if (!initializedUrlHandler) { URLStreamHandlerFactory.RegisterSelfIgnoreError(); initializedUrlHandler = true; } LoadCustomProperties(); StartCBLite(); StartDatabase(); } protected internal virtual InputStream GetAsset(string name) { return this.GetType().GetResourceAsStream("/assets/" + name); } /// <exception cref="System.IO.IOException"></exception> protected internal virtual void StartCBLite() { LiteTestContext context = new LiteTestContext(); string serverPath = context.GetRootDirectory().GetAbsolutePath(); FilePath serverPathFile = new FilePath(serverPath); FileDirUtils.DeleteRecursive(serverPathFile); serverPathFile.Mkdir(); Manager.EnableLogging(Log.Tag, Log.Verbose); Manager.EnableLogging(Log.TagSync, Log.Verbose); Manager.EnableLogging(Log.TagQuery, Log.Verbose); Manager.EnableLogging(Log.TagView, Log.Verbose); Manager.EnableLogging(Log.TagChangeTracker, Log.Verbose); Manager.EnableLogging(Log.TagBlobStore, Log.Verbose); Manager.EnableLogging(Log.TagDatabase, Log.Verbose); Manager.EnableLogging(Log.TagListener, Log.Verbose); Manager.EnableLogging(Log.TagMultiStreamWriter, Log.Verbose); Manager.EnableLogging(Log.TagRemoteRequest, Log.Verbose); Manager.EnableLogging(Log.TagRouter, Log.Verbose); manager = new Manager(context, Manager.DefaultOptions); } protected internal virtual void StopCBLite() { if (manager != null) { manager.Close(); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> protected internal virtual Database StartDatabase() { database = EnsureEmptyDatabase(DefaultTestDb); return database; } protected internal virtual void StopDatabse() { if (database != null) { database.Close(); } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> protected internal virtual Database EnsureEmptyDatabase(string dbName) { Database db = manager.GetExistingDatabase(dbName); if (db != null) { db.Delete(); } db = manager.GetDatabase(dbName); return db; } /// <exception cref="System.IO.IOException"></exception> protected internal virtual void LoadCustomProperties() { Properties systemProperties = Runtime.GetProperties(); InputStream mainProperties = GetAsset("test.properties"); if (mainProperties != null) { systemProperties.Load(mainProperties); } try { InputStream localProperties = GetAsset("local-test.properties"); if (localProperties != null) { systemProperties.Load(localProperties); } } catch (IOException) { Log.W(Tag, "Error trying to read from local-test.properties, does this file exist?" ); } } protected internal virtual string GetReplicationProtocol() { return Runtime.GetProperty("replicationProtocol"); } protected internal virtual string GetReplicationServer() { return Runtime.GetProperty("replicationServer"); } protected internal virtual int GetReplicationPort() { return System.Convert.ToInt32(Runtime.GetProperty("replicationPort")); } protected internal virtual string GetReplicationAdminUser() { return Runtime.GetProperty("replicationAdminUser"); } protected internal virtual string GetReplicationAdminPassword() { return Runtime.GetProperty("replicationAdminPassword"); } protected internal virtual string GetReplicationDatabase() { return Runtime.GetProperty("replicationDatabase"); } protected internal virtual Uri GetReplicationURL() { try { if (GetReplicationAdminUser() != null && GetReplicationAdminUser().Trim().Length > 0) { return new Uri(string.Format("%s://%s:%s@%s:%d/%s", GetReplicationProtocol(), GetReplicationAdminUser (), GetReplicationAdminPassword(), GetReplicationServer(), GetReplicationPort(), GetReplicationDatabase())); } else { return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer (), GetReplicationPort(), GetReplicationDatabase())); } } catch (UriFormatException e) { throw new ArgumentException(e); } } protected internal virtual bool IsTestingAgainstSyncGateway() { return GetReplicationPort() == 4984; } /// <exception cref="System.UriFormatException"></exception> protected internal virtual Uri GetReplicationURLWithoutCredentials() { return new Uri(string.Format("%s://%s:%d/%s", GetReplicationProtocol(), GetReplicationServer (), GetReplicationPort(), GetReplicationDatabase())); } /// <exception cref="System.Exception"></exception> protected override void TearDown() { Log.V(Tag, "tearDown"); base.TearDown(); StopDatabse(); StopCBLite(); } protected internal virtual IDictionary<string, object> UserProperties(IDictionary <string, object> properties) { IDictionary<string, object> result = new Dictionary<string, object>(); foreach (string key in properties.Keys) { if (!key.StartsWith("_")) { result.Put(key, properties.Get(key)); } } return result; } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetReplicationAuthParsedJson() { string authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"[email protected]\"\n" + " }\n" + " }\n"; ObjectWriter mapper = new ObjectWriter(); IDictionary<string, object> authProperties = mapper.ReadValue(authJson, new _TypeReference_203 ()); return authProperties; } private sealed class _TypeReference_203 : TypeReference<Dictionary<string, object >> { public _TypeReference_203() { } } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetPushReplicationParsedJson() { IDictionary<string, object> authProperties = GetReplicationAuthParsedJson(); IDictionary<string, object> targetProperties = new Dictionary<string, object>(); targetProperties.Put("url", GetReplicationURL().ToExternalForm()); targetProperties.Put("auth", authProperties); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("source", DefaultTestDb); properties.Put("target", targetProperties); return properties; } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetPullReplicationParsedJson() { IDictionary<string, object> authProperties = GetReplicationAuthParsedJson(); IDictionary<string, object> sourceProperties = new Dictionary<string, object>(); sourceProperties.Put("url", GetReplicationURL().ToExternalForm()); sourceProperties.Put("auth", authProperties); IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("source", sourceProperties); properties.Put("target", DefaultTestDb); return properties; } protected internal virtual URLConnection SendRequest(string method, string path, IDictionary<string, string> headers, object bodyObj) { try { Uri url = new Uri("cblite://" + path); URLConnection conn = (URLConnection)url.OpenConnection(); conn.SetDoOutput(true); conn.SetRequestMethod(method); if (headers != null) { foreach (string header in headers.Keys) { conn.SetRequestProperty(header, headers.Get(header)); } } IDictionary<string, IList<string>> allProperties = conn.GetRequestProperties(); if (bodyObj != null) { conn.SetDoInput(true); ByteArrayInputStream bais = new ByteArrayInputStream(mapper.WriteValueAsBytes(bodyObj )); conn.SetRequestInputStream(bais); } Couchbase.Lite.Router.Router router = new Couchbase.Lite.Router.Router(manager, conn ); router.Start(); return conn; } catch (UriFormatException) { Fail(); } catch (IOException) { Fail(); } return null; } protected internal virtual object ParseJSONResponse(URLConnection conn) { object result = null; Body responseBody = conn.GetResponseBody(); if (responseBody != null) { byte[] json = responseBody.GetJson(); string jsonString = null; if (json != null) { jsonString = Sharpen.Runtime.GetStringForBytes(json); try { result = mapper.ReadValue<object>(jsonString); } catch (Exception) { Fail(); } } } return result; } protected internal virtual object SendBody(string method, string path, object bodyObj , int expectedStatus, object expectedResult) { URLConnection conn = SendRequest(method, path, null, bodyObj); object result = ParseJSONResponse(conn); Log.V(Tag, string.Format("%s %s --> %d", method, path, conn.GetResponseCode())); NUnit.Framework.Assert.AreEqual(expectedStatus, conn.GetResponseCode()); if (expectedResult != null) { NUnit.Framework.Assert.AreEqual(expectedResult, result); } return result; } protected internal virtual object Send(string method, string path, int expectedStatus , object expectedResult) { return SendBody(method, path, null, expectedStatus, expectedResult); } public static void CreateDocuments(Database db, int n) { //TODO should be changed to use db.runInTransaction for (int i = 0; i < n; i++) { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("testName", "testDatabase"); properties.Put("sequence", i); CreateDocumentWithProperties(db, properties); } } protected internal static Future CreateDocumentsAsync(Database db, int n) { return db.RunAsync(new _AsyncTask_310(db, n)); } private sealed class _AsyncTask_310 : AsyncTask { public _AsyncTask_310(Database db, int n) { this.db = db; this.n = n; } public void Run(Database database) { db.BeginTransaction(); LiteTestCase.CreateDocuments(db, n); db.EndTransaction(true); } private readonly Database db; private readonly int n; } public static Document CreateDocumentWithProperties(Database db, IDictionary<string , object> properties) { Document doc = db.CreateDocument(); NUnit.Framework.Assert.IsNotNull(doc); NUnit.Framework.Assert.IsNull(doc.GetCurrentRevisionId()); NUnit.Framework.Assert.IsNull(doc.GetCurrentRevision()); NUnit.Framework.Assert.IsNotNull("Document has no ID", doc.GetId()); // 'untitled' docs are no longer untitled (8/10/12) try { doc.PutProperties(properties); } catch (Exception e) { Log.E(Tag, "Error creating document", e); NUnit.Framework.Assert.IsTrue("can't create new document in db:" + db.GetName() + " with properties:" + properties.ToString(), false); } NUnit.Framework.Assert.IsNotNull(doc.GetId()); NUnit.Framework.Assert.IsNotNull(doc.GetCurrentRevisionId()); NUnit.Framework.Assert.IsNotNull(doc.GetUserProperties()); // should be same doc instance, since there should only ever be a single Document instance for a given document NUnit.Framework.Assert.AreEqual(db.GetDocument(doc.GetId()), doc); NUnit.Framework.Assert.AreEqual(db.GetDocument(doc.GetId()).GetId(), doc.GetId()); return doc; } /// <exception cref="System.Exception"></exception> public static Document CreateDocWithAttachment(Database database, string attachmentName , string content) { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("foo", "bar"); Document doc = CreateDocumentWithProperties(database, properties); SavedRevision rev = doc.GetCurrentRevision(); NUnit.Framework.Assert.AreEqual(rev.GetAttachments().Count, 0); NUnit.Framework.Assert.AreEqual(rev.GetAttachmentNames().Count, 0); NUnit.Framework.Assert.IsNull(rev.GetAttachment(attachmentName)); ByteArrayInputStream body = new ByteArrayInputStream(Sharpen.Runtime.GetBytesForString (content)); UnsavedRevision rev2 = doc.CreateRevision(); rev2.SetAttachment(attachmentName, "text/plain; charset=utf-8", body); SavedRevision rev3 = rev2.Save(); NUnit.Framework.Assert.IsNotNull(rev3); NUnit.Framework.Assert.AreEqual(rev3.GetAttachments().Count, 1); NUnit.Framework.Assert.AreEqual(rev3.GetAttachmentNames().Count, 1); Attachment attach = rev3.GetAttachment(attachmentName); NUnit.Framework.Assert.IsNotNull(attach); NUnit.Framework.Assert.AreEqual(doc, attach.GetDocument()); NUnit.Framework.Assert.AreEqual(attachmentName, attach.GetName()); IList<string> attNames = new AList<string>(); attNames.AddItem(attachmentName); NUnit.Framework.Assert.AreEqual(rev3.GetAttachmentNames(), attNames); NUnit.Framework.Assert.AreEqual("text/plain; charset=utf-8", attach.GetContentType ()); NUnit.Framework.Assert.AreEqual(IOUtils.ToString(attach.GetContent(), "UTF-8"), content ); NUnit.Framework.Assert.AreEqual(Sharpen.Runtime.GetBytesForString(content).Length , attach.GetLength()); return doc; } /// <exception cref="System.Exception"></exception> public virtual void StopReplication(Replication replication) { CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationStoppedObserver replicationStoppedObserver = new LiteTestCase.ReplicationStoppedObserver (replicationDoneSignal); replication.AddChangeListener(replicationStoppedObserver); replication.Stop(); bool success = replicationDoneSignal.Await(30, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); // give a little padding to give it a chance to save a checkpoint Sharpen.Thread.Sleep(2 * 1000); } public virtual void RunReplication(Replication replication) { CountDownLatch replicationDoneSignal = new CountDownLatch(1); LiteTestCase.ReplicationFinishedObserver replicationFinishedObserver = new LiteTestCase.ReplicationFinishedObserver (replicationDoneSignal); replication.AddChangeListener(replicationFinishedObserver); replication.Start(); CountDownLatch replicationDoneSignalPolling = ReplicationWatcherThread(replication ); Log.D(Tag, "Waiting for replicator to finish"); try { bool success = replicationDoneSignal.Await(120, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); success = replicationDoneSignalPolling.Await(120, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); Log.D(Tag, "replicator finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } replication.RemoveChangeListener(replicationFinishedObserver); } public virtual CountDownLatch ReplicationWatcherThread(Replication replication) { CountDownLatch doneSignal = new CountDownLatch(1); new Sharpen.Thread(new _Runnable_435(replication, doneSignal)).Start(); return doneSignal; } private sealed class _Runnable_435 : Runnable { public _Runnable_435(Replication replication, CountDownLatch doneSignal) { this.replication = replication; this.doneSignal = doneSignal; } public void Run() { bool started = false; bool done = false; while (!done) { if (replication.IsRunning()) { started = true; } bool statusIsDone = (replication.GetStatus() == Replication.ReplicationStatus.ReplicationStopped || replication.GetStatus() == Replication.ReplicationStatus.ReplicationIdle); if (started && statusIsDone) { done = true; } try { Sharpen.Thread.Sleep(500); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } doneSignal.CountDown(); } private readonly Replication replication; private readonly CountDownLatch doneSignal; } public class ReplicationFinishedObserver : Replication.ChangeListener { public bool replicationFinished = false; private CountDownLatch doneSignal; public ReplicationFinishedObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); Log.D(Tag, replicator + " changed. " + replicator.GetCompletedChangesCount() + " / " + replicator.GetChangesCount()); if (replicator.GetCompletedChangesCount() < 0) { string msg = string.Format("%s: replicator.getCompletedChangesCount() < 0", replicator ); Log.D(Tag, msg); throw new RuntimeException(msg); } if (replicator.GetChangesCount() < 0) { string msg = string.Format("%s: replicator.getChangesCount() < 0", replicator); Log.D(Tag, msg); throw new RuntimeException(msg); } // see https://github.com/couchbase/couchbase-lite-java-core/issues/100 if (replicator.GetCompletedChangesCount() > replicator.GetChangesCount()) { string msg = string.Format("replicator.getCompletedChangesCount() - %d > replicator.getChangesCount() - %d" , replicator.GetCompletedChangesCount(), replicator.GetChangesCount()); Log.D(Tag, msg); throw new RuntimeException(msg); } if (!replicator.IsRunning()) { replicationFinished = true; string msg = string.Format("ReplicationFinishedObserver.changed called, set replicationFinished to: %b" , replicationFinished); Log.D(Tag, msg); doneSignal.CountDown(); } else { string msg = string.Format("ReplicationFinishedObserver.changed called, but replicator still running, so ignore it" ); Log.D(Tag, msg); } } internal virtual bool IsReplicationFinished() { return replicationFinished; } } public class ReplicationRunningObserver : Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationRunningObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); if (replicator.IsRunning()) { doneSignal.CountDown(); } } } public class ReplicationIdleObserver : Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationIdleObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); if (replicator.GetStatus() == Replication.ReplicationStatus.ReplicationIdle) { doneSignal.CountDown(); } } } public class ReplicationStoppedObserver : Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationStoppedObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); if (replicator.GetStatus() == Replication.ReplicationStatus.ReplicationStopped) { doneSignal.CountDown(); } } } public class ReplicationErrorObserver : Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationErrorObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); if (replicator.GetLastError() != null) { doneSignal.CountDown(); } } } /// <exception cref="System.Exception"></exception> public virtual void DumpTableMaps() { Cursor cursor = database.GetDatabase().RawQuery("SELECT * FROM maps", null); while (cursor.MoveToNext()) { int viewId = cursor.GetInt(0); int sequence = cursor.GetInt(1); byte[] key = cursor.GetBlob(2); string keyStr = null; if (key != null) { keyStr = Sharpen.Runtime.GetStringForBytes(key); } byte[] value = cursor.GetBlob(3); string valueStr = null; if (value != null) { valueStr = Sharpen.Runtime.GetStringForBytes(value); } Log.D(Tag, string.Format("Maps row viewId: %s seq: %s, key: %s, val: %s", viewId, sequence, keyStr, valueStr)); } } /// <exception cref="System.Exception"></exception> public virtual void DumpTableRevs() { Cursor cursor = database.GetDatabase().RawQuery("SELECT * FROM revs", null); while (cursor.MoveToNext()) { int sequence = cursor.GetInt(0); int doc_id = cursor.GetInt(1); byte[] revid = cursor.GetBlob(2); string revIdStr = null; if (revid != null) { revIdStr = Sharpen.Runtime.GetStringForBytes(revid); } int parent = cursor.GetInt(3); int current = cursor.GetInt(4); int deleted = cursor.GetInt(5); Log.D(Tag, string.Format("Revs row seq: %s doc_id: %s, revIdStr: %s, parent: %s, current: %s, deleted: %s" , sequence, doc_id, revIdStr, parent, current, deleted)); } } /// <exception cref="System.Exception"></exception> public static SavedRevision CreateRevisionWithRandomProps(SavedRevision createRevFrom , bool allowConflict) { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put(UUID.RandomUUID().ToString(), "val"); UnsavedRevision unsavedRevision = createRevFrom.CreateRevision(); unsavedRevision.SetUserProperties(properties); return unsavedRevision.Save(allowConflict); } } }
//----------------------------------------------------------------------- // <copyright file="FlowFlattenMergeSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class FlowFlattenMergeSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowFlattenMergeSpec(ITestOutputHelper helper) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } private Source<int, NotUsed> Src10(int i) => Source.From(Enumerable.Range(i, 10)); private Source<int, NotUsed> Blocked => Source.FromTask(new TaskCompletionSource<int>().Task); private Sink<int, Task<IEnumerable<int>>> ToSeq => Flow.Create<int>().Grouped(1000).ToMaterialized(Sink.First<IEnumerable<int>>(), Keep.Right); private Sink<int, Task<ImmutableHashSet<int>>> ToSet => Flow.Create<int>() .Grouped(1000) .Select(x => x.ToImmutableHashSet()) .ToMaterialized(Sink.First<ImmutableHashSet<int>>(), Keep.Right); [Fact] public void A_FlattenMerge_must_work_in_the_nominal_case() { var task = Source.From(new[] {Src10(0), Src10(10), Src10(20), Src10(30)}) .MergeMany(4, s => s) .RunWith(ToSet, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(0, 40)); } [Fact] public void A_FlattenMerge_must_not_be_held_back_by_one_slow_stream() { var task = Source.From(new[] { Src10(0), Src10(10), Blocked, Src10(20), Src10(30) }) .MergeMany(3, s => s) .Take(40) .RunWith(ToSet, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(0, 40)); } [Fact] public void A_FlattenMerge_must_respect_breadth() { var task = Source.From(new[] { Src10(0), Src10(10), Src10(20), Blocked, Blocked, Src10(30) }) .MergeMany(3, s => s) .Take(40) .RunWith(ToSeq, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.Take(30).ShouldAllBeEquivalentTo(Enumerable.Range(0, 30)); task.Result.Drop(30).ShouldAllBeEquivalentTo(Enumerable.Range(30, 10)); } [Fact] public void A_FlattenMerge_must_propagate_early_failure_from_main_stream() { var ex = new TestException("buh"); var future = Source.Failed<Source<int, NotUsed>>(ex) .MergeMany(1, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_propage_late_failure_from_main_stream() { var ex = new TestException("buh"); var future = Source.Combine(Source.From(new[] {Blocked, Blocked}), Source.Failed<Source<int, NotUsed>>(ex), i => new Merge<Source<int, NotUsed>>(i)) .MergeMany(10, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_propagate_failure_from_map_function() { var ex = new TestException("buh"); var future = Source.From(Enumerable.Range(1, 3)) .MergeMany(10, x => { if (x == 3) throw ex; return Blocked; }) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_bubble_up_substream_exceptions() { var ex = new TestException("buh"); var future = Source.From(new[] { Blocked, Blocked, Source.Failed<int>(ex) }) .MergeMany(10, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_from_main_stream() { var p1 = TestPublisher.CreateProbe<int>(this); var p2 = TestPublisher.CreateProbe<int>(this); var ex = new TestException("buh"); var p = new TaskCompletionSource<Source<int, NotUsed>>(); Source.Combine( Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2)}), Source.FromTask(p.Task), i => new Merge<Source<int, NotUsed>>(i)) .MergeMany(5, x => x) .RunWith(Sink.First<int>(), Materializer); p1.ExpectRequest(); p2.ExpectRequest(); p.SetException(ex); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_from_substream() { var p1 = TestPublisher.CreateProbe<int>(this); var p2 = TestPublisher.CreateProbe<int>(this); var ex = new TestException("buh"); var p = new TaskCompletionSource<int>(); Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2), Source.FromTask(p.Task)}) .MergeMany(5, x => x) .RunWith(Sink.First<int>(), Materializer); p1.ExpectRequest(); p2.ExpectRequest(); p.SetException(ex); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_map_function() { var settings = ActorMaterializerSettings.Create(Sys).WithSyncProcessingLimit(1).WithInputBuffer(1, 1); var materializer = ActorMaterializer.Create(Sys, settings); var p = TestPublisher.CreateProbe<int>(this); var ex = new TestException("buh"); var latch = new TestLatch(); Source.From(Enumerable.Range(1, 3)).MergeMany(10, i => { if (i == 1) return Source.FromPublisher(p); latch.Ready(TimeSpan.FromSeconds(3)); throw ex; }).RunWith(Sink.First<int>(), materializer); p.ExpectRequest(); latch.CountDown(); p.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_being_cancelled() { var p1 = TestPublisher.CreateProbe<int>(this); var p2 = TestPublisher.CreateProbe<int>(this); var sink = Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2)}) .MergeMany(5, x => x) .RunWith(this.SinkProbe<int>(), Materializer); sink.Request(1); p1.ExpectRequest(); p2.ExpectRequest(); sink.Cancel(); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_work_with_many_concurrently_queued_events() { const int noOfSources = 100; var p = Source.From(Enumerable.Range(0, noOfSources).Select(i => Src10(10*i))) .MergeMany(int.MaxValue, x => x) .RunWith(this.SinkProbe<int>(), Materializer); p.EnsureSubscription(); p.ExpectNoMsg(TimeSpan.FromSeconds(1)); var elems = p.Within(TimeSpan.FromSeconds(1), () => Enumerable.Range(1, noOfSources * 10).Select(_ => p.RequestNext()).ToArray()); p.ExpectComplete(); elems.ShouldAllBeEquivalentTo(Enumerable.Range(0, noOfSources * 10)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// Represents a position within a <see cref="LargeArrayBuilder{T}"/>. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] internal readonly struct CopyPosition { /// <summary> /// Constructs a new <see cref="CopyPosition"/>. /// </summary> /// <param name="row">The index of the buffer to select.</param> /// <param name="column">The index within the buffer to select.</param> internal CopyPosition(int row, int column) { Debug.Assert(row >= 0); Debug.Assert(column >= 0); Row = row; Column = column; } /// <summary> /// Represents a position at the start of a <see cref="LargeArrayBuilder{T}"/>. /// </summary> public static CopyPosition Start => default(CopyPosition); /// <summary> /// The index of the buffer to select. /// </summary> internal int Row { get; } /// <summary> /// The index within the buffer to select. /// </summary> internal int Column { get; } /// <summary> /// If this position is at the end of the current buffer, returns the position /// at the start of the next buffer. Otherwise, returns this position. /// </summary> /// <param name="endColumn">The length of the current buffer.</param> public CopyPosition Normalize(int endColumn) { Debug.Assert(Column <= endColumn); return Column == endColumn ? new CopyPosition(Row + 1, 0) : this; } /// <summary> /// Gets a string suitable for display in the debugger. /// </summary> private string DebuggerDisplay => $"[{Row}, {Column}]"; } /// <summary> /// Helper type for building dynamically-sized arrays while minimizing allocations and copying. /// </summary> /// <typeparam name="T">The element type.</typeparam> internal struct LargeArrayBuilder<T> { private const int StartingCapacity = 4; private const int ResizeLimit = 8; private readonly int _maxCapacity; // The maximum capacity this builder can have. private T[] _first; // The first buffer we store items in. Resized until ResizeLimit. private ArrayBuilder<T[]> _buffers; // After ResizeLimit * 2, we store previous buffers we've filled out here. private T[] _current; // Current buffer we're reading into. If _count <= ResizeLimit, this is _first. private int _index; // Index into the current buffer. private int _count; // Count of all of the items in this builder. /// <summary> /// Constructs a new builder. /// </summary> /// <param name="initialize">Pass <c>true</c>.</param> public LargeArrayBuilder(bool initialize) : this(maxCapacity: int.MaxValue) { // This is a workaround for C# not having parameterless struct constructors yet. // Once it gets them, replace this with a parameterless constructor. Debug.Assert(initialize); } /// <summary> /// Constructs a new builder with the specified maximum capacity. /// </summary> /// <param name="maxCapacity">The maximum capacity this builder can have.</param> /// <remarks> /// Do not add more than <paramref name="maxCapacity"/> items to this builder. /// </remarks> public LargeArrayBuilder(int maxCapacity) : this() { Debug.Assert(maxCapacity >= 0); _first = _current = Array.Empty<T>(); _maxCapacity = maxCapacity; } /// <summary> /// Gets the number of items added to the builder. /// </summary> public int Count => _count; /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { Debug.Assert(_maxCapacity > _count); if (_index == _current.Length) { AllocateBuffer(); } _current[_index++] = item; _count++; } /// <summary> /// Adds a range of items to this builder. /// </summary> /// <param name="items">The sequence to add.</param> /// <remarks> /// It is the caller's responsibility to ensure that adding <paramref name="items"/> /// does not cause the builder to exceed its maximum capacity. /// </remarks> public void AddRange(IEnumerable<T> items) { Debug.Assert(items != null); using (IEnumerator<T> enumerator = items.GetEnumerator()) { T[] destination = _current; int index = _index; // Continuously read in items from the enumerator, updating _count // and _index when we run out of space. while (enumerator.MoveNext()) { if (index == destination.Length) { // No more space in this buffer. Resize. _count += index - _index; _index = index; AllocateBuffer(); destination = _current; index = _index; // May have been reset to 0 } destination[index++] = enumerator.Current; } // Final update to _count and _index. _count += index - _index; _index = index; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> public void CopyTo(T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array?.Length - arrayIndex >= count); for (int i = 0; count > 0; i++) { // Find the buffer we're copying from. T[] buffer = GetBuffer(index: i); // Copy until we satisfy count, or we reach the end of the buffer. int toCopy = Math.Min(count, buffer.Length); Array.Copy(buffer, 0, array, arrayIndex, toCopy); // Increment variables to that position. count -= toCopy; arrayIndex += toCopy; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="position">The position in this builder to start copying from.</param> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> /// <returns>The position in this builder that was copied up to.</returns> public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count) { Debug.Assert(array != null); Debug.Assert(arrayIndex >= 0); Debug.Assert(count > 0 && count <= Count); Debug.Assert(array.Length - arrayIndex >= count); // Go through each buffer, which contains one 'row' of items. // The index in each buffer is referred to as the 'column'. /* * Visual representation: * * C0 C1 C2 .. C31 .. C63 * R0: [0] [1] [2] .. [31] * R1: [32] [33] [34] .. [63] * R2: [64] [65] [66] .. [95] .. [127] */ int row = position.Row; int column = position.Column; T[] buffer = GetBuffer(row); int copied = CopyToCore(buffer, column); if (count == 0) { return new CopyPosition(row, column + copied).Normalize(buffer.Length); } do { buffer = GetBuffer(++row); copied = CopyToCore(buffer, 0); } while (count > 0); return new CopyPosition(row, copied).Normalize(buffer.Length); int CopyToCore(T[] sourceBuffer, int sourceIndex) { Debug.Assert(sourceBuffer.Length > sourceIndex); // Copy until we satisfy `count` or reach the end of the current buffer. int copyCount = Math.Min(sourceBuffer.Length - sourceIndex, count); Array.Copy(sourceBuffer, sourceIndex, array, arrayIndex, copyCount); arrayIndex += copyCount; count -= copyCount; return copyCount; } } /// <summary> /// Retrieves the buffer at the specified index. /// </summary> /// <param name="index">The index of the buffer.</param> public T[] GetBuffer(int index) { Debug.Assert(index >= 0 && index < _buffers.Count + 2); return index == 0 ? _first : index <= _buffers.Count ? _buffers[index - 1] : _current; } /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.NoInlining)] public void SlowAdd(T item) => Add(item); /// <summary> /// Creates an array from the contents of this builder. /// </summary> public T[] ToArray() { if (TryMove(out T[] array)) { // No resizing to do. return array; } array = new T[_count]; CopyTo(array, 0, _count); return array; } /// <summary> /// Attempts to transfer this builder into an array without copying. /// </summary> /// <param name="array">The transferred array, if the operation succeeded.</param> /// <returns><c>true</c> if the operation succeeded; otherwise, <c>false</c>.</returns> public bool TryMove(out T[] array) { array = _first; return _count == _first.Length; } private void AllocateBuffer() { // - On the first few adds, simply resize _first. // - When we pass ResizeLimit, allocate ResizeLimit elements for _current // and start reading into _current. Set _index to 0. // - When _current runs out of space, add it to _buffers and repeat the // above step, except with _current.Length * 2. // - Make sure we never pass _maxCapacity in all of the above steps. Debug.Assert((uint)_maxCapacity > (uint)_count); Debug.Assert(_index == _current.Length, $"{nameof(AllocateBuffer)} was called, but there's more space."); // If _count is int.MinValue, we want to go down the other path which will raise an exception. if ((uint)_count < (uint)ResizeLimit) { // We haven't passed ResizeLimit. Resize _first, copying over the previous items. Debug.Assert(_current == _first && _count == _first.Length); int nextCapacity = Math.Min(_count == 0 ? StartingCapacity : _count * 2, _maxCapacity); _current = new T[nextCapacity]; Array.Copy(_first, 0, _current, 0, _count); _first = _current; } else { Debug.Assert(_maxCapacity > ResizeLimit); Debug.Assert(_count == ResizeLimit ^ _current != _first); int nextCapacity; if (_count == ResizeLimit) { nextCapacity = ResizeLimit; } else { // Example scenario: Let's say _count == 64. // Then our buffers look like this: | 8 | 8 | 16 | 32 | // As you can see, our count will be just double the last buffer. // Now, say _maxCapacity is 100. We will find the right amount to allocate by // doing min(64, 100 - 64). The lhs represents double the last buffer, // the rhs the limit minus the amount we've already allocated. Debug.Assert(_count >= ResizeLimit * 2); Debug.Assert(_count == _current.Length * 2); _buffers.Add(_current); nextCapacity = Math.Min(_count, _maxCapacity - _count); } _current = new T[nextCapacity]; _index = 0; } } } }
/** * 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. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.Net; using System.Threading; using System.Threading.Tasks; using Thrift.Protocol; using Thrift.Transport; namespace Thrift.Server { /// <summary> /// Server that uses C# built-in ThreadPool to spawn threads when handling requests /// <para> /// The Max/Min threads count settings see <see cref="https://github.com/dotnet/cli/blob/rel/1.0.0/Documentation/specs/runtime-configuration-file.md"/> /// </para> /// </summary> public class TThreadPoolServer : TServer { // about thread count in .Net Core 1.x //https://github.com/dotnet/cli/blob/rel/1.0.0/Documentation/specs/runtime-configuration-file.md private volatile bool stop = false; public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport) : this(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DefaultLogDelegate) { } public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) : this(processor, serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), logDelegate) { } public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(processor, serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, DefaultLogDelegate) { } public TThreadPoolServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, LogDelegate logDel) : base(processor, serverTransport, inputTransportFactory, outputTransportFactory, inputProtocolFactory, outputProtocolFactory, logDel) { } /// <summary> /// Use new ThreadPool thread for each new client connection /// </summary> public override void Serve() { try { serverTransport.Listen(); } catch (TTransportException ttx) { logDelegate("Error, could not listen on ServerTransport: " + ttx); return; } //Fire the preServe server event when server is up but before any client connections if (serverEventHandler != null) serverEventHandler.preServe(); while (!stop) { int failureCount = 0; try { TTransport client = serverTransport.Accept(); ThreadPool.QueueUserWorkItem(this.Execute, client); } catch (TTransportException ttx) { if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) { ++failureCount; logDelegate(ttx.ToString()); } } catch (Exception ex) { logDelegate($"serverTransport.Accept exception: {ex.ToString()}"); } } if (stop) { try { serverTransport.Close(); } catch (TTransportException ttx) { logDelegate("TServerTransport failed on close: " + ttx.Message); } stop = false; } } /// <summary> /// Loops on processing a client forever /// threadContext will be a TTransport instance /// </summary> /// <param name="threadContext"></param> private void Execute(Object threadContext) { TTransport client = (TTransport)threadContext; TProcessor processor = this.processor; TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; Object connectionContext = null; try { inputTransport = inputTransportFactory.GetTransport(client); outputTransport = outputTransportFactory.GetTransport(client); inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); //Recover event handler (if any) and fire createContext server event when a client connects if (serverEventHandler != null) connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); //Process client requests until client disconnects while (!stop) { if (!inputTransport.Peek()) break; //Fire processContext server event //N.B. This is the pattern implemented in C++ and the event fires provisionally. //That is to say it may be many minutes between the event firing and the client request //actually arriving or the client may hang up without ever makeing a request. if (serverEventHandler != null) serverEventHandler.processContext(connectionContext, inputTransport); //Process client request (blocks until transport is readable) if (!processor.Process(inputProtocol, outputProtocol)) break; } } catch (TTransportException) { //Usually a client disconnect, expected } catch (Exception x) { //Unexpected logDelegate("Error: " + x); } //Fire deleteContext server event after client disconnects if (serverEventHandler != null) serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); //Close transports if (inputTransport != null) inputTransport.Close(); if (outputTransport != null) outputTransport.Close(); } public override void Stop() { stop = true; serverTransport.Close(); } } }
// DataViewTest.cs - Nunit Test Cases for for testing the DataView // class // Authors: // Punit Kumar Todi ( [email protected] ) // Patrick Kalkman [email protected] // Umadevi S ([email protected]) // Atsushi Enomoto ([email protected]) // // (C) 2003 Patrick Kalkman // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data; using System.ComponentModel; using System.IO; namespace MonoTests.System.Data { [TestFixture] public class DataViewTest : Assertion { DataTable dataTable; DataView dataView; Random rndm; int seed, rowCount; ListChangedEventArgs listChangedArgs; TextWriter eventWriter; [SetUp] public void GetReady () { dataTable = new DataTable ("itemTable"); DataColumn dc1 = new DataColumn ("itemId"); DataColumn dc2 = new DataColumn ("itemName"); DataColumn dc3 = new DataColumn ("itemPrice"); DataColumn dc4 = new DataColumn ("itemCategory"); dataTable.Columns.Add (dc1); dataTable.Columns.Add (dc2); dataTable.Columns.Add (dc3); dataTable.Columns.Add (dc4); DataRow dr; seed = 123; rowCount = 5; rndm = new Random (seed); for (int i = 1; i <= rowCount; i++) { dr = dataTable.NewRow (); dr["itemId"] = "item " + i; dr["itemName"] = "name " + rndm.Next (); dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000); dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1); dataTable.Rows.Add (dr); } dataTable.AcceptChanges (); dataView = new DataView (dataTable); dataView.ListChanged += new ListChangedEventHandler (OnListChanged); listChangedArgs = null; } protected void OnListChanged (object sender, ListChangedEventArgs args) { listChangedArgs = args; // for debugging /*Console.WriteLine("EventType :: " + listChangedArgs.ListChangedType + " oldIndex :: " + listChangedArgs.OldIndex + " NewIndex :: " + listChangedArgs.NewIndex);*/ } private void PrintTableOrView (DataTable t, string label) { Console.WriteLine ("\n" + label); for (int i = 0; i<t.Rows.Count; i++){ foreach (DataColumn dc in t.Columns) Console.Write (t.Rows [i][dc] + "\t"); Console.WriteLine (""); } Console.WriteLine (); } private void PrintTableOrView (DataView dv, string label) { Console.WriteLine ("\n" + label); Console.WriteLine ("Sort Key :: " + dv.Sort); for (int i = 0; i < dv.Count; i++) { foreach (DataColumn dc in dv.Table.Columns) Console.Write (dv [i].Row [dc] + "\t"); Console.WriteLine (""); } Console.WriteLine (); } [TearDown] public void Clean () { dataTable = null; dataView = null; } [Test] public void DataView () { DataView dv1,dv2,dv3; dv1 = new DataView (); // AssertEquals ("test#01",null,dv1.Table); AssertEquals ("test#02",true,dv1.AllowNew); AssertEquals ("test#03",true,dv1.AllowEdit); AssertEquals ("test#04",true,dv1.AllowDelete); AssertEquals ("test#05",false,dv1.ApplyDefaultSort); AssertEquals ("test#06",string.Empty,dv1.RowFilter); AssertEquals ("test#07",DataViewRowState.CurrentRows,dv1.RowStateFilter); AssertEquals ("test#08",string.Empty,dv1.Sort); dv2 = new DataView (dataTable); AssertEquals ("test#09","itemTable",dv2.Table.TableName); AssertEquals ("test#10",string.Empty,dv2.Sort); AssertEquals ("test#11",false,dv2.ApplyDefaultSort); AssertEquals ("test#12",dataTable.Rows[0],dv2[0].Row); dv3 = new DataView (dataTable,"","itemId DESC",DataViewRowState.CurrentRows); AssertEquals ("test#13","",dv3.RowFilter); AssertEquals ("test#14","itemId DESC",dv3.Sort); AssertEquals ("test#15",DataViewRowState.CurrentRows,dv3.RowStateFilter); //AssertEquals ("test#16",dataTable.Rows.[(dataTable.Rows.Count-1)],dv3[0]); } [Test] public void TestValue () { DataView TestView = new DataView (dataTable); Assertion.AssertEquals ("Dv #1", "item 1", TestView [0]["itemId"]); } [Test] public void TestCount () { DataView TestView = new DataView (dataTable); Assertion.AssertEquals ("Dv #3", 5, TestView.Count); } [Test] public void AllowNew () { AssertEquals ("test#01",true,dataView.AllowNew); } [Test] public void ApplyDefaultSort () { UniqueConstraint uc = new UniqueConstraint (dataTable.Columns["itemId"]); dataTable.Constraints.Add (uc); dataView.ApplyDefaultSort = true; // dataView.Sort = "itemName"; // AssertEquals ("test#01","item 1",dataView[0]["itemId"]); AssertEquals ("test#02",ListChangedType.Reset,listChangedArgs.ListChangedType); // UnComment the line below to see if dataView is sorted // PrintTableOrView (dataView,"* OnApplyDefaultSort"); } [Test] public void RowStateFilter () { dataView.RowStateFilter = DataViewRowState.Deleted; AssertEquals ("test#01",ListChangedType.Reset,listChangedArgs.ListChangedType); } [Test] public void RowStateFilter_2 () { DataSet dataset = new DataSet ("new"); DataTable dt = new DataTable ("table1"); dataset.Tables.Add (dt); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Rows.Add (new object [] {1,1}); dt.Rows.Add (new object [] {1,2}); dt.Rows.Add (new object [] {1,3}); dataset.AcceptChanges (); DataView dataView = new DataView (dataset.Tables [0]); // 'new' table in this sample contains 6 records dataView.AllowEdit = true; dataView.AllowDelete = true; string v; // Editing the row dataView [0] ["col1"] = -1; dataView.RowStateFilter = DataViewRowState.ModifiedOriginal; v = dataView [0] [0].ToString (); AssertEquals ("ModifiedOriginal.Count", 1, dataView.Count); AssertEquals ("ModifiedOriginal.Value", "1", v); // Deleting the row dataView.Delete (0); dataView.RowStateFilter = DataViewRowState.Deleted; v = dataView [0] [0].ToString (); AssertEquals ("Deleted.Count", 1, dataView.Count); AssertEquals ("Deleted.Value", "1", v); } [Test] public void Sort () { dataView.Sort = "itemName DESC"; AssertEquals ("test#01",ListChangedType.Reset,listChangedArgs.ListChangedType); // UnComment the line below to see if dataView is sorted // PrintTableOrView (dataView); } [Test] [ExpectedException(typeof(DataException))] public void AddNew_1 () { dataView.AllowNew = false; DataRowView drv = dataView.AddNew (); } [Test] public void AddNew_2 () { dataView.AllowNew = true; DataRowView drv = dataView.AddNew (); AssertEquals ("test#01",ListChangedType.ItemAdded,listChangedArgs.ListChangedType); AssertEquals ("test#02",drv["itemName"],dataView [dataView.Count - 1]["itemName"]); listChangedArgs = null; drv["itemId"] = "item " + 1001; drv["itemName"] = "name " + rndm.Next(); drv["itemPrice"] = "Rs. " + (rndm.Next() % 1000); drv["itemCategory"] = "Cat " + ((rndm.Next() % 10) + 1); // Actually no events are arisen when items are set. AssertNull ("test#03", listChangedArgs); } [Test] [Ignore("Test code not implemented")] public void BeginInit () { //TODO } [Test] [ExpectedException(typeof(ArgumentException))] public void Find_1 () { /* since the sort key is not specified. Must raise a ArgumentException */ int sIndex = dataView.Find ("abc"); } [Test] public void Find_2 () { int randInt; DataRowView drv; randInt = rndm.Next () % rowCount; dataView.Sort = "itemId"; drv = dataView [randInt]; AssertEquals ("test#01",randInt,dataView.Find (drv ["itemId"])); dataView.Sort = "itemId DESC"; drv = dataView [randInt]; AssertEquals ("test#02",randInt,dataView.Find (drv ["itemId"])); dataView.Sort = "itemId, itemName"; drv = dataView [randInt]; object [] keys = new object [2]; keys [0] = drv ["itemId"]; keys [1] = drv ["itemName"]; AssertEquals ("test#03",randInt,dataView.Find (keys)); dataView.Sort = "itemId"; AssertEquals ("test#04",-1,dataView.Find("no item")); } [Test] [ExpectedException (typeof (ArgumentException))] public void Find_3 () { dataView.Sort = "itemID, itemName"; /* expecting order key count mismatch */ dataView.Find ("itemValue"); } [Test] [Ignore("Test code not implemented")] public void GetEnumerator () { //TODO } [Test] public void ToStringTest () { AssertEquals ("test#01","System.Data.DataView",dataView.ToString()); } [Test] public void TestingEventHandling () { dataView.Sort = "itemId"; DataRow dr; dr = dataTable.NewRow (); dr ["itemId"] = "item 0"; dr ["itemName"] = "name " + rndm.Next (); dr ["itemPrice"] = "Rs. " + (rndm.Next () % 1000); dr ["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1); dataTable.Rows.Add(dr); //PrintTableOrView(dataView, "ItemAdded"); AssertEquals ("test#01",ListChangedType.ItemAdded,listChangedArgs.ListChangedType); listChangedArgs = null; dr ["itemId"] = "aitem 0"; // PrintTableOrView(dataView, "ItemChanged"); AssertEquals ("test#02",ListChangedType.ItemChanged,listChangedArgs.ListChangedType); listChangedArgs = null; dr ["itemId"] = "zitem 0"; // PrintTableOrView(dataView, "ItemMoved"); AssertEquals ("test#03",ListChangedType.ItemMoved,listChangedArgs.ListChangedType); listChangedArgs = null; dataTable.Rows.Remove (dr); // PrintTableOrView(dataView, "ItemDeleted"); AssertEquals ("test#04",ListChangedType.ItemDeleted,listChangedArgs.ListChangedType); listChangedArgs = null; DataColumn dc5 = new DataColumn ("itemDesc"); dataTable.Columns.Add (dc5); // PrintTableOrView(dataView, "PropertyDescriptorAdded"); AssertEquals ("test#05",ListChangedType.PropertyDescriptorAdded,listChangedArgs.ListChangedType); listChangedArgs = null; dc5.ColumnName = "itemDescription"; // PrintTableOrView(dataView, "PropertyDescriptorChanged"); // AssertEquals ("test#06",ListChangedType.PropertyDescriptorChanged,listChangedArgs.ListChangedType); listChangedArgs = null; dataTable.Columns.Remove (dc5); // PrintTableOrView(dataView, "PropertyDescriptorDeleted"); AssertEquals ("test#07",ListChangedType.PropertyDescriptorDeleted,listChangedArgs.ListChangedType); } [Test] public void TestFindRows () { DataView TestView = new DataView (dataTable); TestView.Sort = "itemId"; DataRowView[] Result = TestView.FindRows ("item 3"); Assertion.AssertEquals ("Dv #1", 1, Result.Length); Assertion.AssertEquals ("Dv #2", "item 3", Result [0]["itemId"]); } [Test] [ExpectedException (typeof (ArgumentException))] public void FindRowsWithoutSort () { DataTable dt = new DataTable ("table"); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Columns.Add ("col3"); dt.Rows.Add (new object [] {1,2,3}); dt.Rows.Add (new object [] {4,5,6}); dt.Rows.Add (new object [] {4,7,8}); dt.Rows.Add (new object [] {5,7,8}); dt.Rows.Add (new object [] {4,8,9}); DataView dv = new DataView (dt); dv.Find (1); } [Test] [ExpectedException (typeof (ArgumentException))] public void FindRowsInconsistentKeyLength () { DataTable dt = new DataTable ("table"); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Columns.Add ("col3"); dt.Rows.Add (new object [] {1,2,3}); dt.Rows.Add (new object [] {4,5,6}); dt.Rows.Add (new object [] {4,7,8}); dt.Rows.Add (new object [] {5,7,8}); dt.Rows.Add (new object [] {4,8,9}); DataView dv = new DataView (dt, null, "col1", DataViewRowState.CurrentRows); dv.FindRows (new object [] {1, 2, 3}); } [Test] [ExpectedException (typeof (DeletedRowInaccessibleException))] public void TestDelete () { DataView TestView = new DataView (dataTable); TestView.Delete (0); DataRow r = TestView.Table.Rows [0]; Assertion.Assert ("Dv #1", !(r ["itemId"] == "item 1")); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void TestDeleteOutOfBounds () { DataView TestView = new DataView (dataTable); TestView.Delete (100); } [Test] [ExpectedException (typeof (DataException))] public void TestDeleteNotAllowed () { DataView TestView = new DataView (dataTable); TestView.AllowDelete = false; TestView.Delete (0); } [Test] [ExpectedException (typeof (DataException))] public void TestDeleteClosed () { DataView TestView = new DataView (dataTable); TestView.Dispose (); // Close the table TestView.Delete (0); } [Test] // based on bug #74631 public void TestDeleteAndCount () { DataSet dataset = new DataSet ("new"); DataTable dt = new DataTable ("table1"); dataset.Tables.Add (dt); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Rows.Add (new object []{1,1}); dt.Rows.Add (new object []{1,2}); dt.Rows.Add (new object []{1,3}); DataView dataView = new DataView (dataset.Tables[0]); AssertEquals ("before delete", 3, dataView.Count); dataView.AllowDelete = true; // Deleting the first row dataView.Delete (0); AssertEquals ("before delete", 2, dataView.Count); } [Test] public void ListChangeOnSetItem () { DataTable dt = new DataTable ("table"); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Columns.Add ("col3"); dt.Rows.Add (new object [] {1, 2, 3}); dt.AcceptChanges (); DataView dv = new DataView (dt); dv.ListChanged += new ListChangedEventHandler (OnChange); dv [0] ["col1"] = 4; } ListChangedEventArgs ListChangeArgOnSetItem; void OnChange (object o, ListChangedEventArgs e) { if (ListChangeArgOnSetItem != null) throw new Exception ("The event is already fired."); ListChangeArgOnSetItem = e; } [Test] [NUnit.Framework.Category ("NotWorking")] public void CancelEditAndEvents () { string reference = " =====ItemAdded:3 ------4 =====ItemAdded:3 =====ItemAdded:4 ------5 =====ItemAdded:4 =====ItemAdded:5 ------6 =====ItemDeleted:5 ------5 =====ItemAdded:5"; eventWriter = new StringWriter (); DataTable dt = new DataTable (); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); dt.Columns.Add ("col3"); dt.Rows.Add (new object [] {1,2,3}); dt.Rows.Add (new object [] {1,2,3}); dt.Rows.Add (new object [] {1,2,3}); DataView dv = new DataView (dt); dv.ListChanged += new ListChangedEventHandler (ListChanged); DataRowView a1 = dv.AddNew (); eventWriter.Write (" ------" + dv.Count); // I wonder why but MS fires another event here. a1 = dv.AddNew (); eventWriter.Write (" ------" + dv.Count); // I wonder why but MS fires another event here. DataRowView a2 = dv.AddNew (); eventWriter.Write (" ------" + dv.Count); a2.CancelEdit (); eventWriter.Write (" ------" + dv.Count); DataRowView a3 = dv.AddNew (); AssertEquals (reference, eventWriter.ToString ()); } private void ListChanged (object o, ListChangedEventArgs e) { eventWriter.Write (" =====" + e.ListChangedType + ":" + e.NewIndex); } [Test] public void ComplexEventSequence1 () { string result = @"setting table... ---- OnListChanged PropertyDescriptorChanged,0,0 ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 table was set. ---- OnListChanged PropertyDescriptorAdded,0,0 col1 added. ---- OnListChanged PropertyDescriptorAdded,0,0 col2 added. ---- OnListChanged PropertyDescriptorAdded,0,0 col3 added. uniq added. ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 sort changed. ---- OnListChanged PropertyDescriptorDeleted,0,0 col3 removed. ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 rowfilter changed. ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 rowstatefilter changed. ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 rowstatefilter changed. ---- OnListChanged ItemAdded,0,-1 added row to Rows. ---- OnListChanged ItemAdded,0,-1 added row to Rows. ---- OnListChanged ItemAdded,0,-1 added row to Rows. ---- OnListChanged ItemAdded,3,-1 AddNew() invoked. 4 ---- OnListChanged ItemDeleted,3,-1 ---- OnListChanged ItemMoved,-2147483648,3 EndEdit() invoked. 3 ---- OnListChanged ItemMoved,0,-2147483648 value changed to appear. 4 ---- OnListChanged ItemMoved,3,0 value moved. 4 ---- OnListChanged ItemMoved,1,3 value moved again. 4 ---- OnListChanged PropertyDescriptorChanged,0,0 ----- UpdateIndex : True ---- OnListChanged Reset,-1,-1 table changed. "; eventWriter = new StringWriter (); DataTable dt = new DataTable ("table"); ComplexEventSequence1View dv = new ComplexEventSequence1View (dt, eventWriter); dt.Columns.Add ("col1"); eventWriter.WriteLine (" col1 added."); dt.Columns.Add ("col2"); eventWriter.WriteLine (" col2 added."); dt.Columns.Add ("col3"); eventWriter.WriteLine (" col3 added."); dt.Constraints.Add (new UniqueConstraint (dt.Columns [0])); eventWriter.WriteLine (" uniq added."); dv.Sort = "col2"; eventWriter.WriteLine (" sort changed."); dt.Columns.Remove ("col3"); eventWriter.WriteLine (" col3 removed."); dv.RowFilter = "col1 <> 0"; eventWriter.WriteLine (" rowfilter changed."); dv.RowStateFilter = DataViewRowState.Deleted; eventWriter.WriteLine (" rowstatefilter changed."); // FIXME: should be also tested. // dv.ApplyDefaultSort = true; // eventWriter.WriteLine (" apply default sort changed."); dv.RowStateFilter = DataViewRowState.CurrentRows; eventWriter.WriteLine (" rowstatefilter changed."); dt.Rows.Add (new object [] {1, 3}); eventWriter.WriteLine (" added row to Rows."); dt.Rows.Add (new object [] {2, 2}); eventWriter.WriteLine (" added row to Rows."); dt.Rows.Add (new object [] {3, 1}); eventWriter.WriteLine (" added row to Rows."); DataRowView drv = dv.AddNew (); eventWriter.WriteLine (" AddNew() invoked."); eventWriter.WriteLine (dv.Count); drv [0] = 0; drv.EndEdit (); eventWriter.WriteLine (" EndEdit() invoked."); eventWriter.WriteLine (dv.Count); dt.Rows [dt.Rows.Count - 1] [0] = 4; eventWriter.WriteLine (" value changed to appear."); eventWriter.WriteLine (dv.Count); dt.Rows [dt.Rows.Count - 1] [1] = 4; eventWriter.WriteLine (" value moved."); eventWriter.WriteLine (dv.Count); dt.Rows [dt.Rows.Count - 1] [1] = 1.5; eventWriter.WriteLine (" value moved again."); eventWriter.WriteLine (dv.Count); dv.Table = new DataTable ("table2"); eventWriter.WriteLine ("table changed."); AssertEquals (result, eventWriter.ToString ().Replace ("\r\n", "\n")); } public class ComplexEventSequence1View : DataView { TextWriter w; public ComplexEventSequence1View (DataTable dt, TextWriter w) : base () { this.w = w; w.WriteLine ("setting table..."); Table = dt; w.WriteLine ("table was set."); } protected override void OnListChanged (ListChangedEventArgs e) { if (w != null) w.WriteLine ("---- OnListChanged " + e.ListChangedType + "," + e.NewIndex + "," + e.OldIndex); base.OnListChanged (e); } protected override void UpdateIndex (bool force) { if (w != null) w.WriteLine ("----- UpdateIndex : " + force); base.UpdateIndex (force); } } } }
using System; using System.ServiceModel; using System.ServiceModel.Description; using System.ComponentModel; namespace ACorns.WCF.DynamicClientProxy { /// <summary> /// Class that can be used with PolicyInjection. Dynamically generated classes will inherit from this class. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class WCFReusableClientProxy<T> : IClientBase where T : class { protected T cachedProxy; private readonly string configName; protected volatile bool manuallyClosed; private static readonly Type _instanceType; static WCFReusableClientProxy() { _instanceType = WCFClientProxy<T>.GetInstanceType(); } protected WCFReusableClientProxy(string configName) { this.configName = configName; } /// <summary> /// Called to retrieve a cached instance of the proxy. /// </summary> protected T Proxy { get { AssureProxy(); return cachedProxy; } } protected string ConfigName { get { return configName; } } /// <summary> /// Close the proxy because it was fauled. /// </summary> protected void CloseProxyBecauseOfException() { if (cachedProxy != null) { ICommunicationObject wcfProxy = cachedProxy as ICommunicationObject; try { if (wcfProxy != null) { if (wcfProxy.State != CommunicationState.Faulted) { wcfProxy.Close(); } else { wcfProxy.Abort(); } } } catch (CommunicationException) { if (wcfProxy != null) wcfProxy.Abort(); } catch (TimeoutException) { if (wcfProxy != null) wcfProxy.Abort(); } catch { if (wcfProxy != null) wcfProxy.Abort(); throw; } finally { cachedProxy = null; } } } /// <summary> /// Create a new proxy if there is none already in use. /// If the previous proxy was faulted, it will be nulled and a new proxy is created /// </summary> protected void AssureProxy() { if (manuallyClosed) { throw new ObjectDisposedException("This proxy was already closed."); } if (cachedProxy == null) { cachedProxy = CreateProxyInstance(); if (ProxyCreated != null) { ProxyCreated(this); } } } protected virtual T CreateProxyInstance() { T instance = (T) Activator.CreateInstance(_instanceType, new object[] {configName}); return instance; } #region IClientBase Members public event ProxyCreatedHandler ProxyCreated; public virtual ClientCredentials ClientCredentials { get { return (Proxy as ClientBase<T>).ClientCredentials; } } public virtual ServiceEndpoint CurrentEndpoint { get { if (manuallyClosed) return null; else { if (cachedProxy == null) return null; else return (cachedProxy as ClientBase<T>).Endpoint; } } } public virtual ServiceEndpoint Endpoint { get { if (manuallyClosed) return null; else return (Proxy as ClientBase<T>).Endpoint; } } public virtual IClientChannel InnerChannel { get { return (Proxy as ClientBase<T>).InnerChannel; } } public virtual CommunicationState State { get { if (cachedProxy != null) { return (cachedProxy as ICommunicationObject).State; } else { return CommunicationState.Closed; } } } public virtual void Abort() { try { if (cachedProxy != null) { (cachedProxy as ICommunicationObject).Abort(); } } finally { CloseProxyBecauseOfException(); } } public virtual void Close() { try { if (cachedProxy != null) { (cachedProxy as ICommunicationObject).Close(); } manuallyClosed = true; } finally { CloseProxyBecauseOfException(); } } public virtual void Open() { try { (Proxy as ICommunicationObject).Open(); return; } catch { CloseProxyBecauseOfException(); throw; } } public object Tag { get; set; } #endregion public void Dispose() { try { CloseProxyBecauseOfException(); } catch { // no throw } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Protos.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Messages { /// <summary>Holder for reflection information generated from Protos.proto</summary> public static partial class ProtosReflection { #region Descriptor /// <summary>File descriptor for Protos.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ProtosReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgxQcm90b3MucHJvdG8SCG1lc3NhZ2VzGhhQcm90by5BY3Rvci9Qcm90b3Mu", "cHJvdG8iDgoMSGVsbG9SZXF1ZXN0IiAKDUhlbGxvUmVzcG9uc2USDwoHTWVz", "c2FnZRgBIAEoCUILqgIITWVzc2FnZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Proto.ProtosReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Messages.HelloRequest), global::Messages.HelloRequest.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Messages.HelloResponse), global::Messages.HelloResponse.Parser, new[]{ "Message" }, null, null, null) })); } #endregion } #region Messages public sealed partial class HelloRequest : pb::IMessage<HelloRequest> { private static readonly pb::MessageParser<HelloRequest> _parser = new pb::MessageParser<HelloRequest>(() => new HelloRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HelloRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloRequest(HelloRequest other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloRequest Clone() { return new HelloRequest(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HelloRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HelloRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HelloRequest other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } public sealed partial class HelloResponse : pb::IMessage<HelloResponse> { private static readonly pb::MessageParser<HelloResponse> _parser = new pb::MessageParser<HelloResponse>(() => new HelloResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HelloResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Messages.ProtosReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloResponse(HelloResponse other) : this() { message_ = other.message_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HelloResponse Clone() { return new HelloResponse(this); } /// <summary>Field number for the "Message" field.</summary> public const int MessageFieldNumber = 1; private string message_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HelloResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HelloResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Message != other.Message) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Message.Length != 0) hash ^= Message.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Message.Length != 0) { output.WriteRawTag(10); output.WriteString(Message); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HelloResponse other) { if (other == null) { return; } if (other.Message.Length != 0) { Message = other.Message; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Message = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Simulation; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteSimulationConnectorModule")] public class RemoteSimulationConnectorModule : ISharedRegionModule, ISimulationService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool initialized = false; protected bool m_enabled = false; protected Scene m_aScene; // RemoteSimulationConnector does not care about local regions; it delegates that to the Local module protected LocalSimulationConnectorModule m_localBackend; protected SimulationServiceConnector m_remoteConnector; protected bool m_safemode; #region Region Module interface public virtual void Initialise(IConfigSource configSource) { IConfig moduleConfig = configSource.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("SimulationServices", ""); if (name == Name) { m_localBackend = new LocalSimulationConnectorModule(); m_localBackend.InitialiseService(configSource); m_remoteConnector = new SimulationServiceConnector(); m_enabled = true; m_log.Info("[REMOTE SIMULATION CONNECTOR]: Remote simulation enabled."); } } } public virtual void PostInitialise() { } public virtual void Close() { } public void AddRegion(Scene scene) { if (!m_enabled) return; if (!initialized) { InitOnce(scene); initialized = true; } InitEach(scene); } public void RemoveRegion(Scene scene) { if (m_enabled) { m_localBackend.RemoveScene(scene); scene.UnregisterModuleInterface<ISimulationService>(this); } } public void RegionLoaded(Scene scene) { if (!m_enabled) return; } public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "RemoteSimulationConnectorModule"; } } protected virtual void InitEach(Scene scene) { m_localBackend.Init(scene); scene.RegisterModuleInterface<ISimulationService>(this); } protected virtual void InitOnce(Scene scene) { m_aScene = scene; //m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService); } #endregion #region ISimulationService public IScene GetScene(UUID regionId) { return m_localBackend.GetScene(regionId); } public ISimulationService GetInnerService() { return m_localBackend; } /** * Agent-related communications */ public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason) { if (destination == null) { reason = "Given destination was null"; m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent was given a null destination"); return false; } // Try local first if (m_localBackend.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out reason)) return true; // else do the remote thing if (!m_localBackend.IsLocalRegion(destination.RegionID)) { return m_remoteConnector.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out reason); } return false; } public bool UpdateAgent(GridRegion destination, AgentData cAgentData, EntityTransferContext ctx) { if (destination == null) return false; // Try local first if (m_localBackend.IsLocalRegion(destination.RegionID)) return m_localBackend.UpdateAgent(destination, cAgentData, ctx); return m_remoteConnector.UpdateAgent(destination, cAgentData, ctx); } public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData) { if (destination == null) return false; // Try local first if (m_localBackend.IsLocalRegion(destination.RegionID)) return m_localBackend.UpdateAgent(destination, cAgentData); return m_remoteConnector.UpdateAgent(destination, cAgentData); } public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> features, EntityTransferContext ctx, out string reason) { reason = "Communications failure"; if (destination == null) return false; // Try local first if (m_localBackend.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason)) return true; // else do the remote thing if (!m_localBackend.IsLocalRegion(destination.RegionID)) return m_remoteConnector.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason); return false; } public bool ReleaseAgent(UUID origin, UUID id, string uri) { // Try local first if (m_localBackend.ReleaseAgent(origin, id, uri)) return true; // else do the remote thing if (!m_localBackend.IsLocalRegion(origin)) return m_remoteConnector.ReleaseAgent(origin, id, uri); return false; } public bool CloseAgent(GridRegion destination, UUID id, string auth_token) { if (destination == null) return false; // Try local first if (m_localBackend.CloseAgent(destination, id, auth_token)) return true; // else do the remote thing if (!m_localBackend.IsLocalRegion(destination.RegionID)) return m_remoteConnector.CloseAgent(destination, id, auth_token); return false; } /** * Object-related communications */ public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall) { if (destination == null) return false; // Try local first if (m_localBackend.CreateObject(destination, newPosition, sog, isLocalCall)) { //m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded"); return true; } // else do the remote thing if (!m_localBackend.IsLocalRegion(destination.RegionID)) return m_remoteConnector.CreateObject(destination, newPosition, sog, isLocalCall); return false; } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Wim { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security.AccessControl; using System.Text.RegularExpressions; /// <summary> /// Provides access to the file system within a WIM file image. /// </summary> public class WimFileSystem : ReadOnlyDiscFileSystem, IWindowsFileSystem { private WimFile _file; private List<RawSecurityDescriptor> _securityDescriptors; private Stream _metaDataStream; private ObjectCache<long, List<DirectoryEntry>> _dirCache; private long _rootDirPos; internal WimFileSystem(WimFile file, int index) { _file = file; ShortResourceHeader metaDataFileInfo = _file.LocateImage(index); if (metaDataFileInfo == null) { throw new ArgumentException("No such image: " + index, "index"); } _metaDataStream = _file.OpenResourceStream(metaDataFileInfo); ReadSecurityDescriptors(); _dirCache = new ObjectCache<long, List<DirectoryEntry>>(); } /// <summary> /// Provides a friendly description of the file system type. /// </summary> public override string FriendlyName { get { return "Microsoft WIM"; } } /// <summary> /// Gets the security descriptor associated with the file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The security descriptor.</returns> public RawSecurityDescriptor GetSecurity(string path) { uint id = GetEntry(path).SecurityId; if (id == uint.MaxValue) { return null; } else if (id >= 0 && id < _securityDescriptors.Count) { return _securityDescriptors[(int)id]; } else { // What if there is no descriptor? throw new NotImplementedException(); } } /// <summary> /// Sets the security descriptor associated with the file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="securityDescriptor">The new security descriptor.</param> public void SetSecurity(string path, RawSecurityDescriptor securityDescriptor) { throw new NotSupportedException(); } /// <summary> /// Gets the reparse point data associated with a file or directory. /// </summary> /// <param name="path">The file to query.</param> /// <returns>The reparse point information.</returns> public ReparsePoint GetReparsePoint(string path) { DirectoryEntry dirEntry = GetEntry(path); ShortResourceHeader hdr = _file.LocateResource(dirEntry.Hash); if (hdr == null) { throw new IOException("No reparse point"); } using (Stream s = _file.OpenResourceStream(hdr)) { byte[] buffer = new byte[s.Length]; s.Read(buffer, 0, buffer.Length); return new ReparsePoint((int)dirEntry.ReparseTag, buffer); } } /// <summary> /// Sets the reparse point data on a file or directory. /// </summary> /// <param name="path">The file to set the reparse point on.</param> /// <param name="reparsePoint">The new reparse point.</param> public void SetReparsePoint(string path, ReparsePoint reparsePoint) { throw new NotSupportedException(); } /// <summary> /// Removes a reparse point from a file or directory, without deleting the file or directory. /// </summary> /// <param name="path">The path to the file or directory to remove the reparse point from.</param> public void RemoveReparsePoint(string path) { throw new NotSupportedException(); } /// <summary> /// Gets the short name for a given path. /// </summary> /// <param name="path">The path to convert.</param> /// <returns>The short name.</returns> /// <remarks> /// This method only gets the short name for the final part of the path, to /// convert a complete path, call this method repeatedly, once for each path /// segment. If there is no short name for the given path,<c>null</c> is /// returned. /// </remarks> public string GetShortName(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.ShortName; } /// <summary> /// Sets the short name for a given file or directory. /// </summary> /// <param name="path">The full path to the file or directory to change.</param> /// <param name="shortName">The shortName, which should not include a path.</param> public void SetShortName(string path, string shortName) { throw new NotSupportedException(); } /// <summary> /// Gets the standard file information for a file. /// </summary> /// <param name="path">The full path to the file or directory to query.</param> /// <returns>The standard file information.</returns> public WindowsFileInformation GetFileStandardInformation(string path) { DirectoryEntry dirEntry = GetEntry(path); return new WindowsFileInformation { CreationTime = DateTime.FromFileTimeUtc(dirEntry.CreationTime), LastAccessTime = DateTime.FromFileTimeUtc(dirEntry.LastAccessTime), ChangeTime = DateTime.FromFileTimeUtc(Math.Max(dirEntry.LastWriteTime, Math.Max(dirEntry.CreationTime, dirEntry.LastAccessTime))), LastWriteTime = DateTime.FromFileTimeUtc(dirEntry.LastWriteTime), FileAttributes = dirEntry.Attributes }; } /// <summary> /// Sets the standard file information for a file. /// </summary> /// <param name="path">The full path to the file or directory to query.</param> /// <param name="info">The standard file information.</param> public void SetFileStandardInformation(string path, WindowsFileInformation info) { throw new NotSupportedException(); } /// <summary> /// Gets the names of the alternate data streams for a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns> /// The list of alternate data streams (or empty, if none). To access the contents /// of the alternate streams, use OpenFile(path + ":" + name, ...). /// </returns> public string[] GetAlternateDataStreams(string path) { DirectoryEntry dirEntry = GetEntry(path); List<string> names = new List<string>(); if (dirEntry.AlternateStreams != null) { foreach (var altStream in dirEntry.AlternateStreams) { if (!string.IsNullOrEmpty(altStream.Key)) { names.Add(altStream.Key); } } } return names.ToArray(); } /// <summary> /// Gets the file id for a given path. /// </summary> /// <param name="path">The path to get the id of.</param> /// <returns>The file id, or -1.</returns> /// <remarks> /// The returned file id uniquely identifies the file, and is shared by all hard /// links to the same file. The value -1 indicates no unique identifier is /// available, and so it can be assumed the file has no hard links. /// </remarks> public long GetFileId(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.HardLink == 0 ? -1 : (long)dirEntry.HardLink; } /// <summary> /// Indicates whether the file is known by other names. /// </summary> /// <param name="path">The file to inspect.</param> /// <returns><c>true</c> if the file has other names, else <c>false</c>.</returns> public bool HasHardLinks(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry.HardLink != 0; } /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> public override bool DirectoryExists(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry != null && (dirEntry.Attributes & FileAttributes.Directory) != 0; } /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> public override bool FileExists(string path) { DirectoryEntry dirEntry = GetEntry(path); return dirEntry != null && (dirEntry.Attributes & FileAttributes.Directory) == 0; } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); List<string> dirs = new List<string>(); DoSearch(dirs, path, re, searchOption == SearchOption.AllDirectories, true, false); return dirs.ToArray(); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); List<string> results = new List<string>(); DoSearch(results, path, re, searchOption == SearchOption.AllDirectories, false, true); return results.ToArray(); } /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path) { DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry == null) { throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "The directory '{0}' does not exist", path)); } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); return Utilities.Map<DirectoryEntry, string>(parentDir, (m) => Utilities.CombinePaths(path, m.FileName)); } /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path, string searchPattern) { Regex re = Utilities.ConvertWildcardsToRegEx(searchPattern); DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry == null) { throw new DirectoryNotFoundException(string.Format(CultureInfo.InvariantCulture, "The directory '{0}' does not exist", path)); } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); List<string> result = new List<string>(); foreach (DirectoryEntry dirEntry in parentDir) { if (re.IsMatch(dirEntry.FileName)) { result.Add(Utilities.CombinePaths(path, dirEntry.FileName)); } } return result.ToArray(); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode, FileAccess access) { if (mode != FileMode.Open && mode != FileMode.OpenOrCreate) { throw new NotSupportedException("No write support for WIM files"); } if (access != FileAccess.Read) { throw new NotSupportedException("No write support for WIM files"); } byte[] streamHash = GetFileHash(path); ShortResourceHeader hdr = _file.LocateResource(streamHash); if (hdr == null) { if (Utilities.IsAllZeros(streamHash, 0, streamHash.Length)) { return new ZeroStream(0); } throw new IOException("Unable to locate file contents"); } return _file.OpenResourceStream(hdr); } /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> public override FileAttributes GetAttributes(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.Attributes; } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.CreationTime); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.LastAccessTime); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTimeUtc(string path) { DirectoryEntry dirEntry = GetEntry(path); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return DateTime.FromFileTimeUtc(dirEntry.LastWriteTime); } /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> public override long GetFileLength(string path) { string filePart; string altStreamPart; SplitFileName(path, out filePart, out altStreamPart); DirectoryEntry dirEntry = GetEntry(filePart); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.GetLength(altStreamPart); } /// <summary> /// Gets the SHA-1 hash of a file's contents. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The 160-bit hash.</returns> /// <remarks>The WIM file format internally stores the SHA-1 hash of files. /// This method provides access to the stored hash. Callers can use this /// value to compare against the actual hash of the byte stream to validate /// the integrity of the file contents.</remarks> public byte[] GetFileHash(string path) { string filePart; string altStreamPart; SplitFileName(path, out filePart, out altStreamPart); DirectoryEntry dirEntry = GetEntry(filePart); if (dirEntry == null) { throw new FileNotFoundException("No such file or directory", path); } return dirEntry.GetStreamHash(altStreamPart); } /// <summary> /// Disposes of this instance. /// </summary> /// <param name="disposing"><c>true</c> if disposing, else <c>false</c>.</param> protected override void Dispose(bool disposing) { try { _metaDataStream.Dispose(); _metaDataStream = null; _file = null; } finally { base.Dispose(disposing); } } private static void SplitFileName(string path, out string filePart, out string altStreamPart) { int streamSepPos = path.IndexOf(":", StringComparison.Ordinal); if (streamSepPos >= 0) { filePart = path.Substring(0, streamSepPos); altStreamPart = path.Substring(streamSepPos + 1); } else { filePart = path; altStreamPart = string.Empty; } } private List<DirectoryEntry> GetDirectory(long id) { List<DirectoryEntry> dir = _dirCache[id]; if (dir == null) { _metaDataStream.Position = (id == 0) ? _rootDirPos : id; LittleEndianDataReader reader = new LittleEndianDataReader(_metaDataStream); dir = new List<DirectoryEntry>(); DirectoryEntry entry = DirectoryEntry.ReadFrom(reader); while (entry != null) { dir.Add(entry); entry = DirectoryEntry.ReadFrom(reader); } _dirCache[id] = dir; } return dir; } private void ReadSecurityDescriptors() { LittleEndianDataReader reader = new LittleEndianDataReader(_metaDataStream); long startPos = reader.Position; uint totalLength = reader.ReadUInt32(); uint numEntries = reader.ReadUInt32(); ulong[] sdLengths = new ulong[numEntries]; for (uint i = 0; i < numEntries; ++i) { sdLengths[i] = reader.ReadUInt64(); } _securityDescriptors = new List<RawSecurityDescriptor>((int)numEntries); for (uint i = 0; i < numEntries; ++i) { _securityDescriptors.Add(new RawSecurityDescriptor(reader.ReadBytes((int)sdLengths[i]), 0)); } if (reader.Position < startPos + totalLength) { reader.Skip((int)(startPos + totalLength - reader.Position)); } _rootDirPos = Utilities.RoundUp(startPos + totalLength, 8); } private DirectoryEntry GetEntry(string path) { if (path.EndsWith(@"\", StringComparison.Ordinal)) { path = path.Substring(0, path.Length - 1); } if (!string.IsNullOrEmpty(path) && !path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = @"\" + path; } return GetEntry(GetDirectory(0), path.Split('\\')); } private DirectoryEntry GetEntry(List<DirectoryEntry> dir, string[] path) { List<DirectoryEntry> currentDir = dir; DirectoryEntry nextEntry = null; for (int i = 0; i < path.Length; ++i) { nextEntry = null; foreach (var entry in currentDir) { if (path[i].Equals(entry.FileName, StringComparison.OrdinalIgnoreCase) || (!string.IsNullOrEmpty(entry.ShortName) && path[i].Equals(entry.ShortName, StringComparison.OrdinalIgnoreCase))) { nextEntry = entry; break; } } if (nextEntry == null) { return null; } else if (nextEntry.SubdirOffset != 0) { currentDir = GetDirectory(nextEntry.SubdirOffset); } } return nextEntry; } private void DoSearch(List<string> results, string path, Regex regex, bool subFolders, bool dirs, bool files) { DirectoryEntry parentDirEntry = GetEntry(path); if (parentDirEntry.SubdirOffset == 0) { return; } List<DirectoryEntry> parentDir = GetDirectory(parentDirEntry.SubdirOffset); foreach (DirectoryEntry de in parentDir) { bool isDir = (de.Attributes & FileAttributes.Directory) != 0; if ((isDir && dirs) || (!isDir && files)) { if (regex.IsMatch(de.SearchName)) { results.Add(Utilities.CombinePaths(path, de.FileName)); } } if (subFolders && isDir) { DoSearch(results, Utilities.CombinePaths(path, de.FileName), regex, subFolders, dirs, files); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; namespace System.Runtime { public static class Fx { private const string defaultEventSource = "System.Runtime"; #if DEBUG private const string AssertsFailFastName = "AssertsFailFast"; private const string BreakOnExceptionTypesName = "BreakOnExceptionTypes"; private const string FastDebugName = "FastDebug"; private const string StealthDebuggerName = "StealthDebugger"; private static bool s_breakOnExceptionTypesRetrieved; private static Type[] s_breakOnExceptionTypesCache; #endif private static ExceptionTrace s_exceptionTrace; private static EtwDiagnosticTrace s_diagnosticTrace; private static bool? s_isUap; private static ExceptionHandler s_asynchronousThreadExceptionHandler; internal static bool IsUap { get { if (!s_isUap.HasValue) { s_isUap = "Microsoft Windows".Equals(RuntimeInformation.OSDescription, StringComparison.Ordinal); } return s_isUap.Value; } } internal static ExceptionTrace Exception { get { if (s_exceptionTrace == null) { // don't need a lock here since a true singleton is not required s_exceptionTrace = new ExceptionTrace(defaultEventSource, Trace); } return s_exceptionTrace; } } internal static EtwDiagnosticTrace Trace { get { if (s_diagnosticTrace == null) { s_diagnosticTrace = InitializeTracing(); } return s_diagnosticTrace; } } private static EtwDiagnosticTrace InitializeTracing() { EtwDiagnosticTrace trace = new EtwDiagnosticTrace(defaultEventSource, EtwDiagnosticTrace.DefaultEtwProviderId); return trace; } public static ExceptionHandler AsynchronousThreadExceptionHandler { get { return Fx.s_asynchronousThreadExceptionHandler; } set { Fx.s_asynchronousThreadExceptionHandler = value; } } // Do not call the parameter "message" or else FxCop thinks it should be localized. [Conditional("DEBUG")] public static void Assert(bool condition, string description) { if (!condition) { Assert(description); } } [Conditional("DEBUG")] public static void Assert(string description) { AssertHelper.FireAssert(description); } public static void AssertAndThrow(bool condition, string description) { if (!condition) { AssertAndThrow(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrow(string description) { Fx.Assert(description); TraceCore.ShipAssertExceptionMessage(Trace, description); throw new InternalException(description); } public static void AssertAndThrowFatal(bool condition, string description) { if (!condition) { AssertAndThrowFatal(description); } } [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndThrowFatal(string description) { Fx.Assert(description); TraceCore.ShipAssertExceptionMessage(Trace, description); throw new FatalInternalException(description); } public static void AssertAndFailFast(bool condition, string description) { if (!condition) { AssertAndFailFast(description); } } // This never returns. The Exception return type lets you write 'throw AssertAndFailFast()' which tells the compiler/tools that // execution stops. [Tag.SecurityNote(Critical = "Calls into critical method Environment.FailFast", Safe = "The side affect of the app crashing is actually intended here")] [SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] public static Exception AssertAndFailFast(string description) { Fx.Assert(description); string failFastMessage = InternalSR.FailFastMessage(description); // The catch is here to force the finally to run, as finallys don't run until the stack walk gets to a catch. // The catch makes sure that the finally will run before the stack-walk leaves the frame, but the code inside is impossible to reach. try { try { Fx.Exception.TraceFailFast(failFastMessage); } finally { Environment.FailFast(failFastMessage); } } catch { throw; } return null; // we'll never get here since we've just fail-fasted } public static bool IsFatal(Exception exception) { while (exception != null) { if (exception is FatalException || exception is OutOfMemoryException || exception is FatalInternalException) { return true; } // These exceptions aren't themselves fatal, but since the CLR uses them to wrap other exceptions, // we want to check to see whether they've been used to wrap a fatal exception. If so, then they // count as fatal. if (exception is TypeInitializationException || exception is TargetInvocationException) { exception = exception.InnerException; } else if (exception is AggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. ReadOnlyCollection<Exception> innerExceptions = ((AggregateException)exception).InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) { return true; } } break; } else { break; } } return false; } // This method should be only used for debug build. internal static bool AssertsFailFast { get { return false; } } // This property should be only used for debug build. internal static Type[] BreakOnExceptionTypes { get { #if DEBUG if (!Fx.s_breakOnExceptionTypesRetrieved) { object value; if (TryGetDebugSwitch(Fx.BreakOnExceptionTypesName, out value)) { string[] typeNames = value as string[]; if (typeNames != null && typeNames.Length > 0) { List<Type> types = new List<Type>(typeNames.Length); for (int i = 0; i < typeNames.Length; i++) { types.Add(Type.GetType(typeNames[i], false)); } if (types.Count != 0) { Fx.s_breakOnExceptionTypesCache = types.ToArray(); } } } Fx.s_breakOnExceptionTypesRetrieved = true; } return Fx.s_breakOnExceptionTypesCache; #else return null; #endif } } // This property should be only used for debug build. internal static bool StealthDebugger { get { return false; } } #if DEBUG private static bool TryGetDebugSwitch(string name, out object value) { value = null; return false; } #endif public static AsyncCallback ThunkCallback(AsyncCallback callback) { return (new AsyncThunk(callback)).ThunkFrame; } public static Action<T1> ThunkCallback<T1>(Action<T1> callback) { return (new ActionThunk<T1>(callback)).ThunkFrame; } [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, Justification = "These are the core methods that should be used for all other Guid(string) calls.")] public static Guid CreateGuid(string guidString) { bool success = false; Guid result = Guid.Empty; try { result = new Guid(guidString); success = true; } finally { if (!success) { AssertAndThrow("Creation of the Guid failed."); } } return result; } [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.UseNewGuidHelperRule, Justification = "These are the core methods that should be used for all other Guid(string) calls.")] public static bool TryCreateGuid(string guidString, out Guid result) { bool success = false; result = Guid.Empty; try { result = new Guid(guidString); success = true; } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } return success; } public static byte[] AllocateByteArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new byte[size]; } catch (OutOfMemoryException exception) { // Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it. // Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K. Fx.Exception.AsError(exception); throw; } } public static char[] AllocateCharArray(int size) { try { // Safe to catch OOM from this as long as the ONLY thing it does is a simple allocation of a primitive type (no method calls). return new char[size]; } catch (OutOfMemoryException exception) { // Desktop wraps the OOM inside a new InsufficientMemoryException, traces, and then throws it. // Project N and K trace and throw the original OOM. InsufficientMemoryException does not exist in N and K. Fx.Exception.AsError(exception); throw; } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] private static void TraceExceptionNoThrow(Exception exception) { try { // This call exits the CER. However, when still inside a catch, normal ThreadAbort is prevented. // Rude ThreadAbort will still be allowed to terminate processing. Fx.Exception.TraceUnhandledException(exception); } catch { // This empty catch is only acceptable because we are a) in a CER and b) processing an exception // which is about to crash the process anyway. } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.DoNotCatchGeneralExceptionTypes, Justification = "Don't want to hide the exception which is about to crash the process.")] [SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.IsFatalRule, Justification = "Don't want to hide the exception which is about to crash the process.")] [Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] private static bool HandleAtThreadBase(Exception exception) { // This area is too sensitive to do anything but return. if (exception == null) { Fx.Assert("Null exception in HandleAtThreadBase."); return false; } TraceExceptionNoThrow(exception); try { ExceptionHandler handler = Fx.AsynchronousThreadExceptionHandler; return handler == null ? false : handler.HandleException(exception); } catch (Exception secondException) { // Don't let a new exception hide the original exception. TraceExceptionNoThrow(secondException); } return false; } private static void UpdateLevel(EtwDiagnosticTrace trace) { if (trace == null) { return; } if (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) || TraceCore.ActionItemScheduledIsEnabled(trace)) { trace.SetEnd2EndActivityTracingEnabled(true); } } private static void UpdateLevel() { UpdateLevel(Fx.Trace); } public abstract class ExceptionHandler { [Tag.SecurityNote(Miscellaneous = "Must not call into PT code as it is called within a CER.")] public abstract bool HandleException(Exception exception); } public static class Tag { public enum CacheAttrition { None, ElementOnTimer, // A finalizer/WeakReference based cache, where the elements are held by WeakReferences (or hold an // inner object by a WeakReference), and the weakly-referenced object has a finalizer which cleans the // item from the cache. ElementOnGC, // A cache that provides a per-element token, delegate, interface, or other piece of context that can // be used to remove the element (such as IDisposable). ElementOnCallback, FullPurgeOnTimer, FullPurgeOnEachAccess, PartialPurgeOnTimer, PartialPurgeOnEachAccess, } public enum ThrottleAction { Reject, Pause, } public enum ThrottleMetric { Count, Rate, Other, } public enum Location { InProcess, OutOfProcess, LocalSystem, LocalOrRemoteSystem, // as in a file that might live on a share RemoteSystem, } public enum SynchronizationKind { LockStatement, MonitorWait, MonitorExplicit, InterlockedNoSpin, InterlockedWithSpin, // Same as LockStatement if the field type is object. FromFieldType, } [Flags] public enum BlocksUsing { MonitorEnter, MonitorWait, ManualResetEvent, AutoResetEvent, AsyncResult, IAsyncResult, PInvoke, InputQueue, ThreadNeutralSemaphore, PrivatePrimitive, OtherInternalPrimitive, OtherFrameworkPrimitive, OtherInterop, Other, NonBlocking, // For use by non-blocking SynchronizationPrimitives such as IOThreadScheduler } public static class Strings { internal const string ExternallyManaged = "externally managed"; internal const string AppDomain = "AppDomain"; internal const string DeclaringInstance = "instance of declaring class"; internal const string Unbounded = "unbounded"; internal const string Infinite = "infinite"; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] [Conditional("DEBUG")] public sealed class FriendAccessAllowedAttribute : Attribute { public FriendAccessAllowedAttribute(string assemblyName) : base() { AssemblyName = assemblyName; } public string AssemblyName { get; set; } } public static class Throws { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class TimeoutAttribute : ThrowsAttribute { public TimeoutAttribute() : this("The operation timed out.") { } public TimeoutAttribute(string diagnosis) : base(typeof(TimeoutException), diagnosis) { } } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class CacheAttribute : Attribute { private readonly CacheAttrition _cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; Timeout = Strings.Infinite; ElementType = elementType ?? throw Fx.Exception.ArgumentNull("elementType"); _cacheAttrition = cacheAttrition; } public Type ElementType { get; } public CacheAttrition CacheAttrition { get { return _cacheAttrition; } } public string Scope { get; set; } public string SizeLimit { get; set; } public string Timeout { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class QueueAttribute : Attribute { public QueueAttribute(Type elementType) { Scope = Strings.DeclaringInstance; SizeLimit = Strings.Unbounded; ElementType = elementType ?? throw Fx.Exception.ArgumentNull("elementType"); } public Type ElementType { get; } public string Scope { get; set; } public string SizeLimit { get; set; } public bool StaleElementsRemovedImmediately { get; set; } public bool EnqueueThrowsIfFull { get; set; } } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ThrottleAttribute : Attribute { private readonly string _limit; public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit) { Scope = Strings.AppDomain; if (string.IsNullOrEmpty(limit)) { throw Fx.Exception.ArgumentNullOrEmpty("limit"); } ThrottleAction = throttleAction; ThrottleMetric = throttleMetric; _limit = limit; } public ThrottleAction ThrottleAction { get; } public ThrottleMetric ThrottleMetric { get; } public string Limit { get { return _limit; } } public string Scope { get; set; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class ExternalResourceAttribute : Attribute { private readonly string _description; public ExternalResourceAttribute(Location location, string description) { Location = location; _description = description; } public Location Location { get; } public string Description { get { return _description; } } } // Set on a class when that class uses lock (this) - acts as though it were on a field // private object this; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Class, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationObjectAttribute : Attribute { public SynchronizationObjectAttribute() { Blocking = true; Scope = Strings.DeclaringInstance; Kind = SynchronizationKind.FromFieldType; } public bool Blocking { get; set; } public string Scope { get; set; } public SynchronizationKind Kind { get; set; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SynchronizationPrimitiveAttribute : Attribute { public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { BlocksUsing = blocksUsing; } public BlocksUsing BlocksUsing { get; } public bool SupportsAsync { get; set; } public bool Spins { get; set; } public string ReleaseMethod { get; set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class BlockingAttribute : Attribute { public BlockingAttribute() { } public string CancelMethod { get; set; } public Type CancelDeclaringType { get; set; } public string Conditional { get; set; } } // Sometime a method will call a conditionally-blocking method in such a way that it is guaranteed // not to block (i.e. the condition can be Asserted false). Such a method can be marked as // GuaranteeNonBlocking as an assertion that the method doesn't block despite calling a blocking method. // // Methods that don't call blocking methods and aren't marked as Blocking are assumed not to block, so // they do not require this attribute. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class GuaranteeNonBlockingAttribute : Attribute { public GuaranteeNonBlockingAttribute() { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class NonThrowingAttribute : Attribute { public NonThrowingAttribute() { } } [SuppressMessage(FxCop.Category.Performance, "CA1813:AvoidUnsealedAttributes", Justification = "This is intended to be an attribute hierarchy. It does not affect product perf.")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public class ThrowsAttribute : Attribute { private readonly string _diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { if (string.IsNullOrEmpty(diagnosis)) { throw Fx.Exception.ArgumentNullOrEmpty("diagnosis"); } ExceptionType = exceptionType ?? throw Fx.Exception.ArgumentNull("exceptionType"); _diagnosis = diagnosis; } public Type ExceptionType { get; } public string Diagnosis { get { return _diagnosis; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class InheritThrowsAttribute : Attribute { public InheritThrowsAttribute() { } public Type FromDeclaringType { get; set; } public string From { get; set; } } [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class KnownXamlExternalAttribute : Attribute { public KnownXamlExternalAttribute() { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class XamlVisibleAttribute : Attribute { public XamlVisibleAttribute() : this(true) { } public XamlVisibleAttribute(bool visible) { Visible = visible; } public bool Visible { get; private set; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Conditional("CODE_ANALYSIS_CDF")] public sealed class SecurityNoteAttribute : Attribute { public SecurityNoteAttribute() { } public string Critical { get; set; } public string Safe { get; set; } public string Miscellaneous { get; set; } } } internal abstract class Thunk<T> where T : class { [Tag.SecurityNote(Critical = "Make these safe to use in SecurityCritical contexts.")] [SecurityCritical] private T _callback; [Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data provided by caller.")] [SecuritySafeCritical] protected Thunk(T callback) { _callback = callback; } internal T Callback { [Tag.SecurityNote(Critical = "Accesses critical field.", Safe = "Data is not privileged.")] [SecuritySafeCritical] get { return _callback; } } } internal sealed class ActionThunk<T1> : Thunk<Action<T1>> { public ActionThunk(Action<T1> callback) : base(callback) { } public Action<T1> ThunkFrame { get { return new Action<T1>(UnhandledExceptionFrame); } } [Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] private void UnhandledExceptionFrame(T1 result) { try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } internal sealed class AsyncThunk : Thunk<AsyncCallback> { public AsyncThunk(AsyncCallback callback) : base(callback) { } public AsyncCallback ThunkFrame { get { return new AsyncCallback(UnhandledExceptionFrame); } } [Tag.SecurityNote(Critical = "Calls PrepareConstrainedRegions which has a LinkDemand", Safe = "Guaranteed not to call into PT user code from the finally.")] [SecuritySafeCritical] private void UnhandledExceptionFrame(IAsyncResult result) { try { Callback(result); } catch (Exception exception) { if (!Fx.HandleAtThreadBase(exception)) { throw; } } } } internal class InternalException : Exception { public InternalException(string description) : base(InternalSR.ShipAssertExceptionMessage(description)) { } protected InternalException(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } } [Serializable] internal class FatalInternalException : InternalException { public FatalInternalException(string description) : base(description) { } protected FatalInternalException(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; namespace Orleans.Runtime.ConsistentRing { /// <summary> /// We use the 'backward/clockwise' definition to assign responsibilities on the ring. /// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range). /// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc. /// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities. /// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range).. /// </summary> internal class VirtualBucketsRingProvider : IConsistentRingProvider, ISiloStatusListener { private readonly List<IRingRangeListener> statusListeners; private readonly SortedDictionary<uint, SiloAddress> bucketsMap; private List<Tuple<uint, SiloAddress>> sortedBucketsList; // flattened sorted bucket list for fast lock-free calculation of CalculateTargetSilo private readonly ILogger logger; private readonly SiloAddress myAddress; private readonly int numBucketsPerSilo; private readonly object lockable; private bool running; private IRingRange myRange; internal VirtualBucketsRingProvider(SiloAddress siloAddress, ILoggerFactory loggerFactory, int numVirtualBuckets) { numBucketsPerSilo = numVirtualBuckets; if (numBucketsPerSilo <= 0 ) throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + numBucketsPerSilo); logger = loggerFactory.CreateLogger<VirtualBucketsRingProvider>(); statusListeners = new List<IRingRangeListener>(); bucketsMap = new SortedDictionary<uint, SiloAddress>(); sortedBucketsList = new List<Tuple<uint, SiloAddress>>(); myAddress = siloAddress; lockable = new object(); running = true; myRange = RangeFactory.CreateFullRange(); logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddress.ToStringWithHashCode()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString); IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize())); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage()); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () => { int size = GetRingSize(); return size == 0 ? 0 : ((float)100.0/(float) size); }); // add myself to the list of members AddServer(myAddress); } private void Stop() { running = false; } public IRingRange GetMyRange() { return myRange; } private int GetRingSize() { lock (lockable) { return bucketsMap.Values.Distinct().Count(); } } public bool SubscribeToRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased) { logger.Info(ErrorCode.CRP_Notify, "-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old.ToString(), now.ToString(), increased); List<IRingRangeListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (IRingRangeListener listener in copy) { try { listener.RangeChangeNotification(old, now, increased); } catch (Exception exc) { logger.Error(ErrorCode.CRP_Local_Subscriber_Exception, String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}", listener.GetType().FullName, old, now, increased), exc); } } } private void AddServer(SiloAddress silo) { lock (lockable) { List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { if (bucketsMap.ContainsKey(hash)) { var other = bucketsMap[hash]; // If two silos conflict, take the lesser of the two (usually the older one; that is, the lower epoch) if (silo.CompareTo(other) > 0) continue; } bucketsMap[hash] = silo; } var myOldRange = myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Added_Silo, "Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } internal void RemoveServer(SiloAddress silo) { lock (lockable) { if (!bucketsMap.ContainsValue(silo)) return; // we have already removed this silo List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { bucketsMap.Remove(hash); } var myOldRange = this.myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Removed_Silo, "Removed Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } private static IRingRange CalculateRange(List<Tuple<uint, SiloAddress>> list, SiloAddress silo) { var ranges = new List<IRingRange>(); for (int i = 0; i < list.Count; i++) { var curr = list[i]; var next = list[(i + 1) % list.Count]; // 'backward/clockwise' definition to assign responsibilities on the ring. if (next.Item2.Equals(silo)) { IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1); ranges.Add(range); } } return RangeFactory.CreateRange(ranges); } // just for debugging public override string ToString() { Dictionary<SiloAddress, IRingRangeInternal> ranges = GetRanges(); List<KeyValuePair<SiloAddress, IRingRangeInternal>> sortedList = ranges.AsEnumerable().ToList(); sortedList.Sort((t1, t2) => t1.Value.RangePercentage().CompareTo(t2.Value.RangePercentage())); return Utils.EnumerableToString(sortedList, kv => String.Format("{0} -> {1}", kv.Key, kv.Value.ToString())); } // Internal: for testing only! internal Dictionary<SiloAddress, IRingRangeInternal> GetRanges() { List<SiloAddress> silos; List<Tuple<uint, SiloAddress>> snapshotBucketsList; lock (lockable) { silos = bucketsMap.Values.Distinct().ToList(); snapshotBucketsList = sortedBucketsList; } var ranges = new Dictionary<SiloAddress, IRingRangeInternal>(); foreach (var silo in silos) { var range = (IRingRangeInternal)CalculateRange(snapshotBucketsList, silo); ranges.Add(silo, range); } return ranges; } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (updatedSilo.Equals(myAddress)) { if (status.IsTerminating()) { Stop(); } } else // Status change for some other silo { if (status.IsTerminating()) { RemoveServer(updatedSilo); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active { AddServer(updatedSilo); } } } public SiloAddress GetPrimaryTargetSilo(uint key) { return CalculateTargetSilo(key); } /// <summary> /// Finds the silo that owns the given hash value. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="hash"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> private SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true) { // put a private reference to point to sortedBucketsList, // so if someone is changing the sortedBucketsList reference, we won't get it changed in the middle of our operation. // The tricks of writing lock-free code! var snapshotBucketsList = sortedBucketsList; // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = excludeThisSiloIfStopping && !running; if (snapshotBucketsList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeMySelf ? null : myAddress; } // use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ... // if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes Tuple<uint, SiloAddress> s = snapshotBucketsList.Find(tuple => (tuple.Item1 >= hash) && // <= hash for counter-clockwise responsibilities (!tuple.Item2.Equals(myAddress) || !excludeMySelf)); if (s == null) { // if not found in traversal, then first silo should be returned (we are on a ring) // if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory s = snapshotBucketsList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy // Make sure it's not us... if (s.Item2.Equals(myAddress) && excludeMySelf) { // vs [membershipRingList.Count - 2]; for counter-clockwise policy s = snapshotBucketsList.Count > 1 ? snapshotBucketsList[1] : null; } } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Calculated ring partition owner silo {0} for key {1}: {2} --> {3}", s.Item2, hash, hash, s.Item1); return s.Item2; } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { public class ProjectReferenceNode : ReferenceNode { #region fields /// <summary> /// The name of the assembly this reference represents /// </summary> private Guid referencedProjectGuid; private string referencedProjectName = String.Empty; private string referencedProjectRelativePath = String.Empty; private string referencedProjectFullPath = String.Empty; private BuildDependency buildDependency; /// <summary> /// This is a reference to the automation object for the referenced project. /// </summary> private EnvDTE.Project referencedProject; /// <summary> /// This state is controlled by the solution events. /// The state is set to false by OnBeforeUnloadProject. /// The state is set to true by OnBeforeCloseProject event. /// </summary> private bool canRemoveReference = true; /// <summary> /// Possibility for solution listener to update the state on the dangling reference. /// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false. /// </summary> private bool isNodeValid; #endregion #region properties public override string Url { get { return this.referencedProjectFullPath; } } public override string Caption { get { return this.referencedProjectName; } } internal Guid ReferencedProjectGuid { get { return this.referencedProjectGuid; } } /// <summary> /// Possiblity to shortcut and set the dangling project reference icon. /// It is ussually manipulated by solution listsneres who handle reference updates. /// </summary> internal protected bool IsNodeValid { get { return this.isNodeValid; } set { this.isNodeValid = value; } } /// <summary> /// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted. /// </summary> internal bool CanRemoveReference { get { return this.canRemoveReference; } set { this.canRemoveReference = value; } } internal string ReferencedProjectName { get { return this.referencedProjectName; } } /// <summary> /// Gets the automation object for the referenced project. /// </summary> internal EnvDTE.Project ReferencedProjectObject { get { // If the referenced project is null then re-read. if (this.referencedProject == null) { // Search for the project in the collection of the projects in the // current solution. EnvDTE.DTE dte = (EnvDTE.DTE)this.ProjectMgr.GetService(typeof(EnvDTE.DTE)); if ((null == dte) || (null == dte.Solution)) { return null; } this.referencedProject = this.FindReferencedProject(dte.Solution.Projects); } return this.referencedProject; } set { this.referencedProject = value; } } /// <summary> /// Gets the full path to the assembly generated by this project. /// </summary> internal string ReferencedProjectOutputPath { get { // Make sure that the referenced project implements the automation object. if(null == this.ReferencedProjectObject) { return null; } // Get the configuration manager from the project. EnvDTE.ConfigurationManager confManager = this.ReferencedProjectObject.ConfigurationManager; if(null == confManager) { return null; } // Get the active configuration. EnvDTE.Configuration config = confManager.ActiveConfiguration; if(null == config) { return null; } // Get the output path for the current configuration. EnvDTE.Property outputPathProperty = config.Properties.Item("OutputPath"); if(null == outputPathProperty) { return null; } string outputPath = outputPathProperty.Value.ToString(); // Ususally the output path is relative to the project path, but it is possible // to set it as an absolute path. If it is not absolute, then evaluate its value // based on the project directory. if(!System.IO.Path.IsPathRooted(outputPath)) { string projectDir = System.IO.Path.GetDirectoryName(referencedProjectFullPath); outputPath = System.IO.Path.Combine(projectDir, outputPath); } // Now get the name of the assembly from the project. // Some project system throw if the property does not exist. We expect an ArgumentException. EnvDTE.Property assemblyNameProperty = null; try { assemblyNameProperty = this.ReferencedProjectObject.Properties.Item("OutputFileName"); } catch(ArgumentException) { } if(null == assemblyNameProperty) { return null; } // build the full path adding the name of the assembly to the output path. outputPath = System.IO.Path.Combine(outputPath, assemblyNameProperty.Value.ToString()); return outputPath; } } private Automation.OAProjectReference projectReference; internal override object Object { get { if(null == projectReference) { projectReference = new Automation.OAProjectReference(this); } return projectReference; } } #endregion #region ctors /// <summary> /// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings")] public ProjectReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include); Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrive referenced project path form project file"); string guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project); // Continue even if project setttings cannot be read. try { this.referencedProjectGuid = new Guid(guidString); this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid); this.ProjectMgr.AddBuildDependency(this.buildDependency); } finally { Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file"); this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name); Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file"); } Uri uri = new Uri(this.ProjectMgr.BaseURI.Uri, this.referencedProjectRelativePath); if(uri != null) { this.referencedProjectFullPath = Microsoft.VisualStudio.Shell.Url.Unescape(uri.LocalPath, true); } } /// <summary> /// constructor for the ProjectReferenceNode /// </summary> public ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference) : base(root) { Debug.Assert(root != null && !String.IsNullOrEmpty(referencedProjectName) && !String.IsNullOrEmpty(projectReference) && !String.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid."); if (projectReference == null) { throw new ArgumentNullException("projectReference"); } this.referencedProjectName = referencedProjectName; int indexOfSeparator = projectReference.IndexOf('|'); string fileName = String.Empty; // Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes. if(indexOfSeparator != -1) { string projectGuid = projectReference.Substring(0, indexOfSeparator); this.referencedProjectGuid = new Guid(projectGuid); if(indexOfSeparator + 1 < projectReference.Length) { string remaining = projectReference.Substring(indexOfSeparator + 1); indexOfSeparator = remaining.IndexOf('|'); if(indexOfSeparator == -1) { fileName = remaining; } else { fileName = remaining.Substring(0, indexOfSeparator); } } } Debug.Assert(!String.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid."); // Did we get just a file or a relative path? Uri uri = new Uri(projectPath); string referenceDir = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, uri); Debug.Assert(!String.IsNullOrEmpty(referenceDir), "Can not add a project reference because the input for adding one is invalid."); string justTheFileName = Path.GetFileName(fileName); this.referencedProjectRelativePath = Path.Combine(referenceDir, justTheFileName); this.referencedProjectFullPath = Path.Combine(projectPath, justTheFileName); this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid); } #endregion #region methods protected override NodeProperties CreatePropertiesObject() { return new ProjectReferencesProperties(this); } /// <summary> /// The node is added to the hierarchy and then updates the build dependency list. /// </summary> public override void AddReference() { if(this.ProjectMgr == null) { return; } base.AddReference(); this.ProjectMgr.AddBuildDependency(this.buildDependency); return; } /// <summary> /// Overridden method. The method updates the build dependency list before removing the node from the hierarchy. /// </summary> public override void Remove(bool removeFromStorage) { if(this.ProjectMgr == null || !this.CanRemoveReference) { return; } this.ProjectMgr.RemoveBuildDependency(this.buildDependency); base.Remove(removeFromStorage); return; } /// <summary> /// Links a reference node to the project file. /// </summary> protected override void BindReferenceData() { Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized"); Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized"); this.ItemNode = new ProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference); this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName); this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B")); this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString()); } /// <summary> /// Defines whether this node is valid node for painting the refererence icon. /// </summary> /// <returns></returns> protected override bool CanShowDefaultIcon() { if(this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid) { return false; } IVsHierarchy hierarchy = null; hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid); if(hierarchy == null) { return false; } //If the Project is unloaded return false if(this.ReferencedProjectObject == null) { return false; } return (!String.IsNullOrEmpty(this.referencedProjectFullPath) && File.Exists(this.referencedProjectFullPath)); } /// <summary> /// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references. /// </summary> /// <param name="errorHandler">The error handler delegate to return</param> /// <returns></returns> protected override bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) { // When this method is called this refererence has not yet been added to the hierarchy, only instantiated. if(!base.CanAddReference(out errorHandler)) { return false; } errorHandler = null; if(this.IsThisProjectReferenceInCycle()) { errorHandler = new CannotAddReferenceErrorMessage(ShowCircularReferenceErrorMessage); return false; } return true; } private bool IsThisProjectReferenceInCycle() { return IsReferenceInCycle(this.referencedProjectGuid); } private void ShowCircularReferenceErrorMessage() { string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectContainsCircularReferences, CultureInfo.CurrentUICulture), this.referencedProjectName); string title = string.Empty; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton); } /// <summary> /// Checks whether a reference added to a given project would introduce a circular dependency. /// </summary> private bool IsReferenceInCycle(Guid projectGuid) { IVsHierarchy referencedHierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid); var solutionBuildManager = this.ProjectMgr.Site.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2; if (solutionBuildManager == null) { throw new InvalidOperationException("Cannot find the IVsSolutionBuildManager2 service."); } int circular; Marshal.ThrowExceptionForHR(solutionBuildManager.CalculateProjectDependencies()); Marshal.ThrowExceptionForHR(solutionBuildManager.QueryProjectDependency(referencedHierarchy, this.ProjectMgr.InteropSafeIVsHierarchy, out circular)); return circular != 0; } private EnvDTE.Project FindReferencedProject(System.Collections.IEnumerable projects) { EnvDTE.Project refProject = null; // Search for the project in the collection of the projects in the current solution. foreach (EnvDTE.Project prj in projects) { //Skip this project if it is an umodeled project (unloaded) if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, prj.Kind, StringComparison.OrdinalIgnoreCase) == 0) { continue; } // Recursively iterate solution folder for the project. if (string.Compare(EnvDTE.Constants.vsProjectKindSolutionItems, prj.Kind, StringComparison.OrdinalIgnoreCase) == 0) { var containedProjects = GetContainerProjects(prj); refProject = FindReferencedProject(containedProjects); if (refProject != null) return refProject; } // Get the full path of the current project. EnvDTE.Property pathProperty = null; try { if (prj.Properties == null) { continue; } pathProperty = prj.Properties.Item("FullPath"); if (null == pathProperty) { // The full path should alway be availabe, but if this is not the // case then we have to skip it. continue; } } catch (ArgumentException) { continue; } string prjPath = pathProperty.Value.ToString(); EnvDTE.Property fileNameProperty = null; // Get the name of the project file. try { fileNameProperty = prj.Properties.Item("FileName"); if (null == fileNameProperty) { // Again, this should never be the case, but we handle it anyway. continue; } } catch (ArgumentException) { continue; } prjPath = System.IO.Path.Combine(prjPath, fileNameProperty.Value.ToString()); // If the full path of this project is the same as the one of this // reference, then we have found the right project. if (NativeMethods.IsSamePath(prjPath, referencedProjectFullPath)) { refProject = prj; break; } } return refProject; } private static System.Collections.IEnumerable GetContainerProjects(EnvDTE.Project prj) { foreach (var obj in prj.ProjectItems) { var pi = obj as EnvDTE.ProjectItem; if (pi == null) { continue; } var nestedPrj = pi.Object as EnvDTE.Project; if (nestedPrj != null) { yield return nestedPrj; } } } #endregion } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using MindTouch.Deki.UserSubscription; using MindTouch.Dream; using MindTouch.Dream.Test; using MindTouch.Tasking; using MindTouch.Xml; using NUnit.Framework; using MindTouch.Extensions.Time; namespace MindTouch.Deki.Tests.ChangeSubscriptionTests { using Yield = IEnumerator<IYield>; [TestFixture] public class PageChangeCacheTests { private static readonly log4net.ILog _log = LogUtils.CreateLog(); [TearDown] public void PerTestCleanup() { MockPlug.DeregisterAll(); } [Test] public void Get_page_data() { Plug deki = Plug.New("http://mock/deki"); AutoMockPlug autoMock = MockPlug.Register(deki.Uri); PageChangeCache cache = new PageChangeCache(deki, (key, trigger) => { }); DateTime timestamp = DateTime.Parse("2009/02/01 10:10:00"); XUri pageUri = deki.Uri.At("pages", "10").With("redirects", "0"); XDoc pageResponse = new XDoc("page") .Elem("uri.ui", "http://foo.com/@api/deki/pages/10") .Elem("title", "foo") .Elem("path", "foo/bar"); XUri feedUri = deki.Uri .At("pages", "10", "feed") .With("redirects", "0") .With("format", "raw") .With("since", timestamp.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss")); XDoc changeResponse = new XDoc("table") .Start("change") .Elem("rc_summary", "Two edits") .Elem("rc_comment", "edit 1") .Elem("rc_comment", "edit 2") .Elem("rc_timestamp", "20090201101000") .End(); _log.Debug("first get"); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri, (XDoc)null, DreamMessage.Ok(changeResponse)); PageChangeData data = Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", timestamp, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait(); Assert.IsTrue(autoMock.WaitAndVerify(TimeSpan.FromSeconds(10))); //string plainbody = "foo\r\n[ http://foo.com/@api/deki/pages/10 ]\r\n\r\n - edit 1 (Sun, 01 Feb 2009 10:10:00 GMT)\r\n [ http://foo.com/@api/deki/pages/10?revision ]\r\n\r\n"; XDoc htmlBody = XDocFactory.From("<html><p><b><a href=\"http://foo.com/@api/deki/pages/10\">foo</a></b> ( Last edited by <a href=\"http://foo.com/User%3a\" /> )<br /><small><a href=\"http://foo.com/@api/deki/pages/10\">http://foo.com/@api/deki/pages/10</a></small><br /><small><a href=\"http://foo.com/index.php?title=Special%3APageAlerts&amp;id=10\">Unsubscribe</a></small></p><p><ol><li>edit 1 ( <a href=\"http://foo.com/@api/deki/pages/10?revision\">Sun, 01 Feb 2009 10:10:00 GMT</a> by <a href=\"http://foo.com/User%3a\" /> )</li></ol></p><br /></html>", MimeType.TEXT_XML); Assert.AreEqual(htmlBody.ToString(), data.HtmlBody.ToString()); } [Test] public void Get_page_data_in_user_timezone() { Plug deki = Plug.New("http://mock/deki"); AutoMockPlug autoMock = MockPlug.Register(deki.Uri); PageChangeCache cache = new PageChangeCache(deki, (key, trigger) => { }); DateTime timestamp = DateTime.Parse("2009/02/01 10:10:00"); XUri pageUri = deki.Uri.At("pages", "10").With("redirects", "0"); XDoc pageResponse = new XDoc("page") .Elem("uri.ui", "http://foo.com/@api/deki/pages/10") .Elem("title", "foo") .Elem("path", "foo/bar"); XUri feedUri = deki.Uri .At("pages", "10", "feed") .With("redirects", "0") .With("format", "raw") .With("since", timestamp.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss")); XDoc changeResponse = new XDoc("table") .Start("change") .Elem("rc_summary", "Two edits") .Elem("rc_comment", "edit 1") .Elem("rc_comment", "edit 2") .Elem("rc_timestamp", "20090201101000") .End(); _log.Debug("first get"); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri, (XDoc)null, DreamMessage.Ok(changeResponse)); PageChangeData data = Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", timestamp, CultureInfo.InvariantCulture, "-09:00", new Result<PageChangeData>()).Wait(); Assert.IsTrue(autoMock.WaitAndVerify(TimeSpan.FromSeconds(10))); //string plainbody = "foo\r\n[ http://foo.com/@api/deki/pages/10 ]\r\n\r\n - edit 1 (Sun, 01 Feb 2009 01:10:00 -09:00)\r\n [ http://foo.com/@api/deki/pages/10?revision ]\r\n\r\n"; XDoc htmlBody = XDocFactory.From("<html><p><b><a href=\"http://foo.com/@api/deki/pages/10\">foo</a></b> ( Last edited by <a href=\"http://foo.com/User%3a\" /> )<br /><small><a href=\"http://foo.com/@api/deki/pages/10\">http://foo.com/@api/deki/pages/10</a></small><br /><small><a href=\"http://foo.com/index.php?title=Special%3APageAlerts&amp;id=10\">Unsubscribe</a></small></p><p><ol><li>edit 1 ( <a href=\"http://foo.com/@api/deki/pages/10?revision\">Sun, 01 Feb 2009 01:10:00 -09:00</a> by <a href=\"http://foo.com/User%3a\" /> )</li></ol></p><br /></html>", MimeType.TEXT_XML); Assert.AreEqual(htmlBody.ToString(), data.HtmlBody.ToString()); } [Test] public void Cache_hit_and_expire() { Plug deki = Plug.New("http://mock/deki"); AutoMockPlug autoMock = MockPlug.Register(deki.Uri); Action expire = null; PageChangeCache cache = new PageChangeCache(deki, (key, trigger) => expire = trigger); DateTime timestamp = DateTime.UtcNow; XUri pageUri = deki.Uri.At("pages", "10").With("redirects", "0"); XDoc pageResponse = new XDoc("page") .Elem("uri.ui", "http://foo.com/@api/deki/pages/10") .Elem("title", "foo") .Elem("path", "foo/bar"); XUri feedUri = deki.Uri .At("pages", "10", "feed") .With("redirects", "0") .With("format", "raw") .With("since", timestamp.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss")); XDoc changeResponse = new XDoc("table") .Start("change") .Elem("rc_summary", "Two edits") .Elem("rc_comment", "edit 1") .Elem("rc_comment", "edit 2") .End(); _log.Debug("first get"); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri, (XDoc)null, DreamMessage.Ok(changeResponse)); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", timestamp, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(10.Seconds())); _log.Debug("second get, cache hit"); autoMock.Reset(); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", timestamp, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(2.Seconds())); _log.Debug("third get, cache miss"); autoMock.Reset(); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri, (XDoc)null, DreamMessage.Ok(changeResponse)); expire(); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", timestamp, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(10.Seconds())); } [Test] public void Cache_hit_if_in_same_minute() { Plug deki = Plug.New("http://mock/deki"); AutoMockPlug autoMock = MockPlug.Register(deki.Uri); PageChangeCache cache = new PageChangeCache(deki, (key, trigger) => { }); DateTime t1 = DateTime.Parse("2009/02/01 10:10:00"); DateTime t2 = DateTime.Parse("2009/02/01 10:10:30"); DateTime t3 = DateTime.Parse("2009/02/01 10:11:00"); XUri pageUri = deki.Uri.At("pages", "10").With("redirects", "0"); XDoc pageResponse = new XDoc("page") .Elem("uri.ui", "http://foo.com/@api/deki/pages/10") .Elem("title", "foo") .Elem("path", "foo/bar"); XUri feedUri = deki.Uri .At("pages", "10", "feed") .With("redirects", "0") .With("format", "raw"); XDoc changeResponse = new XDoc("table") .Start("change") .Elem("rc_summary", "Two edits") .Elem("rc_comment", "edit 1") .Elem("rc_comment", "edit 2") .End(); _log.Debug("first get"); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri.With("since", t1.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss")), (XDoc)null, DreamMessage.Ok(changeResponse)); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", t1, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(10.Seconds())); _log.Debug("second get, cache hit"); autoMock.Reset(); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", t2, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(2.Seconds())); _log.Debug("third get, cache miss"); autoMock.Reset(); autoMock.Expect("GET", pageUri, (XDoc)null, DreamMessage.Ok(pageResponse)); autoMock.Expect("GET", feedUri.With("since", t3.Subtract(TimeSpan.FromSeconds(10)).ToString("yyyyMMddHHmmss")), (XDoc)null, DreamMessage.Ok(changeResponse)); Assert.IsNotNull(Coroutine.Invoke(cache.GetPageData, (uint)10, "foo", t3, CultureInfo.InvariantCulture, (string)null, new Result<PageChangeData>()).Wait()); Assert.IsTrue(autoMock.WaitAndVerify(10.Seconds())); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// AddressResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Api.V2010.Account { public class AddressResource : Resource { private static Request BuildCreateRequest(CreateAddressOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses.json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Create(CreateAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> CreateAsync(CreateAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="customerName"> The name to associate with the new address </param> /// <param name="street"> The number and street address of the new address </param> /// <param name="city"> The city of the new address </param> /// <param name="region"> The state or region of the new address </param> /// <param name="postalCode"> The postal code of the new address </param> /// <param name="isoCountry"> The ISO country code of the new address </param> /// <param name="pathAccountSid"> The SID of the Account that will be responsible for the new Address resource </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="emergencyEnabled"> Whether to enable emergency calling on the new address </param> /// <param name="autoCorrectAddress"> Whether we should automatically correct the address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Create(string customerName, string street, string city, string region, string postalCode, string isoCountry, string pathAccountSid = null, string friendlyName = null, bool? emergencyEnabled = null, bool? autoCorrectAddress = null, ITwilioRestClient client = null) { var options = new CreateAddressOptions(customerName, street, city, region, postalCode, isoCountry){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, EmergencyEnabled = emergencyEnabled, AutoCorrectAddress = autoCorrectAddress}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="customerName"> The name to associate with the new address </param> /// <param name="street"> The number and street address of the new address </param> /// <param name="city"> The city of the new address </param> /// <param name="region"> The state or region of the new address </param> /// <param name="postalCode"> The postal code of the new address </param> /// <param name="isoCountry"> The ISO country code of the new address </param> /// <param name="pathAccountSid"> The SID of the Account that will be responsible for the new Address resource </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="emergencyEnabled"> Whether to enable emergency calling on the new address </param> /// <param name="autoCorrectAddress"> Whether we should automatically correct the address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> CreateAsync(string customerName, string street, string city, string region, string postalCode, string isoCountry, string pathAccountSid = null, string friendlyName = null, bool? emergencyEnabled = null, bool? autoCorrectAddress = null, ITwilioRestClient client = null) { var options = new CreateAddressOptions(customerName, street, city, region, postalCode, isoCountry){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, EmergencyEnabled = emergencyEnabled, AutoCorrectAddress = autoCorrectAddress}; return await CreateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteAddressOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static bool Delete(DeleteAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static bool Delete(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAddressOptions(pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteAddressOptions(pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif private static Request BuildFetchRequest(FetchAddressOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Fetch(FetchAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> FetchAsync(FetchAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for this address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Fetch(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAddressOptions(pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for this address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchAddressOptions(pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateAddressOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses/" + options.PathSid + ".json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Update(UpdateAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> UpdateAsync(UpdateAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for the resource to update </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="customerName"> The name to associate with the address </param> /// <param name="street"> The number and street address of the address </param> /// <param name="city"> The city of the address </param> /// <param name="region"> The state or region of the address </param> /// <param name="postalCode"> The postal code of the address </param> /// <param name="emergencyEnabled"> Whether to enable emergency calling on the address </param> /// <param name="autoCorrectAddress"> Whether we should automatically correct the address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static AddressResource Update(string pathSid, string pathAccountSid = null, string friendlyName = null, string customerName = null, string street = null, string city = null, string region = null, string postalCode = null, bool? emergencyEnabled = null, bool? autoCorrectAddress = null, ITwilioRestClient client = null) { var options = new UpdateAddressOptions(pathSid){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, CustomerName = customerName, Street = street, City = city, Region = region, PostalCode = postalCode, EmergencyEnabled = emergencyEnabled, AutoCorrectAddress = autoCorrectAddress}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that is responsible for the resource to update </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="customerName"> The name to associate with the address </param> /// <param name="street"> The number and street address of the address </param> /// <param name="city"> The city of the address </param> /// <param name="region"> The state or region of the address </param> /// <param name="postalCode"> The postal code of the address </param> /// <param name="emergencyEnabled"> Whether to enable emergency calling on the address </param> /// <param name="autoCorrectAddress"> Whether we should automatically correct the address </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<AddressResource> UpdateAsync(string pathSid, string pathAccountSid = null, string friendlyName = null, string customerName = null, string street = null, string city = null, string region = null, string postalCode = null, bool? emergencyEnabled = null, bool? autoCorrectAddress = null, ITwilioRestClient client = null) { var options = new UpdateAddressOptions(pathSid){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, CustomerName = customerName, Street = street, City = city, Region = region, PostalCode = postalCode, EmergencyEnabled = emergencyEnabled, AutoCorrectAddress = autoCorrectAddress}; return await UpdateAsync(options, client); } #endif private static Request BuildReadRequest(ReadAddressOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static ResourceSet<AddressResource> Read(ReadAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AddressResource>.FromJson("addresses", response.Content); return new ResourceSet<AddressResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Address parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<ResourceSet<AddressResource>> ReadAsync(ReadAddressOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AddressResource>.FromJson("addresses", response.Content); return new ResourceSet<AddressResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAccountSid"> The SID of the Account that is responsible for this address </param> /// <param name="customerName"> The `customer_name` of the Address resources to read </param> /// <param name="friendlyName"> The string that identifies the Address resources to read </param> /// <param name="isoCountry"> The ISO country code of the Address resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Address </returns> public static ResourceSet<AddressResource> Read(string pathAccountSid = null, string customerName = null, string friendlyName = null, string isoCountry = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAddressOptions(){PathAccountSid = pathAccountSid, CustomerName = customerName, FriendlyName = friendlyName, IsoCountry = isoCountry, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAccountSid"> The SID of the Account that is responsible for this address </param> /// <param name="customerName"> The `customer_name` of the Address resources to read </param> /// <param name="friendlyName"> The string that identifies the Address resources to read </param> /// <param name="isoCountry"> The ISO country code of the Address resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Address </returns> public static async System.Threading.Tasks.Task<ResourceSet<AddressResource>> ReadAsync(string pathAccountSid = null, string customerName = null, string friendlyName = null, string isoCountry = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAddressOptions(){PathAccountSid = pathAccountSid, CustomerName = customerName, FriendlyName = friendlyName, IsoCountry = isoCountry, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<AddressResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AddressResource>.FromJson("addresses", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<AddressResource> NextPage(Page<AddressResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AddressResource>.FromJson("addresses", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<AddressResource> PreviousPage(Page<AddressResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<AddressResource>.FromJson("addresses", response.Content); } /// <summary> /// Converts a JSON string into a AddressResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AddressResource object represented by the provided JSON </returns> public static AddressResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AddressResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that is responsible for the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The city in which the address is located /// </summary> [JsonProperty("city")] public string City { get; private set; } /// <summary> /// The name associated with the address /// </summary> [JsonProperty("customer_name")] public string CustomerName { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The ISO country code of the address /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The postal code of the address /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; private set; } /// <summary> /// The state or region of the address /// </summary> [JsonProperty("region")] public string Region { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The number and street address of the address /// </summary> [JsonProperty("street")] public string Street { get; private set; } /// <summary> /// The URI of the resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } /// <summary> /// Whether emergency calling has been enabled on this number /// </summary> [JsonProperty("emergency_enabled")] public bool? EmergencyEnabled { get; private set; } /// <summary> /// Whether the address has been validated to comply with local regulation /// </summary> [JsonProperty("validated")] public bool? Validated { get; private set; } /// <summary> /// Whether the address has been verified to comply with regulation /// </summary> [JsonProperty("verified")] public bool? Verified { get; private set; } private AddressResource() { } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> : IReceivedMessageCallback, ISendCompletionCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); readonly Action<TWrite, SerializationContext> serializer; readonly Func<DeserializationContext, TRead> deserializer; protected readonly object myLock = new object(); protected INativeCall call; protected bool disposed; protected bool started; protected bool cancelRequested; protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null. protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null. protected TaskCompletionSource<object> sendStatusFromServerTcs; protected bool isStreamingWriteCompletionDelayed; // Only used for the client side. protected bool readingDone; // True if last read (i.e. read with null payload) was already received. protected bool halfcloseRequested; // True if send close have been initiated. protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; // Number of streaming send operations started so far. public AsyncCallBase(Action<TWrite, SerializationContext> serializer, Func<DeserializationContext, TRead> deserializer) { this.serializer = GrpcPreconditions.CheckNotNull(serializer); this.deserializer = GrpcPreconditions.CheckNotNull(deserializer); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { GrpcPreconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> protected void CancelWithStatus(Status status) { lock (myLock) { cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(INativeCall call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// </summary> protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendAllowedOrEarlyResult(); if (earlyResult != null) { return earlyResult; } call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent); initialMetadataSent = true; streamingWritesCounter++; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// </summary> protected Task<TRead> ReadMessageInternalAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); if (readingDone) { // the last read that returns null or throws an exception is idempotent // and maintains its state. GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads."); return streamingReadTcs.Task; } GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time"); GrpcPreconditions.CheckState(!disposed); call.StartReceiveMessage(ReceivedMessageCallback); streamingReadTcs = new TaskCompletionSource<TRead>(); return streamingReadTcs.Task; } } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { if (!disposed && call != null) { bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } protected abstract bool IsClient { get; } /// <summary> /// Returns an exception to throw for a failed send operation. /// It is only allowed to call this method for a call that has already finished. /// </summary> protected abstract Exception GetRpcExceptionClientOnly(); protected void ReleaseResources() { if (call != null) { call.Dispose(); } disposed = true; OnAfterReleaseResourcesLocked(); } protected virtual void OnAfterReleaseResourcesLocked() { } protected virtual void OnAfterReleaseResourcesUnlocked() { } /// <summary> /// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send /// logic by directly returning the write operation result task. Normally, null is returned. /// </summary> protected abstract Task CheckSendAllowedOrEarlyResult(); protected byte[] UnsafeSerialize(TWrite msg) { DefaultSerializationContext context = null; try { context = DefaultSerializationContext.GetInitializedThreadLocal(); serializer(msg, context); return context.GetPayload(); } finally { context?.Reset(); } } protected Exception TryDeserialize(IBufferReader reader, out TRead msg) { DefaultDeserializationContext context = null; try { context = DefaultDeserializationContext.GetInitializedThreadLocal(reader); msg = deserializer(context); return null; } catch (Exception e) { msg = default(TRead); return e; } finally { context?.Reset(); } } /// <summary> /// Handles send completion (including SendCloseFromClient). /// </summary> protected void HandleSendFinished(bool success) { bool delayCompletion = false; TaskCompletionSource<object> origTcs = null; bool releasedResources; lock (myLock) { if (!success && !finished && IsClient) { // We should be setting this only once per call, following writes will be short circuited // because they cannot start until the entire call finishes. GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed); // leave streamingWriteTcs set, it will be completed once call finished. isStreamingWriteCompletionDelayed = true; delayCompletion = true; } else { origTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (!success) { if (!delayCompletion) { if (IsClient) { GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient origTcs.SetException(GetRpcExceptionClientOnly()); } else { origTcs.SetException (new IOException("Error sending from server.")); } } // if delayCompletion == true, postpone SetException until call finishes. } else { origTcs.SetResult(null); } } /// <summary> /// Handles send status from server completion. /// </summary> protected void HandleSendStatusFromServerFinished(bool success) { bool releasedResources; lock (myLock) { releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (!success) { sendStatusFromServerTcs.SetException(new IOException("Error sending status from server.")); } else { sendStatusFromServerTcs.SetResult(null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, IBufferReader receivedMessageReader) { // if success == false, the message reader will report null payload. It that case we will // treat this completion as the last read an rely on C core to handle the failed // read (e.g. deliver approriate statusCode on the clientside). TRead msg = default(TRead); var deserializeException = (success && receivedMessageReader.TotalLength.HasValue) ? TryDeserialize(receivedMessageReader, out msg) : null; TaskCompletionSource<TRead> origTcs = null; bool releasedResources; lock (myLock) { origTcs = streamingReadTcs; if (!receivedMessageReader.TotalLength.HasValue) { // This was the last read. readingDone = true; } if (deserializeException != null && IsClient) { readingDone = true; // TODO(jtattermusch): it might be too late to set the status CancelWithStatus(DeserializeResponseFailureStatus); } if (!readingDone) { streamingReadTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (deserializeException != null && !IsClient) { origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException)); return; } origTcs.SetResult(msg); } protected ISendCompletionCallback SendCompletionCallback => this; void ISendCompletionCallback.OnSendCompletion(bool success) { HandleSendFinished(success); } IReceivedMessageCallback ReceivedMessageCallback => this; void IReceivedMessageCallback.OnReceivedMessage(bool success, IBufferReader receivedMessageReader) { HandleReadFinished(success, receivedMessageReader); } } }
#region License /* * EndPointListener.cs * * This code is derived from EndPointListener.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2016 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <[email protected]> */ #endregion #region Contributors /* * Contributors: * - Liryna <[email protected]> * - Nicholas Devenish */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace WebSocketSharp.Net { internal sealed class EndPointListener { #region Private Fields private List<HttpListenerPrefix> _all; // host == '+' private static readonly string _defaultCertFolderPath; private IPEndPoint _endpoint; private Dictionary<HttpListenerPrefix, HttpListener> _prefixes; private bool _secure; private Socket _socket; private ServerSslConfiguration _sslConfig; private List<HttpListenerPrefix> _unhandled; // host == '*' private Dictionary<HttpConnection, HttpConnection> _unregistered; private object _unregisteredSync; #endregion #region Static Constructor static EndPointListener () { _defaultCertFolderPath = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); } #endregion #region Internal Constructors internal EndPointListener ( IPAddress address, int port, bool secure, string certificateFolderPath, ServerSslConfiguration sslConfig, bool reuseAddress ) { if (secure) { var cert = getCertificate (port, certificateFolderPath, sslConfig.ServerCertificate); if (cert == null) throw new ArgumentException ("No server certificate could be found."); _secure = secure; _sslConfig = sslConfig; _sslConfig.ServerCertificate = cert; } _prefixes = new Dictionary<HttpListenerPrefix, HttpListener> (); _unregistered = new Dictionary<HttpConnection, HttpConnection> (); _unregisteredSync = ((ICollection) _unregistered).SyncRoot; _socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (reuseAddress) _socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _endpoint = new IPEndPoint (address, port); _socket.Bind (_endpoint); _socket.Listen (500); _socket.BeginAccept (onAccept, this); } #endregion #region Public Properties public IPAddress Address { get { return _endpoint.Address; } } public bool IsSecure { get { return _secure; } } public int Port { get { return _endpoint.Port; } } public ServerSslConfiguration SslConfiguration { get { return _sslConfig; } } #endregion #region Private Methods private static void addSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix) { var path = prefix.Path; foreach (var pref in prefixes) { if (pref.Path == path) throw new HttpListenerException (87, "The prefix is already in use."); } prefixes.Add (prefix); } private void checkIfRemove () { if (_prefixes.Count > 0) return; var prefs = _unhandled; if (prefs != null && prefs.Count > 0) return; prefs = _all; if (prefs != null && prefs.Count > 0) return; EndPointManager.RemoveEndPoint (this); } private static RSACryptoServiceProvider createRSAFromFile (string filename) { byte[] pvk = null; using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { pvk = new byte[fs.Length]; fs.Read (pvk, 0, pvk.Length); } var rsa = new RSACryptoServiceProvider (); rsa.ImportCspBlob (pvk); return rsa; } private static X509Certificate2 getCertificate ( int port, string folderPath, X509Certificate2 defaultCertificate ) { if (folderPath == null || folderPath.Length == 0) folderPath = _defaultCertFolderPath; try { var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port)); var key = Path.Combine (folderPath, String.Format ("{0}.key", port)); if (File.Exists (cer) && File.Exists (key)) { var cert = new X509Certificate2 (cer); cert.PrivateKey = createRSAFromFile (key); return cert; } } catch { } return defaultCertificate; } private static void onAccept (IAsyncResult asyncResult) { var lsnr = (EndPointListener) asyncResult.AsyncState; Socket sock = null; try { sock = lsnr._socket.EndAccept (asyncResult); } catch (SocketException) { // TODO: Should log the error code when this class has a logging. } catch (ObjectDisposedException) { return; } try { lsnr._socket.BeginAccept (onAccept, lsnr); } catch { if (sock != null) sock.Close (); return; } if (sock == null) return; processAccepted (sock, lsnr); } private static void processAccepted (Socket socket, EndPointListener listener) { HttpConnection conn = null; try { conn = new HttpConnection (socket, listener); lock (listener._unregisteredSync) listener._unregistered[conn] = conn; conn.BeginReadRequest (); } catch { if (conn != null) { conn.Close (true); return; } socket.Close (); } } private static bool removeSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix) { var path = prefix.Path; var cnt = prefixes.Count; for (var i = 0; i < cnt; i++) { if (prefixes[i].Path == path) { prefixes.RemoveAt (i); return true; } } return false; } private HttpListener searchHttpListener (Uri uri, out HttpListenerPrefix prefix) { prefix = null; if (uri == null) return null; var host = uri.Host; var dns = Uri.CheckHostName (host) == UriHostNameType.Dns; var port = uri.Port.ToString (); var path = HttpUtility.UrlDecode (uri.AbsolutePath); var pathSlash = path[path.Length - 1] != '/' ? path + "/" : path; HttpListener bestMatch = null; if (host != null && host.Length > 0) { var bestLen = -1; foreach (var pref in _prefixes.Keys) { if (dns) { var prefHost = pref.Host; if (Uri.CheckHostName (prefHost) == UriHostNameType.Dns && prefHost != host) continue; } if (pref.Port != port) continue; var prefPath = pref.Path; var len = prefPath.Length; if (len < bestLen) continue; if (path.StartsWith (prefPath) || pathSlash.StartsWith (prefPath)) { bestLen = len; bestMatch = _prefixes[pref]; prefix = pref; } } if (bestLen != -1) return bestMatch; } var prefs = _unhandled; bestMatch = searchHttpListenerFromSpecial (path, prefs, out prefix); if (bestMatch == null && pathSlash != path) bestMatch = searchHttpListenerFromSpecial (pathSlash, prefs, out prefix); if (bestMatch != null) return bestMatch; prefs = _all; bestMatch = searchHttpListenerFromSpecial (path, prefs, out prefix); if (bestMatch == null && pathSlash != path) bestMatch = searchHttpListenerFromSpecial (pathSlash, prefs, out prefix); return bestMatch; } private static HttpListener searchHttpListenerFromSpecial ( string path, List<HttpListenerPrefix> prefixes, out HttpListenerPrefix prefix ) { prefix = null; if (prefixes == null) return null; HttpListener bestMatch = null; var bestLen = -1; foreach (var pref in prefixes) { var prefPath = pref.Path; var len = prefPath.Length; if (len < bestLen) continue; if (path.StartsWith (prefPath)) { bestLen = len; bestMatch = pref.Listener; prefix = pref; } } return bestMatch; } #endregion #region Internal Methods internal bool BindHttpListenerTo (HttpListenerContext context) { HttpListenerPrefix pref; var lsnr = searchHttpListener (context.Request.Url, out pref); if (lsnr == null) return false; context.Listener = lsnr; context.Connection.Prefix = pref; return true; } internal static bool CertificateExists (int port, string folderPath) { if (folderPath == null || folderPath.Length == 0) folderPath = _defaultCertFolderPath; var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port)); var key = Path.Combine (folderPath, String.Format ("{0}.key", port)); return File.Exists (cer) && File.Exists (key); } internal void RemoveConnection (HttpConnection connection) { lock (_unregisteredSync) _unregistered.Remove (connection); } #endregion #region Public Methods public void AddPrefix (HttpListenerPrefix prefix, HttpListener listener) { List<HttpListenerPrefix> current, future; if (prefix.Host == "*") { do { current = _unhandled; future = current != null ? new List<HttpListenerPrefix> (current) : new List<HttpListenerPrefix> (); prefix.Listener = listener; addSpecial (future, prefix); } while (Interlocked.CompareExchange (ref _unhandled, future, current) != current); return; } if (prefix.Host == "+") { do { current = _all; future = current != null ? new List<HttpListenerPrefix> (current) : new List<HttpListenerPrefix> (); prefix.Listener = listener; addSpecial (future, prefix); } while (Interlocked.CompareExchange (ref _all, future, current) != current); return; } Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2; do { prefs = _prefixes; if (prefs.ContainsKey (prefix)) { if (prefs[prefix] != listener) { throw new HttpListenerException ( 87, String.Format ("There's another listener for {0}.", prefix) ); } return; } prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs); prefs2[prefix] = listener; } while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs); } public void Close () { _socket.Close (); HttpConnection[] conns = null; lock (_unregisteredSync) { if (_unregistered.Count == 0) return; var keys = _unregistered.Keys; conns = new HttpConnection[keys.Count]; keys.CopyTo (conns, 0); _unregistered.Clear (); } for (var i = conns.Length - 1; i >= 0; i--) conns[i].Close (true); } public void RemovePrefix (HttpListenerPrefix prefix, HttpListener listener) { List<HttpListenerPrefix> current, future; if (prefix.Host == "*") { do { current = _unhandled; if (current == null) break; future = new List<HttpListenerPrefix> (current); if (!removeSpecial (future, prefix)) break; // The prefix wasn't found. } while (Interlocked.CompareExchange (ref _unhandled, future, current) != current); checkIfRemove (); return; } if (prefix.Host == "+") { do { current = _all; if (current == null) break; future = new List<HttpListenerPrefix> (current); if (!removeSpecial (future, prefix)) break; // The prefix wasn't found. } while (Interlocked.CompareExchange (ref _all, future, current) != current); checkIfRemove (); return; } Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2; do { prefs = _prefixes; if (!prefs.ContainsKey (prefix)) break; prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs); prefs2.Remove (prefix); } while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs); checkIfRemove (); } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using HetsApi.Authorization; using HetsApi.Helpers; using HetsApi.Model; using HetsData.Helpers; using HetsData.Entities; using HetsData.Repositories; using HetsData.Dtos; using AutoMapper; namespace HetsApi.Controllers { /// <summary> /// Project Controller /// </summary> [Route("api/projects")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class ProjectController : ControllerBase { private readonly DbAppContext _context; private readonly IConfiguration _configuration; private readonly IMapper _mapper; private readonly IProjectRepository _projectRepo; private readonly IRentalRequestRepository _rentalRequestRepo; private readonly IRentalAgreementRepository _rentalAgreementRepo; public ProjectController(DbAppContext context, IConfiguration configuration, IMapper mapper, IProjectRepository projectRepo, IRentalRequestRepository rentalRequestRepo, IRentalAgreementRepository rentalAgreementRepo) { _context = context; _configuration = configuration; _mapper = mapper; _projectRepo = projectRepo; _rentalRequestRepo = rentalRequestRepo; _rentalAgreementRepo = rentalAgreementRepo; } /// <summary> /// Get project by id /// </summary> /// <param name="id">id of Project to fetch</param> [HttpGet] [Route("{id}")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<ProjectDto> ProjectsIdGet([FromRoute] int id) { // get current district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); return new ObjectResult(new HetsResponse(_projectRepo.GetRecord(id, districtId))); } /// <summary> /// Update project /// </summary> /// <param name="id">id of Project to update</param> /// <param name="item"></param> [HttpPut] [Route("{id}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<ProjectDto> ProjectsIdPut([FromRoute] int id, [FromBody] ProjectDto item) { if (item == null || id != item.ProjectId) { // not found return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get record HetProject project = _context.HetProjects.First(a => a.ProjectId == id); int? statusId = StatusHelper.GetStatusId(item.Status, "projectStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); project.ConcurrencyControlNumber = item.ConcurrencyControlNumber; project.Name = item.Name; project.ProvincialProjectNumber = item.ProvincialProjectNumber; project.ProjectStatusTypeId = (int)statusId; project.Information = item.Information; // HETS-1006 - Go - Live: Add additional fields for projects project.FiscalYear = item.FiscalYear; project.ResponsibilityCentre = item.ResponsibilityCentre; project.ServiceLine = item.ServiceLine; project.Stob = item.Stob; project.Product = item.Product; project.BusinessFunction = item.BusinessFunction; project.WorkActivity = item.WorkActivity; project.CostType = item.CostType; if (item.District != null) { project.DistrictId = item.District.DistrictId; } if (item.PrimaryContact != null) { project.PrimaryContactId = item.PrimaryContact.ContactId; } // save the changes _context.SaveChanges(); // retrieve updated project record to return to ui return new ObjectResult(new HetsResponse(_projectRepo.GetRecord(id))); } /// <summary> /// Create project /// </summary> /// <param name="item"></param> [HttpPost] [Route("")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<ProjectDto> ProjectsPost([FromBody] ProjectDto item) { // not found if (item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int? statusId = StatusHelper.GetStatusId(item.Status, "projectStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); HetProject project = new HetProject { Name = item.Name, ProvincialProjectNumber = item.ProvincialProjectNumber, ProjectStatusTypeId = (int)statusId, Information = item.Information, DistrictId = item.District.DistrictId, // HETS-1006 - Go - Live: Add additional fields for projects FiscalYear = item.FiscalYear, ResponsibilityCentre = item.ResponsibilityCentre, ServiceLine = item.ServiceLine, Stob = item.Stob, Product = item.Product, BusinessFunction = item.BusinessFunction, WorkActivity = item.WorkActivity, CostType = item.CostType }; _context.HetProjects.Add(project); // save record _context.SaveChanges(); int id = project.ProjectId; // retrieve updated project record to return to ui return new ObjectResult(new HetsResponse(_projectRepo.GetRecord(id))); } #region Project Search /// <summary> /// Searches Projects /// </summary> /// <remarks>Used for the project search page.</remarks> /// <param name="districts">Districts (comma separated list of id numbers)</param> /// <param name="project">name or partial name for a Project</param> /// <param name="hasRequests">if true then only include Projects with active Requests</param> /// <param name="hasHires">if true then only include Projects with active Rental Agreements</param> /// <param name="status">if included, filter the results to those with a status matching this string</param> /// <param name="projectNumber"></param> /// <param name="fiscalYear"></param> [HttpGet] [Route("search")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<ProjectLite>> ProjectsSearchGet([FromQuery] string districts, [FromQuery] string project, [FromQuery] bool? hasRequests, [FromQuery] bool? hasHires, [FromQuery] string status, [FromQuery] string projectNumber, [FromQuery] string fiscalYear) { int?[] districtTokens = ArrayHelper.ParseIntArray(districts); // get initial results - must be limited to user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); IQueryable<HetProject> data = _context.HetProjects.AsNoTracking() .Include(x => x.ProjectStatusType) .Include(x => x.District.Region) .Include(x => x.PrimaryContact) .Include(x => x.HetRentalAgreements) .Include(x => x.HetRentalRequests) .Where(x => x.DistrictId.Equals(districtId)); if (districtTokens != null && districts.Length > 0) { data = data.Where(x => districtTokens.Contains(x.DistrictId)); } if (project != null) { data = data.Where(x => x.Name.ToLower().Contains(project.ToLower())); } if (status != null) { int? statusId = StatusHelper.GetStatusId(status, "projectStatus", _context); if (statusId != null) { data = data.Where(x => x.ProjectStatusTypeId == statusId); } } if (projectNumber != null) { // allow for case insensitive search of project name data = data.Where(x => x.ProvincialProjectNumber.ToLower().Contains(projectNumber.ToLower())); } if (!string.IsNullOrEmpty(fiscalYear)) { data = data.Where(x => x.FiscalYear.Equals(fiscalYear)); } // convert Project Model to the "ProjectLite" Model List<ProjectLite> result = new List<ProjectLite>(); foreach (HetProject item in data) { result.Add(_projectRepo.ToLiteModel(item)); } // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion #region Get all projects by region /// <summary> /// Get all projects by district /// </summary> [HttpGet] [Route("")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<ProjectLite>> ProjectsGet([FromQuery] bool currentFiscal = true) { // get initial results - must be limited to user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get fiscal year HetDistrictStatus status = _context.HetDistrictStatuses.AsNoTracking() .First(x => x.DistrictId == districtId); int? fiscalYear = status.CurrentFiscalYear; if (fiscalYear == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); string fiscalYearStr = $"{fiscalYear}/{fiscalYear + 1}"; // HETS-1005 - Time entry tab search issues // * we need retrieve all projects that have been created this year // since users can add time records to closed projects IQueryable<HetProject> projects = _context.HetProjects.AsNoTracking() .Where(x => x.DistrictId.Equals(districtId) && (!currentFiscal || x.FiscalYear.Equals(fiscalYearStr))); // convert Project Model to the "ProjectLite" Model List<ProjectLite> result = new List<ProjectLite>(); foreach (HetProject item in projects) { result.Add(_projectRepo.ToLiteModel(item)); } // return to the client return new ObjectResult(new HetsResponse(result)); } /// <summary> /// Get all projects by district for rental agreement summary filtering /// </summary> [HttpGet] [Route("agreementSummary")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<ProjectAgreementSummary>> ProjectsGetAgreementSummary() { // get user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); var result = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.Project) .Where(x => x.DistrictId.Equals(districtId) && !x.Number.StartsWith("BCBid")) .ToList() .GroupBy(x => x.Project, (p, agreements) => new ProjectAgreementSummary { Id = p.ProjectId, Name = p.Name, AgreementIds = agreements.Select(y => y.RentalAgreementId).Distinct().ToList(), }) .ToList(); // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion #region Clone Project Agreements /// <summary> /// Get rental agreements associated with a project by id /// </summary> /// <remarks>Gets a Projects Rental Agreements</remarks> /// <param name="id">id of Project to fetch agreements for</param> [HttpGet] [Route("{id}/rentalAgreements")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementDto>> ProjectsIdRentalAgreementsGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); List<HetRentalAgreement> agreements = _context.HetProjects.AsNoTracking() .Include(x => x.ProjectStatusType) .Include(x => x.HetRentalAgreements) .ThenInclude(e => e.Equipment) .ThenInclude(d => d.DistrictEquipmentType) .Include(x => x.HetRentalAgreements) .ThenInclude(e => e.Equipment) .ThenInclude(a => a.HetEquipmentAttachments) .Include(x => x.HetRentalAgreements) .ThenInclude(e => e.RentalAgreementStatusType) .First(x => x.ProjectId == id) .HetRentalAgreements .ToList(); return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalAgreementDto>>(agreements))); } /// <summary> /// Update a rental agreement by cloning a previous project rental agreement /// </summary> /// <param name="id">Project id</param> /// <param name="item"></param> [HttpPost] [Route("{id}/rentalAgreementClone")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> ProjectsRentalAgreementClonePost([FromRoute] int id, [FromBody] ProjectRentalAgreementClone item) { // not found if (item == null || id != item.ProjectId) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get all agreements for this project HetProject project = _context.HetProjects .Include(x => x.ProjectStatusType) .Include(x => x.HetRentalAgreements) .ThenInclude(y => y.HetRentalAgreementRates) .Include(x => x.HetRentalAgreements) .ThenInclude(y => y.HetRentalAgreementConditions) .Include(x => x.HetRentalAgreements) .ThenInclude(e => e.RentalAgreementStatusType) .Include(x => x.HetRentalAgreements) .ThenInclude(y => y.HetTimeRecords) .First(a => a.ProjectId == id); List<HetRentalAgreement> agreements = project.HetRentalAgreements.ToList(); // check that the rental agreements exist exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreementId); // (RENTAL AGREEMENT) not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // check that the rental agreement to clone exist exists = agreements.Any(a => a.RentalAgreementId == item.AgreementToCloneId); // (RENTAL AGREEMENT) not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-11", ErrorViewModel.GetDescription("HETS-11", _configuration))); int agreementToCloneIndex = agreements.FindIndex(a => a.RentalAgreementId == item.AgreementToCloneId); int newRentalAgreementIndex = agreements.FindIndex(a => a.RentalAgreementId == item.RentalAgreementId); // ****************************************************************** // Business Rules in the backend: // *Can't clone into an Agreement if it isn't Active // *Can't clone into an Agreement if it has existing time records // ****************************************************************** if (!agreements[newRentalAgreementIndex].RentalAgreementStatusType.Description .Equals("Active", StringComparison.InvariantCultureIgnoreCase)) { // (RENTAL AGREEMENT) is not active return new BadRequestObjectResult(new HetsResponse("HETS-12", ErrorViewModel.GetDescription("HETS-12", _configuration))); } if (agreements[newRentalAgreementIndex].HetTimeRecords != null && agreements[newRentalAgreementIndex].HetTimeRecords.Count > 0) { // (RENTAL AGREEMENT) has time records return new BadRequestObjectResult(new HetsResponse("HETS-13", ErrorViewModel.GetDescription("HETS-13", _configuration))); } // ****************************************************************** // clone agreement // ****************************************************************** agreements[newRentalAgreementIndex].AgreementCity = agreements[agreementToCloneIndex].AgreementCity; agreements[newRentalAgreementIndex].EquipmentRate = agreements[agreementToCloneIndex].EquipmentRate; agreements[newRentalAgreementIndex].Note = agreements[agreementToCloneIndex].Note; agreements[newRentalAgreementIndex].RateComment = agreements[agreementToCloneIndex].RateComment; agreements[newRentalAgreementIndex].RatePeriodTypeId = agreements[agreementToCloneIndex].RatePeriodTypeId; // update rates agreements[newRentalAgreementIndex].HetRentalAgreementRates = null; foreach (HetRentalAgreementRate rate in agreements[agreementToCloneIndex].HetRentalAgreementRates) { HetRentalAgreementRate temp = new HetRentalAgreementRate { RentalAgreementId = id, Comment = rate.Comment, ComponentName = rate.ComponentName, Rate = rate.Rate, Set = rate.Set, Overtime = rate.Overtime, Active = rate.Active, IsIncludedInTotal = rate.IsIncludedInTotal, RatePeriodTypeId = rate.RatePeriodTypeId }; if (agreements[newRentalAgreementIndex].HetRentalAgreementRates == null) { agreements[newRentalAgreementIndex].HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreements[newRentalAgreementIndex].HetRentalAgreementRates.Add(temp); } // update overtime rates (and add if they don't exist) List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); foreach (HetProvincialRateType overtimeRate in overtime) { bool found = false; if (agreements[newRentalAgreementIndex] != null && agreements[newRentalAgreementIndex].HetRentalAgreementRates != null) { found = agreements[newRentalAgreementIndex].HetRentalAgreementRates.Any(x => x.ComponentName == overtimeRate.RateType); } if (found) { HetRentalAgreementRate rate = agreements[newRentalAgreementIndex].HetRentalAgreementRates .First(x => x.ComponentName == overtimeRate.RateType); rate.Rate = overtimeRate.Rate; } else { HetRentalAgreementRate newRate = new HetRentalAgreementRate { RentalAgreementId = id, Comment = overtimeRate.Description, Rate = overtimeRate.Rate, ComponentName = overtimeRate.RateType, Active = overtimeRate.Active, IsIncludedInTotal = overtimeRate.IsIncludedInTotal, Overtime = overtimeRate.Overtime }; if (agreements[newRentalAgreementIndex].HetRentalAgreementRates == null) { agreements[newRentalAgreementIndex].HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreements[newRentalAgreementIndex].HetRentalAgreementRates.Add(newRate); } } // remove non-existent overtime rates List<string> remove = (from overtimeRate in agreements[newRentalAgreementIndex].HetRentalAgreementRates where overtimeRate.Overtime ?? false let found = overtime.Any(x => x.RateType == overtimeRate.ComponentName) where !found select overtimeRate.ComponentName).ToList(); if (remove.Count > 0 && agreements[newRentalAgreementIndex] != null && agreements[newRentalAgreementIndex].HetRentalAgreementRates != null) { foreach (string component in remove) { agreements[newRentalAgreementIndex].HetRentalAgreementRates.Remove( agreements[newRentalAgreementIndex].HetRentalAgreementRates.First(x => x.ComponentName == component)); } } // update conditions agreements[newRentalAgreementIndex].HetRentalAgreementConditions = null; foreach (HetRentalAgreementCondition condition in agreements[agreementToCloneIndex].HetRentalAgreementConditions) { HetRentalAgreementCondition temp = new HetRentalAgreementCondition { Comment = condition.Comment, ConditionName = condition.ConditionName }; if (agreements[newRentalAgreementIndex].HetRentalAgreementConditions == null) { agreements[newRentalAgreementIndex].HetRentalAgreementConditions = new List<HetRentalAgreementCondition>(); } agreements[newRentalAgreementIndex].HetRentalAgreementConditions.Add(temp); } // save the changes _context.SaveChanges(); // ****************************************************************** // return update rental agreement to update the screen // ****************************************************************** return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(item.RentalAgreementId))); } #endregion #region Project Time Records /// <summary> /// Get time records associated with a project /// </summary> /// <remarks>Gets a Projects Time Records</remarks> /// <param name="id">id of Project to fetch Time Records for</param> [HttpGet] [Route("{id}/timeRecords")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<TimeRecordDto>> HetProjectIdTimeRecordsGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get current district and fiscal year int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get fiscal year HetDistrictStatus status = _context.HetDistrictStatuses.AsNoTracking() .First(x => x.DistrictId == districtId); int? fiscalYear = status.CurrentFiscalYear; if (fiscalYear == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // fiscal year in the status table stores the "start" of the year DateTime fiscalYearStart = new DateTime((int)fiscalYear, 4, 1); HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetRentalAgreements) .ThenInclude(t => t.HetTimeRecords) .First(x => x.ProjectId == id); // create a single array of all time records List<HetTimeRecord> timeRecords = new List<HetTimeRecord>(); foreach (HetRentalAgreement rentalAgreement in project.HetRentalAgreements) { // only add records from this fiscal year timeRecords.AddRange(rentalAgreement.HetTimeRecords.Where(x => x.WorkedDate >= fiscalYearStart)); } return new ObjectResult(new HetsResponse(_mapper.Map<List<TimeRecordDto>>(timeRecords))); } /// <summary> /// Add a project time record /// </summary> /// <remarks>Adds Project Time Records</remarks> /// <param name="id">id of Project to add a time record for</param> /// <param name="item">Adds to Project Time Records</param> [HttpPost] [Route("{id}/timeRecord")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<TimeRecordDto>> ProjectsIdTimeRecordsPost([FromRoute] int id, [FromBody] TimeRecordDto item) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get project record HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetRentalAgreements) .ThenInclude(t => t.HetTimeRecords) .First(x => x.ProjectId == id); List<HetRentalAgreement> agreements = project.HetRentalAgreements.ToList(); // ****************************************************************** // must have a valid rental agreement id // ****************************************************************** if (item.RentalAgreementId == null || item.RentalAgreementId == 0) { // (RENTAL AGREEMENT) record not found return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreementId); if (!exists) { // (RENTAL AGREEMENT) record not found return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } // ****************************************************************** // add or update time record // ****************************************************************** int rentalAgreementId = (int)item.RentalAgreementId; // set the time period type id int? timePeriodTypeId = StatusHelper.GetTimePeriodId(item.TimePeriod, _context); if (timePeriodTypeId == null) throw new DataException("Time Period Id cannot be null"); if (item.TimeRecordId > 0) { // get time record HetTimeRecord time = _context.HetTimeRecords.FirstOrDefault(x => x.TimeRecordId == item.TimeRecordId); // not found if (time == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); time.ConcurrencyControlNumber = item.ConcurrencyControlNumber; time.RentalAgreementId = rentalAgreementId; time.EnteredDate = DateTime.UtcNow; time.Hours = item.Hours; time.TimePeriod = item.TimePeriod; time.TimePeriodTypeId = (int)timePeriodTypeId; time.WorkedDate = item.WorkedDate; } else // add time record { HetTimeRecord time = new HetTimeRecord { RentalAgreementId = rentalAgreementId, EnteredDate = DateTime.UtcNow, Hours = item.Hours, TimePeriod = item.TimePeriod, TimePeriodTypeId = (int)timePeriodTypeId, WorkedDate = item.WorkedDate }; _context.HetTimeRecords.Add(time); } // save record _context.SaveChanges(); // ************************************************************* // return updated time records // ************************************************************* project = _context.HetProjects.AsNoTracking() .Include(x => x.HetRentalAgreements) .ThenInclude(t => t.HetTimeRecords) .First(x => x.ProjectId == id); // create a single array of all time records List<HetTimeRecord> timeRecords = new List<HetTimeRecord>(); foreach (HetRentalAgreement rentalAgreement in project.HetRentalAgreements) { timeRecords.AddRange(rentalAgreement.HetTimeRecords); } return new ObjectResult(new HetsResponse(_mapper.Map<List<TimeRecordDto>>(timeRecords))); } #endregion #region Project Equipment /// <summary> /// Get equipment associated with a project /// </summary> /// <remarks>Gets a Projects Equipment</remarks> /// <param name="id">id of Project to fetch Equipment for</param> [HttpGet] [Route("{id}/equipment")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementDto>> ProjectsIdEquipmentGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetRentalAgreements) .ThenInclude(e => e.Equipment) .ThenInclude(o => o.Owner) .ThenInclude(c => c.PrimaryContact) .First(x => x.ProjectId == id); return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalAgreementDto>>(project.HetRentalAgreements))); } #endregion #region Project Attachments /// <summary> /// Get attachments associated with a project /// </summary> /// <remarks>Returns attachments for a particular Project</remarks> /// <param name="id">id of Project to fetch attachments for</param> [HttpGet] [Route("{id}/attachments")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<DigitalFileDto>> ProjectsIdAttachmentsGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetDigitalFiles) .First(a => a.ProjectId == id); // extract the attachments and update properties for UI List<HetDigitalFile> attachments = new List<HetDigitalFile>(); foreach (HetDigitalFile attachment in project.HetDigitalFiles) { if (attachment != null) { attachment.FileSize = attachment.FileContents.Length; attachment.LastUpdateTimestamp = attachment.AppLastUpdateTimestamp; attachment.LastUpdateUserid = attachment.AppLastUpdateUserid; attachment.UserName = UserHelper.GetUserName(attachment.LastUpdateUserid, _context); attachments.Add(attachment); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<DigitalFileDto>>(attachments))); } #endregion #region Project Contacts /// <summary> /// Get contacts associated with a project /// </summary> /// <remarks>Gets an Projects Contacts</remarks> /// <param name="id">id of Project to fetch Contacts for</param> [HttpGet] [Route("{id}/contacts")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<ContactDto>> ProjectsIdContactsGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetContacts) .First(a => a.ProjectId == id); return new ObjectResult(new HetsResponse(_mapper.Map<List<ContactDto>>(project.HetContacts.ToList()))); } /// <summary> /// Add a project contact /// </summary> /// <remarks>Adds Project Contact</remarks> /// <param name="id">id of Project to add a contact for</param> /// <param name="primary">is this the primary contact</param> /// <param name="item">Adds to Project Contact</param> [HttpPost] [Route("{id}/contacts/{primary}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<ContactDto> ProjectsIdContactsPost([FromRoute] int id, [FromBody] ContactDto item, bool primary) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int contactId; // get project record HetProject project = _context.HetProjects .Include(x => x.HetContacts) .First(a => a.ProjectId == id); // add or update contact if (item.ContactId > 0) { HetContact contact = project.HetContacts.FirstOrDefault(a => a.ContactId == item.ContactId); // not found if (contact == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); contactId = item.ContactId; contact.ConcurrencyControlNumber = item.ConcurrencyControlNumber; contact.ProjectId = project.ProjectId; contact.Notes = item.Notes; contact.Address1 = item.Address1; contact.Address2 = item.Address2; contact.City = item.City; contact.EmailAddress = item.EmailAddress; contact.WorkPhoneNumber = item.WorkPhoneNumber; contact.FaxPhoneNumber = item.FaxPhoneNumber; contact.GivenName = item.GivenName; contact.MobilePhoneNumber = item.MobilePhoneNumber; contact.PostalCode = item.PostalCode; contact.Province = item.Province; contact.Surname = item.Surname; contact.Role = item.Role; if (primary) { project.PrimaryContactId = contactId; } } else // add contact { HetContact contact = new HetContact { ProjectId = project.ProjectId, Notes = item.Notes, Address1 = item.Address1, Address2 = item.Address2, City = item.City, EmailAddress = item.EmailAddress, WorkPhoneNumber = item.WorkPhoneNumber, FaxPhoneNumber = item.FaxPhoneNumber, GivenName = item.GivenName, MobilePhoneNumber = item.MobilePhoneNumber, PostalCode = item.PostalCode, Province = item.Province, Surname = item.Surname, Role = item.Role }; _context.HetContacts.Add(contact); _context.SaveChanges(); contactId = contact.ContactId; if (primary) { project.PrimaryContactId = contactId; } } _context.SaveChanges(); // get updated contact record HetProject updatedProject = _context.HetProjects.AsNoTracking() .Include(x => x.HetContacts) .First(a => a.ProjectId == id); HetContact updatedContact = updatedProject.HetContacts .FirstOrDefault(a => a.ContactId == contactId); return new ObjectResult(new HetsResponse(_mapper.Map<ContactDto>(updatedContact))); } /// <summary> /// Update all project contacts /// </summary> /// <remarks>Replaces an Project&#39;s Contacts</remarks> /// <param name="id">id of Project to replace Contacts for</param> /// <param name="items">Replacement Project contacts.</param> [HttpPut] [Route("{id}/contacts")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<ContactDto>> ProjectsIdContactsPut([FromRoute] int id, [FromBody] ContactDto[] items) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists || items == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get project record HetProject project = _context.HetProjects .Include(x => x.HetContacts) .First(a => a.ProjectId == id); // adjust the incoming list for (int i = 0; i < items.Length; i++) { var item = items[i]; if (item != null) { bool contactExists = project.HetContacts.Any(x => x.ContactId == item.ContactId); if (contactExists) { HetContact contact = _context.HetContacts.First(x => x.ContactId == item.ContactId); contact.ConcurrencyControlNumber = item.ConcurrencyControlNumber; contact.ProjectId = id; contact.Notes = item.Notes; contact.Address1 = item.Address1; contact.Address2 = item.Address2; contact.City = item.City; contact.EmailAddress = item.EmailAddress; contact.FaxPhoneNumber = item.FaxPhoneNumber; contact.GivenName = item.GivenName; contact.MobilePhoneNumber = item.MobilePhoneNumber; contact.PostalCode = item.PostalCode; contact.Province = item.Province; contact.Surname = item.Surname; contact.Role = item.Role; } else { HetContact contact = new HetContact { ProjectId = id, Notes = item.Notes, Address1 = item.Address1, Address2 = item.Address2, City = item.City, EmailAddress = item.EmailAddress, FaxPhoneNumber = item.FaxPhoneNumber, GivenName = item.GivenName, MobilePhoneNumber = item.MobilePhoneNumber, PostalCode = item.PostalCode, Province = item.Province, Surname = item.Surname, Role = item.Role }; project.HetContacts.Add(contact); } } } // remove contacts that are no longer attached. foreach (HetContact contact in project.HetContacts) { if (contact != null && items.All(x => x.ContactId != contact.ContactId)) { _context.HetContacts.Remove(contact); } } // save changes _context.SaveChanges(); // get updated contact records HetProject updatedProject = _context.HetProjects.AsNoTracking() .Include(x => x.HetContacts) .First(a => a.ProjectId == id); return new ObjectResult(new HetsResponse(_mapper.Map<List<ContactDto>>(updatedProject.HetContacts.ToList()))); } #endregion #region Project History /// <summary> /// Get history associated with a project /// </summary> /// <remarks>Returns History for a particular Project</remarks> /// <param name="id">id of Project to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> [HttpGet] [Route("{id}/history")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<History>> ProjectsIdHistoryGet([FromRoute] int id, [FromQuery] int? offset, [FromQuery] int? limit) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); return new ObjectResult(new HetsResponse(ProjectHelper.GetHistoryRecords(id, offset, limit, _context))); } /// <summary> /// Create project history /// </summary> /// <remarks>Add a History record to the Project</remarks> /// <param name="id">id of Project to fetch History for</param> /// <param name="item"></param> [HttpPost] [Route("{id}/history")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<History> ProjectsIdHistoryPost([FromRoute] int id, [FromBody] History item) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); if (exists) { HetHistory history = new HetHistory { HistoryText = item.HistoryText, CreatedDate = DateTime.UtcNow, ProjectId = id }; _context.HetHistories.Add(history); _context.SaveChanges(); } return new ObjectResult(new HetsResponse(ProjectHelper.GetHistoryRecords(id, null, null, _context))); } #endregion #region Project Note Records /// <summary> /// Get note records associated with project /// </summary> /// <param name="id">id of Project to fetch Notes for</param> [HttpGet] [Route("{id}/notes")] [RequiresPermission(HetPermission.Login)] public virtual IActionResult ProjectsIdNotesGet([FromRoute] int id) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetNotes) .First(x => x.ProjectId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in project.HetNotes) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes))); } /// <summary> /// Update or create a note associated with a project /// </summary> /// <remarks>Update a Projects Notes</remarks> /// <param name="id">id of Project to update Notes for</param> /// <param name="item">Project Note</param> [HttpPost] [Route("{id}/note")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<NoteDto>> ProjectsIdNotePost([FromRoute] int id, [FromBody] NoteDto item) { bool exists = _context.HetProjects.Any(a => a.ProjectId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // add or update note if (item.NoteId > 0) { // get note HetNote note = _context.HetNotes.FirstOrDefault(a => a.NoteId == item.NoteId); // not found if (note == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); note.ConcurrencyControlNumber = item.ConcurrencyControlNumber; note.ProjectId = id; note.Text = item.Text; note.IsNoLongerRelevant = item.IsNoLongerRelevant; } else // add note { HetNote note = new HetNote { ProjectId = id, Text = item.Text, IsNoLongerRelevant = item.IsNoLongerRelevant }; _context.HetNotes.Add(note); } _context.SaveChanges(); // return updated note records HetProject project = _context.HetProjects.AsNoTracking() .Include(x => x.HetNotes) .First(x => x.ProjectId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in project.HetNotes) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes))); } #endregion #region Get Project by Name and District /// <summary> /// Get a project by name and district (active only) /// </summary> /// <param name="name">name of the project to find</param> [HttpPost] [Route("projectsByName")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<ProjectLite>> ProjectsGetByName([FromBody] string name) { // get current users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); HetDistrict district = _context.HetDistricts.AsNoTracking() .FirstOrDefault(x => x.DistrictId.Equals(districtId)); if (district == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // find agreements IQueryable<HetProject> data = _context.HetProjects.AsNoTracking() .Include(x => x.ProjectStatusType) .Include(x => x.District.Region) .Include(x => x.PrimaryContact) .Include(x => x.HetRentalAgreements) .Include(x => x.HetRentalRequests) .Where(x => x.DistrictId.Equals(districtId)); if (name != null) { // allow for case insensitive search of project name data = data.Where(x => x.Name.ToUpper() == name.ToUpper()); } // convert Project Model to the "ProjectLite" Model List<ProjectLite> result = new List<ProjectLite>(); foreach (HetProject item in data) { result.Add(_projectRepo.ToLiteModel(item)); } // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Unit.Tests { public class RangeHeaderValueTest { [Fact] public void Ctor_InvalidRange_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new RangeHeaderValue(5, 2); }); } [Fact] public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation() { RangeHeaderValue range = new RangeHeaderValue(); range.Unit = "myunit"; Assert.Equal("myunit", range.Unit); Assert.Throws<ArgumentException>(() => { range.Unit = null; }); Assert.Throws<ArgumentException>(() => { range.Unit = ""; }); Assert.Throws<FormatException>(() => { range.Unit = " x"; }); Assert.Throws<FormatException>(() => { range.Unit = "x "; }); Assert.Throws<FormatException>(() => { range.Unit = "x y"; }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { RangeHeaderValue range = new RangeHeaderValue(); range.Unit = "myunit"; range.Ranges.Add(new RangeItemHeaderValue(1, 3)); Assert.Equal("myunit=1-3", range.ToString()); range.Ranges.Add(new RangeItemHeaderValue(5, null)); range.Ranges.Add(new RangeItemHeaderValue(null, 17)); Assert.Equal("myunit=1-3, 5-, -17", range.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { RangeHeaderValue range1 = new RangeHeaderValue(1, 2); RangeHeaderValue range2 = new RangeHeaderValue(1, 2); range2.Unit = "BYTES"; RangeHeaderValue range3 = new RangeHeaderValue(1, null); RangeHeaderValue range4 = new RangeHeaderValue(null, 2); RangeHeaderValue range5 = new RangeHeaderValue(); range5.Ranges.Add(new RangeItemHeaderValue(1, 2)); range5.Ranges.Add(new RangeItemHeaderValue(3, 4)); RangeHeaderValue range6 = new RangeHeaderValue(); range6.Ranges.Add(new RangeItemHeaderValue(3, 4)); // reverse order of range5 range6.Ranges.Add(new RangeItemHeaderValue(1, 2)); Assert.Equal(range1.GetHashCode(), range2.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range4.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode()); Assert.Equal(range5.GetHashCode(), range6.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { RangeHeaderValue range1 = new RangeHeaderValue(1, 2); RangeHeaderValue range2 = new RangeHeaderValue(1, 2); range2.Unit = "BYTES"; RangeHeaderValue range3 = new RangeHeaderValue(1, null); RangeHeaderValue range4 = new RangeHeaderValue(null, 2); RangeHeaderValue range5 = new RangeHeaderValue(); range5.Ranges.Add(new RangeItemHeaderValue(1, 2)); range5.Ranges.Add(new RangeItemHeaderValue(3, 4)); RangeHeaderValue range6 = new RangeHeaderValue(); range6.Ranges.Add(new RangeItemHeaderValue(3, 4)); // reverse order of range5 range6.Ranges.Add(new RangeItemHeaderValue(1, 2)); RangeHeaderValue range7 = new RangeHeaderValue(1, 2); range7.Unit = "other"; Assert.False(range1.Equals(null), "bytes=1-2 vs. <null>"); Assert.True(range1.Equals(range2), "bytes=1-2 vs. BYTES=1-2"); Assert.False(range1.Equals(range3), "bytes=1-2 vs. bytes=1-"); Assert.False(range1.Equals(range4), "bytes=1-2 vs. bytes=-2"); Assert.False(range1.Equals(range5), "bytes=1-2 vs. bytes=1-2,3-4"); Assert.True(range5.Equals(range6), "bytes=1-2,3-4 vs. bytes=3-4,1-2"); Assert.False(range1.Equals(range7), "bytes=1-2 vs. other=1-2"); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { RangeHeaderValue source = new RangeHeaderValue(1, 2); RangeHeaderValue clone = (RangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(1, source.Ranges.Count); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.Ranges.Count, clone.Ranges.Count); Assert.Equal(source.Ranges.ElementAt(0), clone.Ranges.ElementAt(0)); source.Unit = "custom"; source.Ranges.Add(new RangeItemHeaderValue(3, null)); source.Ranges.Add(new RangeItemHeaderValue(null, 4)); clone = (RangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(3, source.Ranges.Count); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.Ranges.Count, clone.Ranges.Count); Assert.Equal(source.Ranges.ElementAt(0), clone.Ranges.ElementAt(0)); Assert.Equal(source.Ranges.ElementAt(1), clone.Ranges.ElementAt(1)); Assert.Equal(source.Ranges.ElementAt(2), clone.Ranges.ElementAt(2)); } [Fact] public void GetRangeLength_DifferentValidScenarios_AllReturnNonZero() { RangeHeaderValue result = null; CallGetRangeLength(" custom = 1 - 2", 1, 14, out result); Assert.Equal("custom", result.Unit); Assert.Equal(1, result.Ranges.Count); Assert.Equal(new RangeItemHeaderValue(1, 2), result.Ranges.First()); CallGetRangeLength("bytes =1-2,,3-, , ,-4,,", 0, 23, out result); Assert.Equal("bytes", result.Unit); Assert.Equal(3, result.Ranges.Count); Assert.Equal(new RangeItemHeaderValue(1, 2), result.Ranges.ElementAt(0)); Assert.Equal(new RangeItemHeaderValue(3, null), result.Ranges.ElementAt(1)); Assert.Equal(new RangeItemHeaderValue(null, 4), result.Ranges.ElementAt(2)); } [Fact] public void GetRangeLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetRangeLength(" bytes=1-2", 0); // no leading whitespaces allowed CheckInvalidGetRangeLength("bytes=1", 0); CheckInvalidGetRangeLength("bytes=", 0); CheckInvalidGetRangeLength("bytes", 0); CheckInvalidGetRangeLength("bytes 1-2", 0); CheckInvalidGetRangeLength("bytes=1-2.5", 0); CheckInvalidGetRangeLength("bytes= ,,, , ,,", 0); CheckInvalidGetRangeLength("", 0); CheckInvalidGetRangeLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" bytes=1-2 ", new RangeHeaderValue(1, 2)); RangeHeaderValue expected = new RangeHeaderValue(); expected.Unit = "custom"; expected.Ranges.Add(new RangeItemHeaderValue(null, 5)); expected.Ranges.Add(new RangeItemHeaderValue(1, 4)); CheckValidParse("custom = - 5 , 1 - 4 ,,", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("bytes=1-2x"); // only delimiter ',' allowed after last range CheckInvalidParse("x bytes=1-2"); CheckInvalidParse("bytes=1-2.4"); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" bytes=1-2 ", new RangeHeaderValue(1, 2)); RangeHeaderValue expected = new RangeHeaderValue(); expected.Unit = "custom"; expected.Ranges.Add(new RangeItemHeaderValue(null, 5)); expected.Ranges.Add(new RangeItemHeaderValue(1, 4)); CheckValidTryParse("custom = - 5 , 1 - 4 ,,", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("bytes=1-2x"); // only delimiter ',' allowed after last range CheckInvalidTryParse("x bytes=1-2"); CheckInvalidTryParse("bytes=1-2.4"); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, RangeHeaderValue expectedResult) { RangeHeaderValue result = RangeHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { RangeHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, RangeHeaderValue expectedResult) { RangeHeaderValue result = null; Assert.True(RangeHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { RangeHeaderValue result = null; Assert.False(RangeHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetRangeLength(string input, int startIndex, int expectedLength, out RangeHeaderValue result) { object temp = null; Assert.Equal(expectedLength, RangeHeaderValue.GetRangeLength(input, startIndex, out temp)); result = temp as RangeHeaderValue; } private static void CheckInvalidGetRangeLength(string input, int startIndex) { object result = null; Assert.Equal(0, RangeHeaderValue.GetRangeLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaxInt32() { var test = new SimpleBinaryOpTest__MaxInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MaxInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__MaxInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__MaxInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Max( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Max( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Max( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse41.Max(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MaxInt32(); var result = Sse41.Max(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != Math.Max(left[0], right[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Max(left[i], right[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Max)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
namespace android.database.sqlite { [global::MonoJavaBridge.JavaClass(typeof(global::android.database.sqlite.SQLiteProgram_))] public abstract partial class SQLiteProgram : android.database.sqlite.SQLiteClosable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SQLiteProgram() { InitJNI(); } protected SQLiteProgram(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _compile2890; protected virtual void compile(java.lang.String arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._compile2890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._compile2890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _close2891; public virtual void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._close2891); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._close2891); } internal static global::MonoJavaBridge.MethodId _onAllReferencesReleased2892; protected override void onAllReferencesReleased() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._onAllReferencesReleased2892); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._onAllReferencesReleased2892); } internal static global::MonoJavaBridge.MethodId _onAllReferencesReleasedFromContainer2893; protected override void onAllReferencesReleasedFromContainer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._onAllReferencesReleasedFromContainer2893); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._onAllReferencesReleasedFromContainer2893); } internal static global::MonoJavaBridge.MethodId _bindNull2894; public virtual void bindNull(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._bindNull2894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._bindNull2894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getUniqueId2895; public virtual int getUniqueId() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._getUniqueId2895); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._getUniqueId2895); } internal static global::MonoJavaBridge.MethodId _bindLong2896; public virtual void bindLong(int arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._bindLong2896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._bindLong2896, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _bindDouble2897; public virtual void bindDouble(int arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._bindDouble2897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._bindDouble2897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _bindString2898; public virtual void bindString(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._bindString2898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._bindString2898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _bindBlob2899; public virtual void bindBlob(int arg0, byte[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._bindBlob2899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._bindBlob2899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _clearBindings2900; public virtual void clearBindings() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._clearBindings2900); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._clearBindings2900); } internal static global::MonoJavaBridge.MethodId _native_compile2901; protected virtual void native_compile(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_compile2901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_compile2901, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _native_finalize2902; protected virtual void native_finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_finalize2902); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_finalize2902); } internal static global::MonoJavaBridge.MethodId _native_bind_null2903; protected virtual void native_bind_null(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_bind_null2903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_bind_null2903, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _native_bind_long2904; protected virtual void native_bind_long(int arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_bind_long2904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_bind_long2904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _native_bind_double2905; protected virtual void native_bind_double(int arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_bind_double2905, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_bind_double2905, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _native_bind_string2906; protected virtual void native_bind_string(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_bind_string2906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_bind_string2906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _native_bind_blob2907; protected virtual void native_bind_blob(int arg0, byte[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram._native_bind_blob2907, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.sqlite.SQLiteProgram.staticClass, global::android.database.sqlite.SQLiteProgram._native_bind_blob2907, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.sqlite.SQLiteProgram.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/sqlite/SQLiteProgram")); global::android.database.sqlite.SQLiteProgram._compile2890 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "compile", "(Ljava/lang/String;Z)V"); global::android.database.sqlite.SQLiteProgram._close2891 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "close", "()V"); global::android.database.sqlite.SQLiteProgram._onAllReferencesReleased2892 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "onAllReferencesReleased", "()V"); global::android.database.sqlite.SQLiteProgram._onAllReferencesReleasedFromContainer2893 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "onAllReferencesReleasedFromContainer", "()V"); global::android.database.sqlite.SQLiteProgram._bindNull2894 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "bindNull", "(I)V"); global::android.database.sqlite.SQLiteProgram._getUniqueId2895 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "getUniqueId", "()I"); global::android.database.sqlite.SQLiteProgram._bindLong2896 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "bindLong", "(IJ)V"); global::android.database.sqlite.SQLiteProgram._bindDouble2897 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "bindDouble", "(ID)V"); global::android.database.sqlite.SQLiteProgram._bindString2898 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "bindString", "(ILjava/lang/String;)V"); global::android.database.sqlite.SQLiteProgram._bindBlob2899 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "bindBlob", "(I[B)V"); global::android.database.sqlite.SQLiteProgram._clearBindings2900 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "clearBindings", "()V"); global::android.database.sqlite.SQLiteProgram._native_compile2901 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_compile", "(Ljava/lang/String;)V"); global::android.database.sqlite.SQLiteProgram._native_finalize2902 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_finalize", "()V"); global::android.database.sqlite.SQLiteProgram._native_bind_null2903 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_bind_null", "(I)V"); global::android.database.sqlite.SQLiteProgram._native_bind_long2904 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_bind_long", "(IJ)V"); global::android.database.sqlite.SQLiteProgram._native_bind_double2905 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_bind_double", "(ID)V"); global::android.database.sqlite.SQLiteProgram._native_bind_string2906 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_bind_string", "(ILjava/lang/String;)V"); global::android.database.sqlite.SQLiteProgram._native_bind_blob2907 = @__env.GetMethodIDNoThrow(global::android.database.sqlite.SQLiteProgram.staticClass, "native_bind_blob", "(I[B)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.database.sqlite.SQLiteProgram))] public sealed partial class SQLiteProgram_ : android.database.sqlite.SQLiteProgram { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SQLiteProgram_() { InitJNI(); } internal SQLiteProgram_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.sqlite.SQLiteProgram_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/sqlite/SQLiteProgram")); } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Requests; using Cassandra.Serialization; namespace Cassandra { /// <summary> /// A simple <see cref="IStatement"/> implementation built directly from a query string. /// </summary> public class SimpleStatement : RegularStatement { private static readonly Logger Logger = new Logger(typeof(SimpleStatement)); private string _query; private volatile RoutingKey _routingKey; private object[] _routingValues; /// <summary> /// Gets the query string. /// </summary> public override string QueryString { get { return _query; } } /// <summary> /// Gets the routing key for the query. /// <para> /// Routing key can be provided using the <see cref="SetRoutingValues"/> method. /// </para> /// </summary> public override RoutingKey RoutingKey { get { if (_routingKey != null) { return _routingKey; } if (_routingValues == null) { return null; } var serializer = Serializer; if (serializer == null) { serializer = Serializer.Default; Logger.Warning("Calculating routing key before executing is not supporting for SimpleStatements, " + "using default serializer."); } //Calculate the routing key return RoutingKey.Compose( _routingValues .Select(value => new RoutingKey(serializer.Serialize(value))) .ToArray()); } } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> without any query string or parameters. /// </summary> public SimpleStatement() { } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query. /// </summary> /// <param name="query">The cql query string.</param> public SimpleStatement(string query) { _query = query; } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> with the provided CQL query and values provided. /// </summary> /// <param name="query">The cql query string.</param> /// <param name="values">Parameter values required for the execution of <c>query</c>.</param> /// <example> /// Using positional parameters: /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (?, ?, ?)"; /// var statement = new SimpleStatement(query, id, name, email); /// </code> /// Using named parameters (using anonymous objects): /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)"; /// var statement = new SimpleStatement(query, new { id, name, email } ); /// </code> /// </example> public SimpleStatement(string query, params object[] values) : this(query) { // ReSharper disable once DoNotCallOverridableMethodsInConstructor SetValues(values); } /// <summary> /// Creates a new instance of <see cref="SimpleStatement"/> using a dictionary of parameters and a query with /// named parameters. /// </summary> /// <param name="valuesDictionary"> /// A dictionary containing the query parameters values using the parameter name as keys. /// </param> /// <param name="query">The cql query string.</param> /// <remarks> /// This constructor is valid for dynamically-sized named parameters, consider using anonymous types for /// fixed-size named parameters. /// </remarks> /// <example> /// <code> /// const string query = "INSERT INTO users (id, name, email) VALUES (:id, :name, :email)"; /// var parameters = new Dictionary&lt;string, object&gt; /// { /// { "id", id }, /// { "name", name }, /// { "email", email }, /// }; /// var statement = new SimpleStatement(parameters, query); /// </code> /// </example> /// <seealso cref="SimpleStatement(string, object[])"/> public SimpleStatement(IDictionary<string, object> valuesDictionary, string query) { if (valuesDictionary == null) { throw new ArgumentNullException("valuesDictionary"); } if (query == null) { throw new ArgumentNullException("query"); } //The order of the keys and values is unspecified, but is guaranteed to be both in the same order. SetParameterNames(valuesDictionary.Keys); base.SetValues(valuesDictionary.Values.ToArray()); _query = query; } /// <summary> /// Set the routing key for this query. <p> This method allows to manually /// provide a routing key for this query. It is thus optional since the routing /// key is only an hint for token aware load balancing policy but is never /// mandatory. </p><p> If the partition key for the query is composite, use the /// <link>#setRoutingKey(ByteBuffer...)</link> method instead to build the /// routing key.</p> /// </summary> /// <param name="routingKeyComponents"> the raw (binary) values to compose to /// obtain the routing key. /// </param> /// <returns>this <c>SimpleStatement</c> object. <see>Query#getRoutingKey</see></returns> public SimpleStatement SetRoutingKey(params RoutingKey[] routingKeyComponents) { _routingKey = RoutingKey.Compose(routingKeyComponents); return this; } /// <summary> /// Sets the partition key values in order to route the query to the correct replicas. /// <para>For simple partition keys, set the partition key value.</para> /// <para>For composite partition keys, set the multiple the partition key values in correct order.</para> /// </summary> public SimpleStatement SetRoutingValues(params object[] keys) { _routingValues = keys; return this; } public SimpleStatement SetQueryString(string queryString) { _query = queryString; return this; } /// <summary> /// Sets the parameter values for the query. /// <para> /// The same amount of values must be provided as parameter markers in the query. /// </para> /// <para> /// Specify the parameter values by the position of the markers in the query or by name, /// using a single instance of an anonymous type, with property names as parameter names. /// </para> /// </summary> [Obsolete("The method Bind() is deprecated, use SimpleStatement constructor parameters to provide query values")] public SimpleStatement Bind(params object[] values) { SetValues(values); return this; } [Obsolete("The method BindObject() is deprecated, use SimpleStatement constructor parameters to provide query values")] public SimpleStatement BindObjects(object[] values) { return Bind(values); } internal override IQueryRequest CreateBatchRequest(int protocolVersion) { //Uses the default query options as the individual options of the query will be ignored var options = QueryProtocolOptions.CreateFromQuery(this, new QueryOptions()); return new QueryRequest(protocolVersion, QueryString, IsTracing, options); } internal override void SetValues(object[] values) { if (values != null && values.Length == 1 && Utils.IsAnonymousType(values[0])) { var keyValues = Utils.GetValues(values[0]); SetParameterNames(keyValues.Keys); values = keyValues.Values.ToArray(); } base.SetValues(values); } private void SetParameterNames(IEnumerable<string> names) { //Force named values to lowercase as identifiers are lowercased in Cassandra QueryValueNames = names.Select(k => k.ToLowerInvariant()).ToList(); } } }
using System; using System.Collections.Generic; using System.Text; using gView.Framework.Data; using System.IO; using gView.Framework.system; using System.Xml; using gView.Framework.Geometry; using gView.Framework.OGC.GML; using gView.Framework.IO; namespace gView.Framework.OGC.WFS { [gView.Framework.system.RegisterPlugIn("DBD759E3-4776-43c0-A31A-0481C5480A67")] public class Filter : IPersistable { private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; private List<FilterObject> _filterObjects; private GmlVersion _gmlVersion = GmlVersion.v1; public Filter() : this(GmlVersion.v1) { } public Filter(GmlVersion gmlVersion) { _filterObjects = new List<FilterObject>(); _gmlVersion = gmlVersion; } public Filter(string ogcFilter, GmlVersion version) : this(version) { GenerateFromString(ogcFilter, null); } public Filter(IFeatureClass fc, IQueryFilter filter, GmlVersion version) : this(fc, filter, null, version) { } public Filter(IFeatureClass fc, IQueryFilter filter, Filter_Capabilities filter_cabs, GmlVersion version) : this(version) { if (filter_cabs == null) // Default erstellen filter_cabs = new Filter_Capabilities(); string ogcFilter = Filter.ToWFS(fc, filter, filter_cabs, version); GenerateFromString(ogcFilter, fc); } private void GenerateFromString(string ogcFilter, IFeatureClass fc) { ogcFilter = ogcFilter.Replace("<ogc:", "<").Replace("</ogc:", "</").Replace("<gml:", "<").Replace("</gml:", "</"); _filterObjects.Clear(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(ogcFilter); XmlNode filterNode = doc.SelectSingleNode("Filter"); if (filterNode == null) return; foreach (XmlNode childNode in filterNode.ChildNodes) { switch (childNode.Name) { case "And": AndOperator newAnd = new AndOperator(); newAnd.BuildFromNode(childNode); _filterObjects.Add(newAnd); break; case "Or": OrOperator newOr = new OrOperator(); newOr.BuildFromNode(childNode); _filterObjects.Add(newOr); break; case "PropertyIsEqualTo": case "PropertyIsNotEqualTo": case "PropertyIsLessThan": case "PropertyIsGreaterThan": case "PropertyIsLessThanEqualTo": case "PropertyIsGreaterThanEqualTo": case "PropertyIsLessThanOrEqualTo": case "PropertyIsGreaterThanOrEqualTo": case "PropertyIsLike": case "PropertyIsBetween": case "PropertyIsNullCheck": ComparisonOperator newComp = new ComparisonOperator(); newComp.BuildFromNode(childNode); _filterObjects.Add(newComp); break; case "Intersects": case "Intersect": case "Contains": case "Within": case "BBOX": SpatialComparisonOperator newSpComp = new SpatialComparisonOperator(); newSpComp.BuildFromNode(childNode); if (fc != null) { newSpComp.PropertyName = fc.ShapeFieldName; } _filterObjects.Add(newSpComp); break; } } } catch { } } public string ToXmlString() { return this.ToXmlString(false); } public string ToXmlString(bool useNamespace) { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); if (useNamespace) sw.WriteLine("<Filter xmlns=\"http://www.opengis.net/ogc\" >"); else sw.WriteLine("<Filter>"); foreach (FilterObject fObject in _filterObjects) { fObject.WriteTo(sw, _gmlVersion); } sw.WriteLine("</Filter>"); sw.Flush(); ms.Position = 0; byte[] bytes = new byte[ms.Length]; ms.Read(bytes, 0, (int)ms.Length); sw.Close(); string ret = Encoding.UTF8.GetString(bytes).Trim(); return ret; } public string[] PropertyNames { get { List<string> names = new List<string>(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(this.ToXmlString()); foreach (XmlNode pNode in doc.SelectNodes("//PropertyName")) { if (names.Contains(pNode.InnerText)) continue; names.Add(pNode.InnerText); } } catch { } return names.ToArray(); } } public string WhereClause { get { try { XmlDocument doc = new XmlDocument(); doc.LoadXml(this.ToXmlString(true)); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("OGC", "http://www.opengis.net/ogc"); IQueryFilter queryFilter = gView.Framework.OGC.WFS.Filter.FromWFS(doc.SelectSingleNode("OGC:Filter", ns), _gmlVersion); return queryFilter.WhereClause; } catch { return String.Empty; } } } public bool Check(IFeature feature, ISpatialReference featureSRef) { // // Im obersten Knoten wird immer mit AND getestet!!! // (es sollte ja sowieso nur ein an oberster stelle stehen) foreach (FilterObject fObject in _filterObjects) { if (!fObject.Check(feature, featureSRef)) return false; } return true; } public void SetDefaultSrsName(string srsName) { foreach (FilterObject filterObject in _filterObjects) { SetDefaultSrsName(filterObject, srsName); } } private void SetDefaultSrsName(FilterObject filterObject, string srsName) { if (filterObject == null) return; if (filterObject is SpatialComparisonOperator && String.IsNullOrEmpty(((SpatialComparisonOperator)filterObject).srsName)) { ((SpatialComparisonOperator)filterObject).srsName = srsName; } if (filterObject is LogicalOperator) { foreach (FilterObject child in ((LogicalOperator)filterObject).FilterObjects) { SetDefaultSrsName(child, srsName); } } } #region SubClasses private abstract class FilterObject { abstract public void WriteTo(StreamWriter sw, GmlVersion version); abstract public void BuildFromNode(XmlNode node); abstract public bool Check(IFeature feature, ISpatialReference featureSRef); } private abstract class LogicalOperator : FilterObject { private List<FilterObject> _filterObjects = new List<FilterObject>(); public LogicalOperator() { } public List<FilterObject> FilterObjects { get { return _filterObjects; } } public override void BuildFromNode(XmlNode node) { foreach (XmlNode childNode in node.ChildNodes) { switch (childNode.Name) { case "And": AndOperator newAnd = new AndOperator(); newAnd.BuildFromNode(childNode); _filterObjects.Add(newAnd); break; case "Or": OrOperator newOr = new OrOperator(); newOr.BuildFromNode(childNode); _filterObjects.Add(newOr); break; case "PropertyIsEqualTo": case "PropertyIsNotEqualTo": case "PropertyIsLessThan": case "PropertyIsGreaterThan": case "PropertyIsLessThanEqualTo": case "PropertyIsGreaterThanEqualTo": case "PropertyIsLessThanOrEqualTo": case "PropertyIsGreaterThanOrEqualTo": case "PropertyIsLike": case "PropertyIsBetween": case "PropertyIsNullCheck": ComparisonOperator newComp = new ComparisonOperator(); newComp.BuildFromNode(childNode); _filterObjects.Add(newComp); break; } } } } private class AndOperator : LogicalOperator { public override void WriteTo(StreamWriter sw, GmlVersion version) { sw.WriteLine("<And>"); foreach (FilterObject fObject in this.FilterObjects) fObject.WriteTo(sw, version); sw.WriteLine("</And>"); } public override bool Check(IFeature feature, ISpatialReference featureSRef) { foreach (FilterObject fObject in this.FilterObjects) { if (!fObject.Check(feature, featureSRef)) return false; } return true; } } private class OrOperator : LogicalOperator { public override void WriteTo(StreamWriter sw, GmlVersion version) { sw.WriteLine("<Or>"); foreach (FilterObject fObject in this.FilterObjects) fObject.WriteTo(sw, version); sw.WriteLine("</Or>"); } public override bool Check(IFeature feature, ISpatialReference featureSRef) { foreach (FilterObject fObject in this.FilterObjects) { if (fObject.Check(feature, featureSRef)) return true; } return false; } } private class ComparisonOperator : FilterObject { public enum CompOperator { EqualTo = 0, NotEqualTo = 1, LessThan = 2, GreaterThan = 3, LessThanOrEqualTo = 4, GreaterThanOrEqualTo = 5, Like = 6, Between = 7, NullCheck = 8 } public String PropertyName = String.Empty; public object Literal = String.Empty; public CompOperator Operator; private WildcardEx _wildcard = null; public ComparisonOperator() { } public ComparisonOperator(CompOperator op, string propertyName, string literal) { Operator = op; PropertyName = propertyName; Literal = literal; if (Operator == CompOperator.Like) { _wildcard = new WildcardEx(Literal.ToString().Replace("%", "*"), System.Text.RegularExpressions.RegexOptions.IgnoreCase); } } private bool NumericCompare(double val) { double lit = Convert.ToDouble(Literal.ToString().Replace(",", "."), _nhi); switch (Operator) { case CompOperator.EqualTo: return val == lit; case CompOperator.NotEqualTo: return val != lit; case CompOperator.GreaterThan: return val > lit; case CompOperator.GreaterThanOrEqualTo: return val >= lit; case CompOperator.LessThan: return val < lit; case CompOperator.LessThanOrEqualTo: return val <= lit; } return false; } private bool StringCompare(string val) { string lit = Literal.ToString(); switch (Operator) { case CompOperator.EqualTo: return lit.Equals(val, StringComparison.OrdinalIgnoreCase); //case CompOperator.GreaterThan: // return lit > val; //case CompOperator.GreaterThanEqualTo: // return lit >=val; //case CompOperator.LessThan: // return lit < val; //case CompOperator.LessThanEqualTo: // return lit<=val; case CompOperator.Like: if (_wildcard != null) { return _wildcard.IsMatch(val); } break; case CompOperator.NotEqualTo: return !lit.Equals(val, StringComparison.OrdinalIgnoreCase); } return false; } private bool DateTimeCompare(DateTime val) { DateTime lit; if (!DateTime.TryParse(Literal.ToString(), out lit)) return false; switch (Operator) { case CompOperator.EqualTo: return lit.Equals(val); case CompOperator.GreaterThan: return val > lit; case CompOperator.GreaterThanOrEqualTo: return val >= lit; case CompOperator.LessThan: return val < lit; case CompOperator.LessThanOrEqualTo: return val <= lit; case CompOperator.NotEqualTo: return !lit.Equals(val); } return false; } private bool Compare(object val) { Type t = val.GetType(); if (t == typeof(double) || t == typeof(float) || t == typeof(decimal) || t == typeof(int) || t == typeof(short) || t == typeof(byte) || t == typeof(long)) { return NumericCompare(Convert.ToDouble(val)); } else if (t == typeof(string)) { return StringCompare(val.ToString()); } else if (t == typeof(DateTime)) { return DateTimeCompare((DateTime)val); } return false; } public override bool Check(IFeature feature, ISpatialReference featureSRef) { if (feature == null) return false; object val = feature[PropertyName]; if (val == null || val == DBNull.Value) { if (Operator == CompOperator.NullCheck) return true; return false; } return Compare(val); } public override void WriteTo(StreamWriter sw, GmlVersion version) { sw.WriteLine("<PropertyIs" + Operator.ToString() + ">"); sw.WriteLine("<PropertyName>" + PropertyName + "</PropertyName>"); sw.WriteLine("<Literal>" + Literal + "</Literal>"); sw.WriteLine("</PropertyIs" + Operator.ToString() + ">"); } public override void BuildFromNode(XmlNode node) { XmlNode nodePropertyName = node.SelectSingleNode("PropertyName"); XmlNode nodeLiteral = node.SelectSingleNode("Literal"); if (nodePropertyName != null) PropertyName = nodePropertyName.InnerText; if (nodeLiteral != null) Literal = nodeLiteral.InnerText; switch (node.Name) { case "PropertyIsEqualTo": Operator = CompOperator.EqualTo; break; case "PropertyIsNotEqualTo": Operator = CompOperator.NotEqualTo; break; case "PropertyIsLessThan": Operator = CompOperator.LessThan; break; case "PropertyIsGreaterThan": Operator = CompOperator.GreaterThan; break; case "PropertyIsLessThanEqualTo": case "PropertyIsLessThanOrEqualTo": Operator = CompOperator.LessThanOrEqualTo; break; case "PropertyIsGreaterThanEqualTo": case "PropertyIsGreaterThanOrEqualTo": Operator = CompOperator.GreaterThanOrEqualTo; break; case "PropertyIsLike": Operator = CompOperator.Like; _wildcard = new WildcardEx(Literal.ToString().Replace("%", "*"), System.Text.RegularExpressions.RegexOptions.IgnoreCase); break; case "PropertyIsBetween": Operator = CompOperator.Between; break; case "PropertyIsNullCheck": Operator = CompOperator.NullCheck; break; } } } private class SpatialComparisonOperator : FilterObject { public enum SpatialCompOperator { BBOX = 0, Intersect = 1, Intersects = 2, Within = 3, Contains = 4 } private SpatialFilter sFilter = null; private SpatialCompOperator Operator = SpatialCompOperator.BBOX; public string PropertyName = String.Empty; private GmlVersion _gmlVersion; //public string srsName = String.Empty; public SpatialComparisonOperator() { } public SpatialComparisonOperator(SpatialCompOperator op, IGeometry geometry, GmlVersion gmlVersion) { sFilter = new SpatialFilter(); sFilter.Geometry = geometry; _gmlVersion = gmlVersion; Operator = op; switch (op) { case SpatialCompOperator.BBOX: sFilter.SpatialRelation = spatialRelation.SpatialRelationEnvelopeIntersects; break; case SpatialCompOperator.Intersect: case SpatialCompOperator.Intersects: sFilter.SpatialRelation = spatialRelation.SpatialRelationIntersects; break; case SpatialCompOperator.Contains: sFilter.SpatialRelation = spatialRelation.SpatialRelationContains; break; case SpatialCompOperator.Within: sFilter.SpatialRelation = spatialRelation.SpatialRelationWithin; break; } } public string srsName { get { if (sFilter != null && sFilter.FilterSpatialReference != null) return sFilter.FilterSpatialReference.Name; return String.Empty; } set { if (sFilter != null) sFilter.FilterSpatialReference = SpatialReference.FromID(value); } } public override bool Check(IFeature feature, ISpatialReference featureSRef) { if (feature == null || feature.Shape == null || sFilter == null || sFilter.Geometry == null) return false; IGeometry pGeometry = GeometricTransformer.Transform2D( sFilter.Geometry, sFilter.FilterSpatialReference, featureSRef); SpatialFilter filter = new SpatialFilter(); filter.Geometry = pGeometry; filter.SpatialRelation = sFilter.SpatialRelation; return SpatialRelation.Check(filter, feature.Shape); } public override void WriteTo(StreamWriter sw, GmlVersion version) { if (sFilter == null) return; //Operator = SpatialCompOperator.BBOX; sw.WriteLine("<" + Operator.ToString() + ">"); sw.WriteLine("<PropertyName>" + PropertyName + "</PropertyName>"); sw.WriteLine(gView.Framework.OGC.GML.GeometryTranslator.Geometry2GML( sFilter.Geometry, srsName, version ).Replace("<gml:", "<").Replace("</gml:", "</") ); sw.WriteLine("</" + Operator.ToString() + ">"); } public override void BuildFromNode(XmlNode node) { if (node == null) return; switch (node.Name.ToLower()) { case "bbox": Operator = SpatialCompOperator.BBOX; break; case "intersect": Operator = SpatialCompOperator.Intersect; break; case "intersects": Operator = SpatialCompOperator.Intersects; break; case "contains": Operator = SpatialCompOperator.Contains; break; case "widthin": Operator = SpatialCompOperator.Within; break; } sFilter = new SpatialFilter(); switch (Operator) { case SpatialCompOperator.BBOX: sFilter.SpatialRelation = spatialRelation.SpatialRelationEnvelopeIntersects; break; case SpatialCompOperator.Intersect: case SpatialCompOperator.Intersects: sFilter.SpatialRelation = spatialRelation.SpatialRelationIntersects; break; case SpatialCompOperator.Contains: sFilter.SpatialRelation = spatialRelation.SpatialRelationContains; break; case SpatialCompOperator.Within: sFilter.SpatialRelation = spatialRelation.SpatialRelationWithin; break; } foreach (XmlNode child in node.ChildNodes) { if (child.Name == "PropertyName") { PropertyName = child.InnerText; continue; } sFilter.Geometry = gView.Framework.OGC.GML.GeometryTranslator.GML2Geometry(child.OuterXml, _gmlVersion); if (sFilter.Geometry != null) { if (child.Attributes["srsName"] != null) srsName = child.Attributes["srsName"].Value; break; } } } } #endregion #region IPersistable Member public void Load(IPersistStream stream) { string ogcFilter = (string)stream.Load("OGCFilter", String.Empty); GenerateFromString(ogcFilter, null); } public void Save(IPersistStream stream) { stream.Save("OGCFilter", this.ToXmlString()); } #endregion #region Static Members static public string ToWFS(IFeatureClass fc, IQueryFilter filter, Filter_Capabilities filterCaps, GmlVersion version) { if (filterCaps == null) return String.Empty; if (filter is IBufferQueryFilter) { filter = BufferQueryFilter.ConvertToSpatialFilter((IBufferQueryFilter)filter); } MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms, Encoding.UTF8); sw.WriteLine("<ogc:Filter>"); if (filter is ISpatialFilter && ((ISpatialFilter)filter).Geometry != null) { ISpatialFilter sFilter = filter as ISpatialFilter; string srsName = (sFilter.FilterSpatialReference != null) ? sFilter.FilterSpatialReference.Name : ""; if (sFilter.WhereClause != String.Empty) sw.WriteLine("<ogc:And>"); string op = filterCaps.SpatialOperator(sFilter.SpatialRelation); sw.WriteLine(" <ogc:" + op + ">"); sw.WriteLine(" <ogc:PropertyName>" + fc.ShapeFieldName + "</ogc:PropertyName>"); switch (sFilter.SpatialRelation) { case spatialRelation.SpatialRelationMapEnvelopeIntersects: case spatialRelation.SpatialRelationEnvelopeIntersects: sw.WriteLine(GML.GeometryTranslator.Geometry2GML(sFilter.Geometry.Envelope, srsName, version)); break; case spatialRelation.SpatialRelationWithin: case spatialRelation.SpatialRelationIntersects: case spatialRelation.SpatialRelationContains: sw.WriteLine(GML.GeometryTranslator.Geometry2GML( filterCaps.SupportsSpatialOperator(sFilter.SpatialRelation) ? sFilter.Geometry : sFilter.Geometry.Envelope, srsName, version)); break; } sw.WriteLine(" </ogc:" + op + ">"); if (sFilter.WhereClause != String.Empty) { if (filter.WhereClause.ToLower().Contains(" in (")) ParseInWhereClause(filter.WhereClause, sw); else { ParseWhereClause(filter.WhereClause, sw); } sw.WriteLine("</ogc:And>"); } } else if (filter is IRowIDFilter) { if (fc.IDFieldName == String.Empty) { CreateRowIDFilter(fc, filter as IRowIDFilter, sw); } else { ParseInWhereClause(((IRowIDFilter)filter).RowIDWhereClause, sw); } } else if (filter is IQueryFilter) { if (filter.WhereClause.ToLower().Contains(" in (")) ParseInWhereClause(filter.WhereClause, sw); else { ParseWhereClause(filter.WhereClause, sw); } } sw.WriteLine("</ogc:Filter>"); sw.Flush(); ms.Position = 0; byte[] bytes = new byte[ms.Length]; ms.Read(bytes, 0, (int)ms.Length); sw.Close(); string ret = Encoding.UTF8.GetString(bytes).Trim(); // ret = @"<ogc:Filter> // <ogc:PropertyIsLike wildCard=""%"" singleChar=""?"" escape=""ESC""> // <ogc:PropertyName> // item_plz // </ogc:PropertyName> // <ogc:Literal> // 53111 // </ogc:Literal> // </ogc:PropertyIsLike> //</ogc:Filter>"; return ret; } static public IQueryFilter FromWFS(XmlNode filter, GmlVersion gmlVersion) { return FromWFS(null, filter, gmlVersion); } static public IQueryFilter FromWFS(IFeatureClass fc, XmlNode filter, GmlVersion gmlVersion/*, string nsName*/) { if (filter == null) { QueryFilter empty = new QueryFilter(); return empty; } XmlNamespaceManager ns = null; if (filter.NamespaceURI != String.Empty) { ns = new XmlNamespaceManager(filter.OwnerDocument.NameTable); ns.AddNamespace("OGC", filter.NamespaceURI); ns.AddNamespace("GML", "http://www.opengis.net/gml"); } StringBuilder whereClause = new StringBuilder(); IQueryFilter newFilter = null; ParseWFSFilter(fc, filter, "", ns, whereClause, ref newFilter, gmlVersion); if (newFilter == null) newFilter = new QueryFilter(); newFilter.WhereClause = RemoveOuterBrackets(whereClause.ToString()); return newFilter; } static public void AppendSortBy(IQueryFilter filter, XmlNode SortBy) { if (filter == null || SortBy == null) return; XmlNamespaceManager ns = null; if (SortBy.NamespaceURI != String.Empty) { ns = new XmlNamespaceManager(SortBy.OwnerDocument.NameTable); ns.AddNamespace("OGC", SortBy.NamespaceURI); } XmlNode sortProperty = SortBy.SelectSingleNode("SortProperty", ns); if (sortProperty == null) sortProperty = SortBy.SelectSingleNode("OGC:SortProperty", ns); if (sortProperty == null) return; string prop = String.Empty, order = String.Empty; foreach (XmlNode child in sortProperty.ChildNodes) { switch (child.Name) { case "ogc:PropertyName": case "OGC:PropertyName": case "PropertyName": prop = child.InnerText; break; case "ogc:SortOrder": case "OGC:SortOrder": case "SortOrder": order = child.InnerText; break; } } if (!String.IsNullOrEmpty(prop)) { filter.OrderBy = prop; if (!String.IsNullOrEmpty(order)) filter.OrderBy += " " + order; } } #region Helper #region ToWFS private static void CreateRowIDFilter(IFeatureClass fc, IRowIDFilter filter, StreamWriter sw) { if (fc == null || filter == null || sw == null) return; string fcName = XML.Globals.TypeWithoutPrefix(fc.Name); foreach (int id in filter.IDs) { //sw.WriteLine("<ogc:GmlObjectId gml:id=\"" + fcName + "." + id.ToString() + "\" />"); sw.WriteLine("<ogc:FeatureId fid=\"" + fcName + "." + id.ToString() + "\" />"); } } private static void ParseWhereClause(string whereClause, StreamWriter sw) { Tokenizer tokenizer = new Tokenizer(whereClause); tokenizer.OnTransformToken += new Tokenizer.TransformTokenEventHandler(tokenizer_OnTransformToken); sw.Write(tokenizer.TransformXML()); } static void tokenizer_OnTransformToken(ref string text) { if (text == String.Empty) return; if (text.LastIndexOf("[") == 0 && text.IndexOf("]") == text.Length - 1) return; text = ParseFlatWhereClause(text); } private static string ParseFlatWhereClause(string whereClause) { StringBuilder sb = new StringBuilder(); if (whereClause == String.Empty) return String.Empty; if (whereClause.Contains("(") || whereClause.Contains(")")) { throw (new Exception("Whereclause to complex: don't use brackets")); } //Tokenizer tokenizer = new Tokenizer(whereClause); //Token rootToken = tokenizer.Token; bool useAND = false, useOR = false, useNOT = false; useAND = containsLogicalOperator(whereClause, "and"); useOR = containsLogicalOperator(whereClause, "or"); useNOT = containsLogicalOperator(whereClause, "not"); if (useAND == true && useOR == true || useAND == true && useNOT == true || useOR == true && useNOT == true) { throw (new Exception("Whereclause to complex: Only use one kind of logical operations (and, or, not)")); } string op = String.Empty; if (useAND) op = "And"; if (useOR) op = "Or"; if (useNOT) op = "Not"; string[] properties = SplitByString(whereClause, " " + op + " "); if (op != String.Empty) sb.Append("<ogc:" + op + ">"); foreach (string property in properties) { if (property == String.Empty) continue; if (property[0] == '[' && property[property.Length - 1] == ']') { sb.Append(property); continue; } string[] parts = SplitPropertyClause(property); string operatorName = ""; switch (parts[1].ToLower()) { case "like": operatorName = "ogc:PropertyIsLike"; sb.Append(@"<ogc:PropertyIsLike wildCard=""%"" singleChar=""?"" escape=""ESC"">"); break; case "=": operatorName = "ogc:PropertyIsEqualTo"; sb.Append(@"<ogc:PropertyIsEqualTo>"); //operatorName = "ogc:PropertyIsLike"; //sb.Append(@"<ogc:PropertyIsLike wildCard=""%"" singleChar=""?"" escape=""ESC"">"); break; case ">": operatorName = "ogc:PropertyIsGreaterThan"; sb.Append(@"<ogc:PropertyIsGreaterThan>"); break; case ">=": operatorName = "ogc:PropertyIsGreaterThanOrEqualTo"; sb.Append(@"<ogc:PropertyIsGreaterThanOrEqualTo>"); break; case "<": operatorName = "ogc:PropertyIsLessThan"; sb.Append(@"<ogc:PropertyIsLessThan>"); break; case "<=": operatorName = "ogc:PropertyIsLessThanOrEqualTo"; sb.Append(@"<ogc:PropertyIsLessThanOrEqualTo>"); break; case "<>": operatorName = "ogc:PropertyIsNotEqualTo"; sb.Append(@"<ogc:PropertyIsNotEqualTo>"); break; } sb.Append("<ogc:PropertyName>" + parts[0] + "</ogc:PropertyName>"); sb.Append("<ogc:Literal>" + parts[2].Replace("\"", "").Replace("'", "") + "</ogc:Literal>"); sb.Append(@"</" + operatorName + ">"); } if (op != String.Empty) sb.Append("</ogc:" + op + ">"); return sb.ToString(); } private static void ParseInWhereClause(string whereClause, StreamWriter sw) { while (whereClause.IndexOf(" ,") != -1) whereClause = whereClause.Replace(" ,", ","); while (whereClause.IndexOf(", ") != -1) whereClause = whereClause.Replace(", ", ","); string[] parts = whereClause.Trim().Split(' '); if (parts.Length != 3) throw (new Exception("Whereclause to complex...")); string field = parts[0]; string[] ids = parts[2].Substring(1, parts[2].Length - 2).Split(','); StringBuilder sb = new StringBuilder(); foreach (string id in ids) { if (sb.Length > 0) sb.Append(" OR "); sb.Append(field + "=" + id); } ParseWhereClause(sb.ToString(), sw); } private static bool containsLogicalOperator(string clause, string op) { clause = TrimClause(clause).ToLower(); op = op.ToLower(); string[] parts = clause.Split(' '); foreach (string part in parts) { if (part == op) return true; } return false; } private static string TrimClause(string clause) { clause = clause.Trim(); while (clause.IndexOf(" ") != -1) clause = clause.Replace(" ", " "); return clause; } private static string[] SplitByString(string testString, string split) { if (split == string.Empty) { string[] ret = new string[1]; ret[0] = testString; return ret; } split = split.ToLower(); string testStringL = testString.ToLower(); int offset = 0; int index = 0; int[] offsets = new int[testString.Length + 1]; while (index < testStringL.Length) { int indexOf = testStringL.IndexOf(split, index); if (indexOf != -1) { offsets[offset++] = indexOf; index = (indexOf + split.Length); } else { index = testStringL.Length; } } string[] final = new string[offset + 1]; if (offset == 0) { final[0] = testString; } else { offset--; final[0] = testString.Substring(0, offsets[0]); for (int i = 0; i < offset; i++) { final[i + 1] = testString.Substring(offsets[i] + split.Length, offsets[i + 1] - offsets[i] - split.Length); } final[offset + 1] = testString.Substring(offsets[offset] + split.Length); } return final; } private static string[] SplitPropertyClause(string clause) { clause = clause.Trim(); string clause2 = clause.ToLower(); if (clause2.Contains(">=")) { return SplitPropertyClause(clause, ">="); } else if (clause2.Contains("<=")) { return SplitPropertyClause(clause, "<="); } else if (clause2.Contains("<>")) { return SplitPropertyClause(clause, "<>"); } else if (clause2.Contains(">")) { return SplitPropertyClause(clause, ">"); } else if (clause2.Contains("<")) { return SplitPropertyClause(clause, "<"); } else if (clause2.Contains("=")) { return SplitPropertyClause(clause, "="); } else if (clause2.ToLower().Contains(" like ")) { return SplitPropertyClause(clause, " like "); } else { throw new Exception("Parser Error: Unkonwn operator in clause " + clause); } } private static string[] SplitPropertyClause(string clause, string op) { int pos = clause.ToLower().IndexOf(op.ToLower()); if (pos == 0) { throw new Exception("Parse Error: " + clause + " do not contain " + op); } string[] parts = new string[3]; parts[0] = (clause.Substring(0, pos)).Trim(); parts[1] = op.Trim(); parts[2] = (clause.Substring(pos + op.Length, clause.Length - pos - op.Length)).Trim(); return parts; } #endregion #region FromWFS private static void ParseWFSFilter(IFeatureClass fc, XmlNode parentNode, string LogicalOperator, XmlNamespaceManager ns, StringBuilder sb, ref IQueryFilter newFilter, GmlVersion gmlVersion) { if (parentNode == null) return; foreach (XmlNode child in parentNode.ChildNodes) { XmlNode gmlNode = null; switch (child.Name) { case "ogc:And": case "And": StringBuilder sb1 = new StringBuilder(); ParseWFSFilter(fc, child, "AND", ns, sb1, ref newFilter, gmlVersion); AppendClause(LogicalOperator, "(" + sb1.ToString() + ")", sb); //sb.Append("(" + sb1.ToString() + ")"); break; case "ogc:Or": case "Or": StringBuilder sb2 = new StringBuilder(); ParseWFSFilter(fc, child, "OR", ns, sb2, ref newFilter, gmlVersion); AppendClause(LogicalOperator, "(" + sb2.ToString() + ")", sb); //sb.Append("(" + sb2.ToString() + ")"); break; case "ogc:Not": case "Not": StringBuilder sb3 = new StringBuilder(); ParseWFSFilter(fc, child, "NOT", ns, sb3, ref newFilter, gmlVersion); AppendClause(LogicalOperator, "(" + sb3.ToString() + ")", sb); //sb.Append("(" + sb3.ToString() + ")"); break; case "ogc:BBOX": case "BBOX": if (newFilter != null) throw new Exception("Invalid or corrupt Filter!!!"); newFilter = new SpatialFilter(); ((ISpatialFilter)newFilter).SpatialRelation = spatialRelation.SpatialRelationEnvelopeIntersects; gmlNode = (ns != null) ? child.SelectSingleNode("GML:*", ns) : child.ChildNodes[0]; break; case "ogc:Intersects": case "Intersects": if (newFilter != null) throw new Exception("Invalid or corrupt Filter!!!"); newFilter = new SpatialFilter(); ((ISpatialFilter)newFilter).SpatialRelation = spatialRelation.SpatialRelationIntersects; gmlNode = (ns != null) ? child.SelectSingleNode("GML:*", ns) : child.ChildNodes[0]; break; case "ogc:Within": case "Within": if (newFilter != null) throw new Exception("Invalid or corrupt Filter!!!"); newFilter = new SpatialFilter(); ((ISpatialFilter)newFilter).SpatialRelation = spatialRelation.SpatialRelationContains; gmlNode = (ns != null) ? child.SelectSingleNode("GML:*", ns) : child.ChildNodes[0]; break; case "ogc:Contains": case "Contains": if (newFilter != null) throw new Exception("Invalid or corrupt Filter!!!"); newFilter = new SpatialFilter(); ((ISpatialFilter)newFilter).SpatialRelation = spatialRelation.SpatialRelationContains; gmlNode = (ns != null) ? child.SelectSingleNode("GML:*", ns) : child.ChildNodes[0]; break; default: string clause = ParseWFSFilterNode(fc, child, ns); AppendClause(LogicalOperator, clause, sb); break; } if (gmlNode != null && newFilter is ISpatialFilter) { ((ISpatialFilter)newFilter).Geometry = GeometryTranslator.GML2Geometry(gmlNode.OuterXml, gmlVersion); if (((ISpatialFilter)newFilter).Geometry == null) throw new Exception("Unknown GML Geometry..."); if (gmlNode.Attributes["srsName"] != null) ((ISpatialFilter)newFilter).FilterSpatialReference = SpatialReference.FromID(gmlNode.Attributes["srsName"].Value); } } } private static string ParseWFSFilterNode(IFeatureClass fc, XmlNode node, XmlNamespaceManager ns) { //if(fc==null) // throw new ArgumentException("ParseWFSFilterNode: FeatureClass is null..."); if (node == null) return String.Empty; string op = String.Empty; switch (node.Name) { case "PropertyIsEqualTo": case "ogc:PropertyIsEqualTo": op = "="; break; case "PropertyIsLike": case "ogc:PropertyIsLike": op = " like "; break; case "PropertyIsGreaterThan": case "ogc:PropertyIsGreaterThan": op = ">"; break; case "PropertyIsGreaterThanOrEqualTo": case "ogc:PropertyIsGreaterThanOrEqualTo": op = ">="; break; case "PropertyIsLessThan": case "ogc:PropertyIsLessThan": op = "<"; break; case "PropertyIsLessThanOrEqualTo": case "ogc:PropertyIsLessThanOrEqualTo": op = "<="; break; case "PropertyIsNotEqualTo": case "ogc:PropertyIsNotEqualTo": op = "<>"; break; default: throw new Exception("Unknown operation: " + node.Name + ". Xml is case sensitive."); } XmlNodeList propertyName = (ns != null) ? node.SelectNodes("OGC:PropertyName", ns) : node.SelectNodes("PropertyName"); if (propertyName.Count > 1) { throw new Exception("More than one PropertyName in Property: " + node.OuterXml); } if (propertyName.Count == 0) { throw new Exception("No PropertyName in Property: " + node.OuterXml); } XmlNodeList Literal = (ns != null) ? node.SelectNodes("OGC:Literal", ns) : node.SelectNodes("Literal"); if (Literal.Count > 1) { throw new Exception("More than one Literal in Property: " + node.OuterXml); } if (Literal.Count == 0) { throw new Exception("No Literal in Property: " + node.OuterXml); } string fieldname = propertyName[0].InnerText; string fieldvalue = Literal[0].InnerText; if (fc != null) { IField field = fc.FindField(fieldname); if (field == null) { throw new Exception("Type " + fc.Name + " do not has field " + fieldname); } switch (field.type) { case FieldType.String: fieldvalue = "'" + fieldvalue + "'"; break; case FieldType.Date: fieldvalue = "'" + fieldvalue + "'"; break; } } return fieldname + op + fieldvalue; } private static void AppendClause(string op, string clause, StringBuilder sb) { if (clause == String.Empty) return; if (sb.Length > 0) sb.Append(" " + op + " "); sb.Append(clause); } private static string RemoveOuterBrackets(string sql) { if (sql == null || sql == String.Empty) return String.Empty; byte[] c = new byte[sql.Length]; int pos = 0; for (int i = 0; i < sql.Length; i++) { if (sql[i] == '(') c[i] = (byte)++pos; if (sql[i] == ')') c[i] = (byte)pos--; } if (c[0] != 1 || c[c.Length - 1] != 1) return sql; if (CountValues(c, 1) == 2) { return RemoveOuterBrackets(sql.Substring(1, sql.Length - 2)); } else { return sql; } } private static int CountValues(byte[] array, byte val) { int counter = 0; for (int i = 0; i < array.Length; i++) if (array[i] == val) counter++; return counter; } #endregion #endregion #endregion } public class Filter_Capabilities { #region Declarations private List<string> GeometryOperands = new List<string>(); private List<string> SpatialOperators = new List<string>(); private List<string> ComparisonOperators = new List<string>(); private List<string> SimpleArithmeticOperators = new List<string>(); private List<string> ArithmeticFunctions = new List<string>(); #endregion public Filter_Capabilities() // Default Constructor { SpatialOperators.Add("BBOX"); SpatialOperators.Add("Contains"); SpatialOperators.Add("Intersects"); SpatialOperators.Add("Within"); } public Filter_Capabilities(XmlNode node, XmlNamespaceManager ns) { if (node == null) return; #region GeometryOperands foreach (XmlNode n in node.SelectNodes("OGC:Spatial_Capabilities/OGC:GeometryOperands/OGC:GeometryOperand", ns)) { GeometryOperands.Add(n.InnerText); } foreach (XmlNode n in node.SelectNodes("OGC:Spatial_Capabilities/OGC:Geometry_Operands", ns)) { foreach (XmlNode c in n.ChildNodes) GeometryOperands.Add(gView.Framework.OGC.XML.Globals.TypeWithoutPrefix(c.Name)); } #endregion #region SpatialOperators foreach (XmlNode n in node.SelectNodes("OGC:Spatial_Capabilities/OGC:SpatialOperators/OGC:SpatialOperator[@name]", ns)) { SpatialOperators.Add(n.Attributes["name"].Value); } foreach (XmlNode n in node.SelectNodes("OGC:Spatial_Capabilities/OGC:Spatial_Operators", ns)) { foreach (XmlNode c in n.ChildNodes) SpatialOperators.Add(gView.Framework.OGC.XML.Globals.TypeWithoutPrefix(c.Name)); } #endregion #region ComparisonOperators foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:ComparisonOperators/OGC:ComparisonOperator", ns)) { ComparisonOperators.Add(n.InnerText); } foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:Comparison_Operators", ns)) { foreach (XmlNode c in n.ChildNodes) ComparisonOperators.Add(gView.Framework.OGC.XML.Globals.TypeWithoutPrefix(c.Name)); } #endregion #region ArithmeticFunctions foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:ArithmeticOperators/OGC:Functions/OGC:FunctionNames/OGC:FunctionName", ns)) { ArithmeticFunctions.Add(n.InnerText); } foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:Arithmetic_Operators/OGC:Functions", ns)) { foreach (XmlNode c in n.ChildNodes) ArithmeticFunctions.Add(gView.Framework.OGC.XML.Globals.TypeWithoutPrefix(c.Name)); } #endregion // keine Ahnung wie so was ausschaut //#region SimpleArithmeticOperators //foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:ArithmeticOperators/OGC:SimpleArithmetic", ns)) //{ // SimpleArithmeticOperators.Add(n.InnerText); //} //foreach (XmlNode n in node.SelectNodes("OGC:Scalar_Capabilities/OGC:Arithmetic_Operators/OGC:SimpleArithmetic", ns)) //{ // SimpleArithmeticOperators.Add(n.InnerText); //} //#endregion } #region Supports... private string Supports(List<string> list, string op) { foreach (string l in list) { if (l.ToLower() == op.ToLower()) return l; } return String.Empty; } public bool SuportsGeometryOperand(string op) { return Supports(GeometryOperands, op) != String.Empty; } public bool SupportsSpatialOperator(string op) { return Supports(SpatialOperators, op) != String.Empty; } public bool SupportsSpatialOperator(spatialRelation relation) { switch (relation) { case spatialRelation.SpatialRelationMapEnvelopeIntersects: return SupportsSpatialOperator("BBOX"); case spatialRelation.SpatialRelationWithin: return SupportsSpatialOperator("Contains"); case spatialRelation.SpatialRelationIntersects: return SupportsSpatialOperator("Intersects"); case spatialRelation.SpatialRelationEnvelopeIntersects: return SupportsSpatialOperator("Intersects"); case spatialRelation.SpatialRelationContains: return SupportsSpatialOperator("Within"); } return false; } public bool SupportsComparisonOperator(string op) { return Supports(ComparisonOperators, op) != String.Empty; } public bool SupportsSimpleArithmeticOperator(string op) { return Supports(SimpleArithmeticOperators, op) != String.Empty; } public bool SupportsArithmeticFunction(string op) { return Supports(ArithmeticFunctions, op) != String.Empty; } #endregion public string SpatialOperator(spatialRelation relation) { bool bbox = SupportsSpatialOperator("BBOX"); if (!SupportsSpatialOperator(relation)) { if (SupportsSpatialOperator("BBOX")) return "BBOX"; return String.Empty; } switch (relation) { case spatialRelation.SpatialRelationMapEnvelopeIntersects: return "BBOX"; case spatialRelation.SpatialRelationWithin: return "Contains"; case spatialRelation.SpatialRelationIntersects: return "Intersects"; case spatialRelation.SpatialRelationEnvelopeIntersects: return "Intersects"; case spatialRelation.SpatialRelationContains: return "Within"; } return String.Empty; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using GitVersion; using GitVersionCore.Tests; using Microsoft.Build.Framework; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; using NSubstitute; using NUnit.Framework; using Shouldly; [TestFixture] public class AssemblyInfoBuilderTests { public interface ICompiler { Compilation Compile(string assemblyInfoText); AssemblyInfoBuilder Builder { get; } string ApprovedSubFolder { get; } } private class CSharpCompiler : ICompiler { public Compilation Compile(string assemblyInfoText) { return CSharpCompilation.Create("Fake.dll") .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddSyntaxTrees(CSharpSyntaxTree.ParseText(assemblyInfoText)); } public AssemblyInfoBuilder Builder { get { return new CSharpAssemblyInfoBuilder(); } } public string ApprovedSubFolder { get { return Path.Combine("Approved", "CSharp"); } } } private class VisualBasicCompiler : ICompiler { public Compilation Compile(string assemblyInfoText) { return VisualBasicCompilation.Create("Fake.dll") .WithOptions(new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: "Fake")) .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(assemblyInfoText)); } public AssemblyInfoBuilder Builder { get { return new VisualBasicAssemblyInfoBuilder(); } } public string ApprovedSubFolder { get { return Path.Combine("Approved", "VisualBasic"); } } } private static readonly ICompiler[] compilers = new ICompiler[] { new CSharpCompiler(), new VisualBasicCompiler() }; [Test] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyCreatedCode([ValueSource("compilers")]ICompiler compiler) { var semanticVersion = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData(5, "feature1", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; var config = new TestEffectiveConfiguration(); var versionVariables = VariableProvider.GetVariablesFor(semanticVersion, config, false); var assemblyInfoText = compiler.Builder.GetAssemblyInfoText(versionVariables, "Fake"); assemblyInfoText.ShouldMatchApproved(c => c.SubFolder(compiler.ApprovedSubFolder)); var compilation = compiler.Compile(assemblyInfoText); using (var stream = new MemoryStream()) { var emitResult = compilation.Emit(stream); Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Descriptor))); stream.Seek(0, SeekOrigin.Begin); var assembly = Assembly.Load(stream.ToArray()); VerifyGitVersionInformationAttribute(assembly, versionVariables); } } [Test] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyCreatedCode_NoNamespaceConflict([ValueSource("compilers")]ICompiler compiler) { var semanticVersion = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData(5, "feature1", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; var config = new TestEffectiveConfiguration(); var versionVariables = VariableProvider.GetVariablesFor(semanticVersion, config, false); var assemblyInfoText = compiler.Builder.GetAssemblyInfoText(versionVariables, "Fake.System"); assemblyInfoText.ShouldMatchApproved(c => c.SubFolder(compiler.ApprovedSubFolder)); var compilation = compiler.Compile(assemblyInfoText); var emitResult = compilation.Emit(new MemoryStream()); Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Descriptor))); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_Major([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.Major); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinor([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinor); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinorPatch([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinorPatch); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinorPatchTag([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinorPatchTag); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_Major_InvalidInformationalValue([ValueSource("compilers")]ICompiler compiler) { var exception = Assert.Throws<WarningException>(() => VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.Major, "{ThisVariableDoesntExist}")); Assert.That(exception.Message, Does.Contain("ThisVariableDoesntExist")); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_Major_NugetAssemblyInfo([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.Major, "{NugetVersion}"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] public void VerifyAssemblyVersion_MajorMinor_NugetAssemblyInfoWithMultipleVariables([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinor, "{BranchName}-{Major}.{Minor}.{Patch}-{Sha}"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinor_NugetAssemblyInfo([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinor, "{NugetVersion}"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinorPatch_NugetAssemblyInfo([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinorPatch, "{NugetVersion}"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [NUnit.Framework.Category("NoMono")] [NUnit.Framework.Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void VerifyAssemblyVersion_MajorMinorPatchTag_NugetAssemblyInfo([ValueSource("compilers")]ICompiler compiler) { VerifyAssemblyVersion(compiler, AssemblyVersioningScheme.MajorMinorPatchTag, "{NugetVersion}"); } [Test] public void GetAssemblyInfoBuilder_Empty_ThrowsWarningException() { var taskItems = Substitute.For<IEnumerable<ITaskItem>>(); var exception = Assert.Throws<GitTools.WarningException>(() => AssemblyInfoBuilder.GetAssemblyInfoBuilder(taskItems)); exception.Message.ShouldBe("Unable to determine which AssemblyBuilder required to generate GitVersion assembly information"); } [Test] public void GetAssemblyInfoBuilder_Null_ThrowsArgumentNullException() { var exception = Assert.Throws<ArgumentNullException>(() => AssemblyInfoBuilder.GetAssemblyInfoBuilder(null)); exception.ParamName.ShouldBe("compileFiles"); } [TestCase("Class1.cs", typeof(CSharpAssemblyInfoBuilder))] [TestCase("Class1.vb", typeof(VisualBasicAssemblyInfoBuilder))] [TestCase("Class1.fs", typeof(FSharpAssemblyInfoBuilder))] [TestCase("AssemblyInfo.cs", typeof(CSharpAssemblyInfoBuilder))] [TestCase("AssemblyInfo.vb", typeof(VisualBasicAssemblyInfoBuilder))] [TestCase("AssemblyInfo.fs", typeof(FSharpAssemblyInfoBuilder))] public void GetAssemblyInfoBuilder_ShouldReturnAppropriateAssemblyInfoBuilder(string fileName, Type assemblyInfoBuilderType) { var taskItem = Substitute.For<ITaskItem>(); taskItem.ItemSpec.Returns(fileName); var assemblyInfoBuilder = AssemblyInfoBuilder.GetAssemblyInfoBuilder(new[] { taskItem }); assemblyInfoBuilder.ShouldNotBeNull(); assemblyInfoBuilder.ShouldBeOfType(assemblyInfoBuilderType); } static void VerifyAssemblyVersion(ICompiler compiler, AssemblyVersioningScheme avs, string assemblyInformationalFormat = null) { var semanticVersion = new SemanticVersion { Major = 2, Minor = 3, Patch = 4, PreReleaseTag = "beta.5", BuildMetaData = new SemanticVersionBuildMetaData(6, "master", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")), }; var config = new TestEffectiveConfiguration(assemblyVersioningScheme: avs, assemblyInformationalFormat: assemblyInformationalFormat); var versionVariables = VariableProvider.GetVariablesFor(semanticVersion, config, false); var assemblyInfoText = compiler.Builder.GetAssemblyInfoText(versionVariables, "Fake"); assemblyInfoText.ShouldMatchApproved(c => c.UseCallerLocation().SubFolder(compiler.ApprovedSubFolder)); var compilation = compiler.Compile(assemblyInfoText); var emitResult = compilation.Emit(new MemoryStream()); Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Descriptor))); } static void VerifyGitVersionInformationAttribute(Assembly assembly, VersionVariables versionVariables) { var gitVersionInformation = assembly.GetType("Fake.GitVersionInformation"); var fields = gitVersionInformation.GetFields(BindingFlags.Static | BindingFlags.Public); foreach (var variable in versionVariables) { Assert.IsNotNull(variable.Value); var field = fields.FirstOrDefault(p => p.Name == variable.Key); Assert.IsNotNull(field); var value = field.GetValue(null); Assert.AreEqual(variable.Value, value, "{0} had an invalid value.", field.Name); } } }
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// Structure describing the fine-grained features that can be supported by /// an implementation. /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct PhysicalDeviceFeatures { /// <summary> /// /// </summary> public bool RobustBufferAccess { get; set; } /// <summary> /// /// </summary> public bool FullDrawIndexUint32 { get; set; } /// <summary> /// /// </summary> public bool ImageCubeArray { get; set; } /// <summary> /// /// </summary> public bool IndependentBlend { get; set; } /// <summary> /// /// </summary> public bool GeometryShader { get; set; } /// <summary> /// /// </summary> public bool TessellationShader { get; set; } /// <summary> /// /// </summary> public bool SampleRateShading { get; set; } /// <summary> /// /// </summary> public bool DualSourceBlend { get; set; } /// <summary> /// /// </summary> public bool LogicOp { get; set; } /// <summary> /// /// </summary> public bool MultiDrawIndirect { get; set; } /// <summary> /// /// </summary> public bool DrawIndirectFirstInstance { get; set; } /// <summary> /// /// </summary> public bool DepthClamp { get; set; } /// <summary> /// /// </summary> public bool DepthBiasClamp { get; set; } /// <summary> /// /// </summary> public bool FillModeNonSolid { get; set; } /// <summary> /// /// </summary> public bool DepthBounds { get; set; } /// <summary> /// /// </summary> public bool WideLines { get; set; } /// <summary> /// /// </summary> public bool LargePoints { get; set; } /// <summary> /// /// </summary> public bool AlphaToOne { get; set; } /// <summary> /// /// </summary> public bool MultiViewport { get; set; } /// <summary> /// /// </summary> public bool SamplerAnisotropy { get; set; } /// <summary> /// /// </summary> public bool TextureCompressionETC2 { get; set; } /// <summary> /// /// </summary> public bool TexturecompressionastcLdr { get; set; } /// <summary> /// /// </summary> public bool TextureCompressionBC { get; set; } /// <summary> /// /// </summary> public bool OcclusionQueryPrecise { get; set; } /// <summary> /// /// </summary> public bool PipelineStatisticsQuery { get; set; } /// <summary> /// /// </summary> public bool VertexPipelineStoresAndAtomics { get; set; } /// <summary> /// /// </summary> public bool FragmentStoresAndAtomics { get; set; } /// <summary> /// /// </summary> public bool ShaderTessellationAndGeometryPointSize { get; set; } /// <summary> /// /// </summary> public bool ShaderImageGatherExtended { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageImageExtendedFormats { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageImageMultisample { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageImageReadWithoutFormat { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageImageWriteWithoutFormat { get; set; } /// <summary> /// /// </summary> public bool ShaderUniformBufferArrayDynamicIndexing { get; set; } /// <summary> /// /// </summary> public bool ShaderSampledImageArrayDynamicIndexing { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageBufferArrayDynamicIndexing { get; set; } /// <summary> /// /// </summary> public bool ShaderStorageImageArrayDynamicIndexing { get; set; } /// <summary> /// /// </summary> public bool ShaderClipDistance { get; set; } /// <summary> /// /// </summary> public bool ShaderCullDistance { get; set; } /// <summary> /// /// </summary> public bool ShaderFloat64 { get; set; } /// <summary> /// /// </summary> public bool ShaderInt64 { get; set; } /// <summary> /// /// </summary> public bool ShaderInt16 { get; set; } /// <summary> /// /// </summary> public bool ShaderResourceResidency { get; set; } /// <summary> /// /// </summary> public bool ShaderResourceMinLod { get; set; } /// <summary> /// /// </summary> public bool SparseBinding { get; set; } /// <summary> /// /// </summary> public bool SparseResidencyBuffer { get; set; } /// <summary> /// /// </summary> public bool SparseResidencyImage2D { get; set; } /// <summary> /// /// </summary> public bool SparseResidencyImage3D { get; set; } /// <summary> /// /// </summary> public bool SparseResidency2Samples { get; set; } /// <summary> /// /// </summary> public bool SparseResidency4Samples { get; set; } /// <summary> /// /// </summary> public bool SparseResidency8Samples { get; set; } /// <summary> /// /// </summary> public bool SparseResidency16Samples { get; set; } /// <summary> /// /// </summary> public bool SparseResidencyAliased { get; set; } /// <summary> /// /// </summary> public bool VariableMultisampleRate { get; set; } /// <summary> /// /// </summary> public bool InheritedQueries { get; set; } /// <summary> /// /// </summary> /// <param name="pointer"> /// </param> internal unsafe void MarshalTo(SharpVk.Interop.PhysicalDeviceFeatures* pointer) { pointer->RobustBufferAccess = this.RobustBufferAccess; pointer->FullDrawIndexUint32 = this.FullDrawIndexUint32; pointer->ImageCubeArray = this.ImageCubeArray; pointer->IndependentBlend = this.IndependentBlend; pointer->GeometryShader = this.GeometryShader; pointer->TessellationShader = this.TessellationShader; pointer->SampleRateShading = this.SampleRateShading; pointer->DualSourceBlend = this.DualSourceBlend; pointer->LogicOp = this.LogicOp; pointer->MultiDrawIndirect = this.MultiDrawIndirect; pointer->DrawIndirectFirstInstance = this.DrawIndirectFirstInstance; pointer->DepthClamp = this.DepthClamp; pointer->DepthBiasClamp = this.DepthBiasClamp; pointer->FillModeNonSolid = this.FillModeNonSolid; pointer->DepthBounds = this.DepthBounds; pointer->WideLines = this.WideLines; pointer->LargePoints = this.LargePoints; pointer->AlphaToOne = this.AlphaToOne; pointer->MultiViewport = this.MultiViewport; pointer->SamplerAnisotropy = this.SamplerAnisotropy; pointer->TextureCompressionETC2 = this.TextureCompressionETC2; pointer->TexturecompressionastcLdr = this.TexturecompressionastcLdr; pointer->TextureCompressionBC = this.TextureCompressionBC; pointer->OcclusionQueryPrecise = this.OcclusionQueryPrecise; pointer->PipelineStatisticsQuery = this.PipelineStatisticsQuery; pointer->VertexPipelineStoresAndAtomics = this.VertexPipelineStoresAndAtomics; pointer->FragmentStoresAndAtomics = this.FragmentStoresAndAtomics; pointer->ShaderTessellationAndGeometryPointSize = this.ShaderTessellationAndGeometryPointSize; pointer->ShaderImageGatherExtended = this.ShaderImageGatherExtended; pointer->ShaderStorageImageExtendedFormats = this.ShaderStorageImageExtendedFormats; pointer->ShaderStorageImageMultisample = this.ShaderStorageImageMultisample; pointer->ShaderStorageImageReadWithoutFormat = this.ShaderStorageImageReadWithoutFormat; pointer->ShaderStorageImageWriteWithoutFormat = this.ShaderStorageImageWriteWithoutFormat; pointer->ShaderUniformBufferArrayDynamicIndexing = this.ShaderUniformBufferArrayDynamicIndexing; pointer->ShaderSampledImageArrayDynamicIndexing = this.ShaderSampledImageArrayDynamicIndexing; pointer->ShaderStorageBufferArrayDynamicIndexing = this.ShaderStorageBufferArrayDynamicIndexing; pointer->ShaderStorageImageArrayDynamicIndexing = this.ShaderStorageImageArrayDynamicIndexing; pointer->ShaderClipDistance = this.ShaderClipDistance; pointer->ShaderCullDistance = this.ShaderCullDistance; pointer->ShaderFloat64 = this.ShaderFloat64; pointer->ShaderInt64 = this.ShaderInt64; pointer->ShaderInt16 = this.ShaderInt16; pointer->ShaderResourceResidency = this.ShaderResourceResidency; pointer->ShaderResourceMinLod = this.ShaderResourceMinLod; pointer->SparseBinding = this.SparseBinding; pointer->SparseResidencyBuffer = this.SparseResidencyBuffer; pointer->SparseResidencyImage2D = this.SparseResidencyImage2D; pointer->SparseResidencyImage3D = this.SparseResidencyImage3D; pointer->SparseResidency2Samples = this.SparseResidency2Samples; pointer->SparseResidency4Samples = this.SparseResidency4Samples; pointer->SparseResidency8Samples = this.SparseResidency8Samples; pointer->SparseResidency16Samples = this.SparseResidency16Samples; pointer->SparseResidencyAliased = this.SparseResidencyAliased; pointer->VariableMultisampleRate = this.VariableMultisampleRate; pointer->InheritedQueries = this.InheritedQueries; } /// <summary> /// /// </summary> /// <param name="pointer"> /// </param> internal static unsafe PhysicalDeviceFeatures MarshalFrom(SharpVk.Interop.PhysicalDeviceFeatures* pointer) { PhysicalDeviceFeatures result = default(PhysicalDeviceFeatures); result.RobustBufferAccess = pointer->RobustBufferAccess; result.FullDrawIndexUint32 = pointer->FullDrawIndexUint32; result.ImageCubeArray = pointer->ImageCubeArray; result.IndependentBlend = pointer->IndependentBlend; result.GeometryShader = pointer->GeometryShader; result.TessellationShader = pointer->TessellationShader; result.SampleRateShading = pointer->SampleRateShading; result.DualSourceBlend = pointer->DualSourceBlend; result.LogicOp = pointer->LogicOp; result.MultiDrawIndirect = pointer->MultiDrawIndirect; result.DrawIndirectFirstInstance = pointer->DrawIndirectFirstInstance; result.DepthClamp = pointer->DepthClamp; result.DepthBiasClamp = pointer->DepthBiasClamp; result.FillModeNonSolid = pointer->FillModeNonSolid; result.DepthBounds = pointer->DepthBounds; result.WideLines = pointer->WideLines; result.LargePoints = pointer->LargePoints; result.AlphaToOne = pointer->AlphaToOne; result.MultiViewport = pointer->MultiViewport; result.SamplerAnisotropy = pointer->SamplerAnisotropy; result.TextureCompressionETC2 = pointer->TextureCompressionETC2; result.TexturecompressionastcLdr = pointer->TexturecompressionastcLdr; result.TextureCompressionBC = pointer->TextureCompressionBC; result.OcclusionQueryPrecise = pointer->OcclusionQueryPrecise; result.PipelineStatisticsQuery = pointer->PipelineStatisticsQuery; result.VertexPipelineStoresAndAtomics = pointer->VertexPipelineStoresAndAtomics; result.FragmentStoresAndAtomics = pointer->FragmentStoresAndAtomics; result.ShaderTessellationAndGeometryPointSize = pointer->ShaderTessellationAndGeometryPointSize; result.ShaderImageGatherExtended = pointer->ShaderImageGatherExtended; result.ShaderStorageImageExtendedFormats = pointer->ShaderStorageImageExtendedFormats; result.ShaderStorageImageMultisample = pointer->ShaderStorageImageMultisample; result.ShaderStorageImageReadWithoutFormat = pointer->ShaderStorageImageReadWithoutFormat; result.ShaderStorageImageWriteWithoutFormat = pointer->ShaderStorageImageWriteWithoutFormat; result.ShaderUniformBufferArrayDynamicIndexing = pointer->ShaderUniformBufferArrayDynamicIndexing; result.ShaderSampledImageArrayDynamicIndexing = pointer->ShaderSampledImageArrayDynamicIndexing; result.ShaderStorageBufferArrayDynamicIndexing = pointer->ShaderStorageBufferArrayDynamicIndexing; result.ShaderStorageImageArrayDynamicIndexing = pointer->ShaderStorageImageArrayDynamicIndexing; result.ShaderClipDistance = pointer->ShaderClipDistance; result.ShaderCullDistance = pointer->ShaderCullDistance; result.ShaderFloat64 = pointer->ShaderFloat64; result.ShaderInt64 = pointer->ShaderInt64; result.ShaderInt16 = pointer->ShaderInt16; result.ShaderResourceResidency = pointer->ShaderResourceResidency; result.ShaderResourceMinLod = pointer->ShaderResourceMinLod; result.SparseBinding = pointer->SparseBinding; result.SparseResidencyBuffer = pointer->SparseResidencyBuffer; result.SparseResidencyImage2D = pointer->SparseResidencyImage2D; result.SparseResidencyImage3D = pointer->SparseResidencyImage3D; result.SparseResidency2Samples = pointer->SparseResidency2Samples; result.SparseResidency4Samples = pointer->SparseResidency4Samples; result.SparseResidency8Samples = pointer->SparseResidency8Samples; result.SparseResidency16Samples = pointer->SparseResidency16Samples; result.SparseResidencyAliased = pointer->SparseResidencyAliased; result.VariableMultisampleRate = pointer->VariableMultisampleRate; result.InheritedQueries = pointer->InheritedQueries; return result; } } }
using EaseFunction = System.Func<float, float, float>; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Prime31.GoKitLite { public class GoKitLite : AutoSingleton<GoKitLite> { static int _debugID; public static int DebugID { get { return _debugID;} set { _debugID = value; }} #region Internal classes and enums static void DebugTrapTween(Tween tween) { if(tween.GetID() == DebugID) { } } public class TweenCollection : IAdvYieldInstruction { List<TweenHandle> _tweenHandles = new List<TweenHandle>(); public void Add(Tween inTween) { TweenHandle handle = new TweenHandle(inTween); if(!_tweenHandles.Contains(handle)) _tweenHandles.Add(handle); } public bool IsDoneYielding() { bool isDone = true; for(int i = 0; i < _tweenHandles.Count && isDone; ++i) { isDone &= _tweenHandles[i].IsDoneYielding(); } return isDone; } } public class TweenHandle : IAdvYieldInstruction { //TYENOTE: these could be queues where we drop off the fronts when they're done. That would rid us of references for long chains. private List<Tween> tweens = new List<Tween>(); private List<int> tweenIds = new List<int>(); public TweenHandle(Tween inTween) { tweens.Add(inTween); tweenIds.Add(inTween.id); Tween nextTween = inTween.nextTween; while (nextTween != null) { tweens.Add(nextTween); tweenIds.Add(nextTween.id); nextTween = nextTween.nextTween; } //Get all tweens that point to these as their next tween (previous only went forward) for (int i = GoKitLite.GetInstance()._activeTweens.Count-1; i >= 0 ; --i) { var tween = GoKitLite.GetInstance()._activeTweens[i]; if (tween.nextTween != null && tweens.Contains(tween.nextTween)) { tweens.Add(tween); tweenIds.Add(tween.id); } } } public bool StopTween(bool bringToCompletion) { for (int i = 0; i < tweenIds.Count; ++i) { if (GoKitLite.GetInstance().StopTween(tweenIds[i], bringToCompletion)) return true; } return false; } public bool IsDoneYielding() { bool done = true; for (int i = 0; i < tweens.Count; ++i) { Tween tween = tweens[i]; done &= tween == null || tween._elapsedTime == tween.duration || tween.id != tweenIds[i]; } return done; } } public class Tween { public TweenHandle GetTweenHandle() { return new TweenHandle(this); } private enum TargetValueType { None, Vector3, Color, Float, } // common properties internal int id; internal Transform transform; internal RectTransform rectTransform; internal Material material; internal TweenType tweenType; internal bool isTimeScaleIndependent; internal bool isRunningInReverse; internal float duration; internal float delay; internal float delayBetweenLoops; internal EaseFunction easeFunction; internal bool isRelativeTween; internal Action<Transform> onComplete; internal Action<Transform> onLoopComplete; internal LoopType loopType; internal int loops = 0; internal Tween nextTween; // tweenable: Vector3 internal Vector3 targetVector; private Vector3 _startVector; private Vector3 _diffVector; // Tweenable shared: material property name. internal string materialProperty; // tweenable: Color internal Color targetColor; private Color _startColor; private Color _diffColor; // tweenable: Sprite Tint public SpriteRenderer spriteRenderer; // tweenable: float public float targetFloat; float _startFloat; float _diffFloat; // tweenable: Action and property internal Action<Transform,float> customAction; internal ITweenable propertyTween; // internal state internal float _elapsedTime; private TargetValueType targetValueType; internal bool isPaused; private bool isActive = false; internal void reset() { // any pointers or values that are not guaranteed to be set later are defaulted here isActive = false; transform = null; rectTransform = null; targetVector = _startVector = _diffVector = Vector3.zero; targetColor = _startColor = _diffColor = Color.white; delay = delayBetweenLoops = 0f; isTimeScaleIndependent = isRunningInReverse = isPaused = false; loopType = LoopType.None; easeFunction = null; isRelativeTween = false; onComplete = onLoopComplete = null; customAction = null; propertyTween = null; material = null; materialProperty = null; spriteRenderer = null; if( nextTween != null ) { // null out and return to the stack all additional tweens GoKitLite.GetInstance()._inactiveTweenStack.Push( nextTween ); nextTween.reset(); } nextTween = null; } /// <summary> /// sets the appropriate start value and calculates the diffValue /// </summary> internal void PrepareForUse() { if(easeFunction == null) easeFunction = defaultEaseFunction; switch(tweenType) { case TweenType.Position: targetValueType = TargetValueType.Vector3; _startVector = transform.position; break; case TweenType.LocalPosition: targetValueType = TargetValueType.Vector3; _startVector = transform.localPosition; break; case TweenType.Scale: targetValueType = TargetValueType.Vector3; _startVector = transform.localScale; break; case TweenType.Rotation: targetValueType = TargetValueType.Vector3; _startVector = transform.rotation.eulerAngles; if(isRelativeTween) _diffVector = targetVector; else _diffVector = new Vector3(Mathf.DeltaAngle(_startVector.x, targetVector.x), Mathf.DeltaAngle(_startVector.y, targetVector.y), Mathf.DeltaAngle(_startVector.z, targetVector.z)); break; case TweenType.LocalRotation: targetValueType = TargetValueType.Vector3; _startVector = transform.localRotation.eulerAngles; if(isRelativeTween) _diffVector = targetVector; else _diffVector = new Vector3(Mathf.DeltaAngle(_startVector.x, targetVector.x), Mathf.DeltaAngle(_startVector.y, targetVector.y), Mathf.DeltaAngle(_startVector.z, targetVector.z)); break; case TweenType.RectTransformPosition: targetValueType = TargetValueType.Vector3; _startVector = rectTransform.anchoredPosition3D; break; case TweenType.Color: targetValueType = TargetValueType.Color; break; case TweenType.SpriteTint: targetValueType = TargetValueType.Color; break; case TweenType.Float: targetValueType = TargetValueType.Float; break; case TweenType.Action: targetValueType = TargetValueType.None; break; case TweenType.Property: targetValueType = TargetValueType.None; propertyTween.prepareForUse(); break; } _elapsedTime = -delay; // we have to be careful with rotations because we always want to rotate in the shortest angle so we set the diffValue with that in mind if(targetValueType == TargetValueType.Vector3 && tweenType != TweenType.Rotation && tweenType != TweenType.LocalRotation) { if(isRelativeTween) _diffVector = targetVector; else _diffVector = targetVector - _startVector; } else if(targetValueType == TargetValueType.Color) { if(tweenType == TweenType.Color) _startColor = material.GetColor(materialProperty); else if(tweenType == TweenType.SpriteTint) _startColor = spriteRenderer.color; if(isRelativeTween) _diffColor = targetColor; else _diffColor = targetColor - _startColor; } else if(targetValueType == TargetValueType.Float) { _startFloat = material.GetFloat(materialProperty); if(isRelativeTween) _diffFloat = targetFloat; else _diffFloat = targetFloat - _startFloat; } } /// <summary> /// handles the tween. returns true if it is complete and ready for removal /// </summary> internal bool tick( bool completeTweenThisStep = false ) { DebugTrapTween(this); // fetch our deltaTime. It will either be taking this to completion or standard delta/unscaledDelta var deltaTime = completeTweenThisStep ? float.MaxValue : ( isTimeScaleIndependent ? Time.unscaledDeltaTime : Time.deltaTime ); // add deltaTime to our elapsed time and clamp it from -delay to duration _elapsedTime = Mathf.Clamp( _elapsedTime + deltaTime, -delay, duration ); // if we have a delay, we will have a negative elapsedTime until the delay is complete if(_elapsedTime <= 0 && duration > 0f) return false; float easedTime = 0f; if(duration > 0f) { var modifiedElapsedTime = isRunningInReverse ? duration - _elapsedTime : _elapsedTime; easedTime = easeFunction(modifiedElapsedTime, duration); } else { easedTime = 1f; } // special case: Action tweens if( tweenType == TweenType.Action ) customAction( transform, easedTime ); else if( tweenType == TweenType.Property ) propertyTween.tick( easedTime ); if( targetValueType == TargetValueType.Vector3 ) { var easedVector = new Vector3 ( _startVector.x + _diffVector.x * easedTime, _startVector.y + _diffVector.y * easedTime, _startVector.z + _diffVector.z * easedTime ); SetVectorAsRequiredPerCurrentTweenType( ref easedVector ); } else if( targetValueType == TargetValueType.Color ) { var easedColor = new Color ( _startColor.r + _diffColor.r*easedTime, _startColor.g + _diffColor.g*easedTime, _startColor.b + _diffColor.b*easedTime, _startColor.a + _diffColor.a*easedTime ); if(tweenType == TweenType.Color) { material.SetColor(materialProperty, easedColor); } else if(tweenType == TweenType.SpriteTint) { spriteRenderer.color = easedColor; } } else if(targetValueType == TargetValueType.Float) { var easedFloat = _startFloat + _diffFloat * easedTime; material.SetFloat(materialProperty, easedFloat); } // if we have a loopType and we are done do the loop if( loopType != GoKitLite.LoopType.None && _elapsedTime == duration ) handleLooping(); if (!isActive) isActive = true; return _elapsedTime == duration; } /// <summary> /// handles loop logic /// </summary> private void handleLooping() { loops--; if( loopType == GoKitLite.LoopType.RestartFromBeginning ) { if(targetValueType == TargetValueType.Vector3) { SetVectorAsRequiredPerCurrentTweenType(ref _startVector); } else if(targetValueType == TargetValueType.Color) { if(tweenType == TweenType.Color) { material.SetColor(materialProperty, _startColor); } else if(tweenType == TweenType.SpriteTint) { spriteRenderer.color = _startColor; } } else if(targetValueType == TargetValueType.Float) { material.SetFloat(materialProperty, _startFloat); } PrepareForUse(); } else // ping-pong { isRunningInReverse = !isRunningInReverse; } if( loopType == GoKitLite.LoopType.RestartFromBeginning || loops % 2 == 1 ) { if( onLoopComplete != null ) onLoopComplete( transform ); } // kill our loop if we have no loops left and zero out the delay then prepare for use if( loops == 0 ) loopType = GoKitLite.LoopType.None; delay = delayBetweenLoops; _elapsedTime = -delay; } /// <summary> /// if we have an appropriate tween type that takes a vector value this will correctly set it /// </summary> private void SetVectorAsRequiredPerCurrentTweenType( ref Vector3 vec ) { switch( tweenType ) { case TweenType.Position: transform.position = vec; break; case TweenType.LocalPosition: transform.localPosition = vec; break; case TweenType.Scale: transform.localScale = vec; break; case TweenType.Rotation: transform.eulerAngles = vec; break; case TweenType.LocalRotation: transform.localEulerAngles = vec; break; case TweenType.RectTransformPosition: rectTransform.anchoredPosition3D = vec; break; } } /// <summary> /// reverses the current tween. if it was going forward it will be going backwards and vice versa. /// </summary> public void ReverseTween() { isRunningInReverse = !isRunningInReverse; _elapsedTime = duration - _elapsedTime; } /// <summary> /// chainable. Sets the EaseFunction used by the tween. /// </summary> public Tween SetEaseFunction( EaseFunction easeFunction ) { this.easeFunction = easeFunction; return this; } /// <summary> /// chainable. sets the action that should be called when the tween is complete. do not store a reference to the tween! /// </summary> public Tween SetCompletionHandler( Action<Transform> onComplete ) { this.onComplete = onComplete; return this; } /// <summary> /// chainable. sets the action that should be called when a loop is complete. A loop is either when the first part of /// a ping-pong animation completes or when starting over when using a restart-from-beginning loop type. Note that ping-pong /// loops (which are really two part tweens) will not fire the loop completion handler on the last iteration. The normal /// tween completion handler will fire though /// </summary> public Tween SetLoopCompletionHandler( Action<Transform> onLoopComplete ) { this.onLoopComplete = onLoopComplete; return this; } /// <summary> /// chainable. set the loop type for the tween. a single pingpong loop means going from start-finish-start. /// </summary> public Tween SetLoopType( LoopType loopType, int loops = 1, float delayBetweenLoops = 0f ) { this.loopType = loopType; this.delayBetweenLoops = delayBetweenLoops; // double the loop count for ping-pong if( loopType == LoopType.PingPong ) loops = loops * 2 - 1; this.loops = loops; return this; } /// <summary> /// chainable. sets the delay for the tween. /// </summary> public Tween SetDelay( float delay ) { this.delay = delay; _elapsedTime = -delay; return this; } /// <summary> /// sets the tween to be time scale independent /// </summary> /// <returns>The Tween</returns> public Tween SetTimeScaleIndependent() { isTimeScaleIndependent = true; return this; } /// <summary> /// gets the id which can be used to stop the tween later /// </summary> public int GetID() { return id; } /// <summary> /// adds a vector tween using this tween's Transform and type that will start as soon as this completes /// </summary> public Tween Next( float duration, Vector3 targetVector, float delay = 0 ) { var tween = GoKitLite.GetInstance().VectorTweenTo_Inactive( transform, tweenType, duration, targetVector, false ); tween.delay = delay; nextTween = tween; return tween; } /// <summary> /// adds a vector tween using this tween's Transform and type that will start as soon as this completes /// </summary> public Tween Next( float duration, Vector3 targetVector, float delay, EaseFunction easeFunction, bool isRelativeTween = false ) { var tween = GoKitLite.GetInstance().VectorTweenTo_Inactive( transform, tweenType, duration, targetVector, isRelativeTween ); tween.delay = delay; nextTween = tween; return tween; } /// <summary> /// adds a tween that will start as soon as this tween completes /// </summary> public Tween Next( TweenType tweenType, float duration, Vector3 targetVector, bool isRelativeTween = false ) { var tween = GoKitLite.GetInstance().VectorTweenTo_Inactive( transform, tweenType, duration, targetVector, isRelativeTween ); tween.delay = delay; nextTween = tween; return tween; } /// <summary> /// adds a tween that will start as soon as this tween completes /// </summary> public Tween Next( Transform trans, TweenType tweenType, float duration, Vector3 targetVector, bool isRelativeTween = false ) { var tween = GoKitLite.GetInstance().VectorTweenTo_Inactive( trans, tweenType, duration, targetVector, isRelativeTween ); tween.delay = delay; nextTween = tween; return tween; } /// <summary> /// adds a color tween using this tween's Transform and type that will start as soon as this completes /// </summary> public Tween Next( float duration, Color targetColor, Renderer inRenderer) { var tween = GoKitLite.GetInstance().ColorTweenTo_Inactive( transform, duration, targetColor, inRenderer, "_Color", false ); tween.easeFunction = easeFunction; nextTween = tween; return tween; } /// <summary> /// adds a color tween using this tween's Transform that will start as soon as this completes /// </summary> public Tween Next( float duration, Color targetColor, Renderer inRenderer, string materialProperty, bool isRelativeTween = false ) { var tween = GoKitLite.GetInstance().ColorTweenTo_Inactive( transform, duration, targetColor, inRenderer, materialProperty, isRelativeTween ); tween.easeFunction = easeFunction; nextTween = tween; return tween; } /// <summary> /// adds a sprite alpha tween using this tween's Transform that will start as soon as this completes /// </summary> public Tween NextSpriteAlphaTween( float duration, float targetAlpha, bool isRelativeTween = false ) { var color = spriteRenderer.color; color.a = targetAlpha; var tween = GoKitLite.GetInstance().SpriteTintTweenTo_Inactive( transform, duration, color, spriteRenderer); tween.easeFunction = easeFunction; nextTween = tween; return tween; } /// <summary> /// adds a float material property tween using this tween's Transform that will start as soon as this completes /// </summary> public Tween NextFloatTween( float duration, float targetFloat, bool isRelativeTween = false ) { var tween = GoKitLite.GetInstance().MaterialFloatPropertyTo_Inactive( transform, duration, targetFloat, material, materialProperty); tween.easeFunction = easeFunction; nextTween = tween; return tween; } /// <summary> /// adds a property tween that will start as soon as the current tween completes /// </summary> public Tween Next( float duration, ITweenable newPropertyTween ) { var tween = GoKitLite.GetInstance().nextAvailableTween( transform, duration, TweenType.Property ); tween.easeFunction = easeFunction; tween.propertyTween = newPropertyTween; nextTween = tween; return tween; } /// <summary> /// adds a custom action tween using this tween's Transform that will start as soon as the current tween completes /// </summary> public Tween Next( float duration, Action<Transform, float> action ) { var tween = GoKitLite.GetInstance().nextAvailableTween( transform, duration, TweenType.Action ); tween.easeFunction = easeFunction; tween.customAction = action; nextTween = tween; return tween; } /// <summary> /// adds a custom action tween that will start as soon as the current tween completes /// </summary> public Tween Next( Transform trans, float duration, Action<Transform, float> action ) { var tween = GoKitLite.GetInstance().nextAvailableTween( trans, duration, TweenType.Action ); tween.easeFunction = easeFunction; tween.customAction = action; nextTween = tween; return tween; } } public enum TweenType { Position, LocalPosition, Rotation, LocalRotation, Scale, RectTransformPosition, Color, Action, Property, SpriteTint, Float, } public enum LoopType { None, RestartFromBeginning, PingPong } #endregion private List<Tween> _activeTweens = new List<Tween>( 20 ); internal Stack<Tween> _inactiveTweenStack = new Stack<Tween>( 20 ); private int _tweenIdCounter = 0; public static EaseFunction defaultEaseFunction = GoKitLiteEasing.Quartic.EaseIn; #region MonoBehaviour private void Update() { // loop backwards so we can remove completed tweens for( var i = _activeTweens.Count - 1; i >= 0; --i ) { var tween = _activeTweens[i]; if( tween.isPaused ) continue; if( tween.transform == null || tween.tick() ) { if( tween.onComplete != null ) tween.onComplete( tween.transform ); // handle nextTween if we have a chain if( tween.nextTween != null ) { tween.nextTween.PrepareForUse(); _activeTweens.Add( tween.nextTween ); // null out the nextTween so that the reset method doesnt remove it! tween.nextTween = null; } RemoveActiveTween( tween, i ); } } #if UNITY_EDITOR gameObject.name = string.Format("GoKitLite active tweens: {0}", _activeTweens.Count); #endif } #endregion #region Private Tween VectorTweenTo_Inactive( Transform trans, TweenType tweenType, float duration, Vector3 targetVector, bool isRelativeTween = false ) { var tween = nextAvailableTween( trans, duration, tweenType ); tween.targetVector = targetVector; tween.isRelativeTween = isRelativeTween; return tween; } Tween ColorTweenTo_Inactive( Transform trans, float duration, Color targetColor, Renderer inRenderer, string materialProperty = "_Color", bool isRelativeTween = false ) { var tween = nextAvailableTween(trans, duration, TweenType.Color); tween.targetColor = targetColor; tween.material = inRenderer.sharedMaterial; tween.materialProperty = materialProperty; tween.isRelativeTween = isRelativeTween; return tween; } Tween SpriteTintTweenTo_Inactive(Transform trans, float duration, Color targetColor, SpriteRenderer inSpriteRenderer, bool isRelativeTween = false) { var tween = nextAvailableTween(trans, duration, TweenType.SpriteTint); tween.targetColor = targetColor; tween.spriteRenderer = inSpriteRenderer; tween.isRelativeTween = isRelativeTween; return tween; } Tween MaterialFloatPropertyTo_Inactive(Transform transform, float duration, float targetFloat, Material inMaterial, string materialProperty, bool isRelativeTween = false ) { var tween = nextAvailableTween(transform, duration, TweenType.Float); tween.targetFloat = targetFloat; tween.material = inMaterial; tween.materialProperty = materialProperty; tween.isRelativeTween = isRelativeTween; return tween; } Tween nextAvailableTween( Transform trans, float duration, TweenType tweenType ) { Tween tween = null; if( _inactiveTweenStack.Count > 0 ) tween = _inactiveTweenStack.Pop(); else tween = new Tween(); tween.id = ++_tweenIdCounter; tween.transform = trans; tween.duration = duration; tween.tweenType = tweenType; return tween; } void RemoveActiveTween(Tween tween, int index) { DebugTrapTween(tween); _activeTweens.RemoveAt(index); tween.reset(); tween.id = -tween.id; _inactiveTweenStack.Push(tween); } void AddActiveTween(Tween tween) { _activeTweens.Add(tween); } #endregion #region Public public Tween PositionTo(Transform trans, float duration, Vector3 targetPosition, bool isRelativeTween = false) { var tween = VectorTweenTo_Inactive(trans, TweenType.Position, duration, targetPosition, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween PositionFrom( Transform trans, float duration, Vector3 targetPosition, bool isRelativeTween = false ) { var currentPosition = trans.position; trans.position = targetPosition; return PositionTo( trans, duration, currentPosition, isRelativeTween ); } public Tween LocalPositionTo( Transform trans, float duration, Vector3 targetPosition, bool isRelativeTween = false ) { var tween = VectorTweenTo_Inactive( trans, TweenType.LocalPosition, duration, targetPosition, isRelativeTween ); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween LocalPositionFrom( Transform trans, float duration, Vector3 targetPosition, bool isRelativeTween = false ) { var currentPosition = trans.localPosition; trans.localPosition = targetPosition; return LocalPositionTo( trans, duration, currentPosition, isRelativeTween ); } public Tween ScaleTo( Transform trans, float duration, Vector3 targetScale, bool isRelativeTween = false ) { var tween = VectorTweenTo_Inactive( trans, TweenType.Scale, duration, targetScale, isRelativeTween ); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween ScaleFrom( Transform trans, float duration, Vector3 targetScale, bool isRelativeTween = false ) { var currentScale = trans.localScale; trans.localScale = targetScale; return ScaleTo( trans, duration, currentScale, isRelativeTween ); } public Tween RotationTo( Transform trans, float duration, Vector3 targetEulers, bool isRelativeTween = false ) { var tween = VectorTweenTo_Inactive( trans, TweenType.Rotation, duration, targetEulers, isRelativeTween ); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween rectTransformPositionTo( RectTransform trans, float duration, Vector3 targetScale, bool isRelativeTween = false ) { var tween = VectorTweenTo_Inactive( trans, TweenType.RectTransformPosition, duration, targetScale, isRelativeTween ); tween.rectTransform = trans; tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween RotationFrom( Transform trans, float duration, Vector3 targetEulers, bool isRelativeTween = false ) { var currentEulers = trans.eulerAngles; trans.eulerAngles = targetEulers; return RotationTo( trans, duration, currentEulers, isRelativeTween ); } public Tween LocalRotationTo( Transform trans, float duration, Vector3 targetEulers, bool isRelativeTween = false ) { var tween = VectorTweenTo_Inactive( trans, TweenType.LocalRotation, duration, targetEulers, isRelativeTween ); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween LocalRotationFrom( Transform trans, float duration, Vector3 targetEulers, bool isRelativeTween = false ) { var currentEulers = trans.localEulerAngles; trans.localEulerAngles = targetEulers; return LocalRotationTo( trans, duration, currentEulers, isRelativeTween ); } public TweenCollection AllSpriteTintsTo(Transform trans, float duration, Color targetColor, bool isRelativeTween = false) { var spriteRenderers = trans.GetComponentsInChildren<SpriteRenderer>(); TweenCollection tweens = new TweenCollection(); for (int i = 0; i < spriteRenderers.Length; ++i) { var tween = SpriteTintTweenTo_Inactive(trans, duration, targetColor, spriteRenderers[i], isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public TweenCollection AllSpriteTintsFrom(Transform trans, float duration, Color targetColor, bool isRelativeTween = false) { var spriteRenderers = trans.GetComponentsInChildren<SpriteRenderer>(true); TweenCollection tweens = new TweenCollection(); for (int i = 0; i < spriteRenderers.Length; ++i) { var currentColor = spriteRenderers[i].color; spriteRenderers[i].color = targetColor; var tween = SpriteTintTweenTo_Inactive(trans, duration, currentColor, spriteRenderers[i], isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public Tween SpriteTintTo(SpriteRenderer spriteRenderer, float duration, Color targetColor, bool isRelativeTween = false) { var tween = SpriteTintTweenTo_Inactive(spriteRenderer.transform, duration, targetColor, spriteRenderer, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public TweenCollection AllSpritesAlphaTo(Transform trans, float duration, float targetAlpha, bool isRelativeTween = false) { var spriteRenderers = trans.GetComponentsInChildren<SpriteRenderer>(true); TweenCollection tweens = new TweenCollection(); for (int i = 0; i < spriteRenderers.Length; ++i) { var targetColor = spriteRenderers[i].color; targetColor.a = targetAlpha; var tween = SpriteTintTweenTo_Inactive(trans, duration, targetColor, spriteRenderers[i], isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public Tween SpriteAlphaTo(Transform trans, float duration, float targetAlpha, bool isRelativeTween = false) { var spriteRenderer = trans.GetComponent<SpriteRenderer>(true); return SpriteAlphaTo(spriteRenderer, duration, targetAlpha, isRelativeTween); } public Tween SpriteAlphaTo(SpriteRenderer spriteRenderer, float duration, float targetAlpha, bool isRelativeTween = false) { var targetColor = spriteRenderer.color; targetColor.a = targetAlpha; var tween = SpriteTintTweenTo_Inactive(spriteRenderer.transform, duration, targetColor, spriteRenderer, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public TweenCollection AllSpritesAlphaFrom(Transform trans, float duration, float targetAlpha, bool isRelativeTween = false) { var renderers = trans.GetComponentsInChildren<SpriteRenderer>(); TweenCollection tweens = new TweenCollection(); for (int i = 0; i < renderers.Length; ++i) { var targetColor = renderers[i].color; var currentColor = targetColor; targetColor.a = targetAlpha; renderers[i].color = targetColor; var tween = SpriteTintTweenTo_Inactive(trans, duration, currentColor, renderers[i], isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public TweenCollection AllMaterialColorsTo(Transform trans, float duration, Color targetColor, string materialProperty = "_Color", bool isRelativeTween = false) { var renderers = trans.GetComponentsInChildren<Renderer>(); TweenCollection tweens = new TweenCollection(); for(int i = 0; i < renderers.Length; ++i) { var tween = ColorTweenTo_Inactive(trans, duration, targetColor, renderers[i], materialProperty, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public TweenCollection AllMaterialColorsFrom(Transform trans, float duration, Color targetColor, string materialProperty = "_Color", bool isRelativeTween = false) { var renderers = trans.GetComponentsInChildren<Renderer>(true); TweenCollection tweens = new TweenCollection(); for(int i = 0; i < renderers.Length; ++i) { var currentColor = renderers[i].sharedMaterial.GetColor(materialProperty); renderers[i].sharedMaterial.SetColor(materialProperty, targetColor); var tween = ColorTweenTo_Inactive(trans, duration, currentColor, renderers[i], materialProperty, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public TweenCollection AllMaterialAlphasTo(Transform trans, float duration, float targetAlpha, string materialProperty = "_Color", bool isRelativeTween = false) { var renderers = trans.GetComponentsInChildren<Renderer>(true); TweenCollection tweens = new TweenCollection(); for(int i = 0; i < renderers.Length; ++i) { var targetColor = renderers[i].sharedMaterial.GetColor(materialProperty); targetColor.a = targetAlpha; var tween = ColorTweenTo_Inactive(trans, duration, targetColor, renderers[i], materialProperty, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public TweenCollection AllMaterialAlphasFrom(Transform trans, float duration, float targetAlpha, string materialProperty = "_Color", bool isRelativeTween = false) { var renderers = trans.GetComponentsInChildren<Renderer>(true); TweenCollection tweens = new TweenCollection(); for(int i = 0; i < renderers.Length; ++i) { var targetColor = renderers[i].sharedMaterial.GetColor(materialProperty); var currentColor = targetColor; targetColor.a = targetAlpha; renderers[i].sharedMaterial.SetColor(materialProperty, targetColor); var tween = ColorTweenTo_Inactive(trans, duration, currentColor, renderers[i], materialProperty, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); } return tweens; } public Tween MaterialFloatTo(Transform trans, float duration, float targetFloat, Material inMaterial, string materialProperty, bool isRelativeTween = false) { var tween = MaterialFloatPropertyTo_Inactive(trans, duration, targetFloat, inMaterial, materialProperty, isRelativeTween); tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween CustomAction( Transform trans, float duration, Action<Transform,float> action ) { var tween = nextAvailableTween( trans, duration, TweenType.Action ); tween.customAction = action; tween.PrepareForUse(); AddActiveTween(tween); return tween; } public Tween propertyTween( ITweenable propertyTween, float duration ) { var tween = nextAvailableTween( this.transform, duration, TweenType.Property ); tween.propertyTween = propertyTween; tween.PrepareForUse(); AddActiveTween(tween); return tween; } #endregion #region Tween Management /// <summary> /// stops the tween optionally bringing it to its final value first. returns true if the tween was found and stopped. /// </summary> public bool StopTween( int id, bool bringToCompletion ) { for( var i = 0; i < _activeTweens.Count; i++ ) { if( _activeTweens[i].id == id ) { // send in a delta of float.max if we should be completing this tween before killing it if( bringToCompletion ) _activeTweens[i].tick( true ); RemoveActiveTween( _activeTweens[i], i ); return true; } } return false; } /// <summary> /// Stops all in-progress tweens affiliated with a given transform optionally bringing them to their final values. /// </summary> /// <param name="bringToCompletion">If true, then all active tweens are broght to completion before they are stopped</param> public void StopAllTweens(Transform inTransform, bool bringToCompletion) { for (var i = _activeTweens.Count - 1; i >= 0; --i) { if(_activeTweens[i].transform == inTransform) { // send in a delta of float.max if we should be completing this tween before killing it if(bringToCompletion) _activeTweens[i].tick(true); RemoveActiveTween(_activeTweens[i], i); } } } /// <summary> /// Stops all in-progress tweens optionally bringing them to their final values. /// </summary> /// <param name="bringToCompletion">If true, then all active tweens are broght to completion before they are stopped</param> public void StopAllTweens( bool bringToCompletion ) { for( var i = _activeTweens.Count - 1; i >= 0; --i ) { // send in a delta of float.max if we should be completing this tween before killing it if( bringToCompletion ) _activeTweens[i].tick( true ); RemoveActiveTween( _activeTweens[i], i ); } } /// <summary> /// set the tween's pause state. returns true if the tween was found. /// </summary> public bool setTweenPauseState( int id, bool isPaused ) { for( var i = 0; i < _activeTweens.Count; i++ ) { if( _activeTweens[i].id == id ) { _activeTweens[i].isPaused = isPaused; return true; } } return false; } /// <summary> /// set all in-progress tween's pause state. /// </summary> public void setAllTweenPauseState( bool isPaused ) { for( var i = 0; i < _activeTweens.Count; i++ ) _activeTweens[i].isPaused = isPaused; } /// <summary> /// Checks if the current tween is active /// </summary> /// <param name="id"></param> /// <returns>True if the tween is active, false otherwise</returns> public bool isTweenActive( int id ) { for( var i = 0; i < _activeTweens.Count; i++ ) { if( _activeTweens[i].id == id ) return true; } return false; } /// <summary> /// reverses the tween. if it was going forward it will be going backwards and vice versa. /// </summary> /// <param name="id"></param> /// <returns>True if the tween is active, false otherwise</returns> private bool reverseTween( int id ) { for( var i = 0; i < _activeTweens.Count; i++ ) { if( _activeTweens[i].id == id ) { _activeTweens[i].ReverseTween(); return true; } } return false; } /// <summary> /// find an active tween with given id, do not store a reference to the tween! /// </summary> public Tween getActiveTween( int id ) { for( var i = 0; i < _activeTweens.Count; i++ ) { if( _activeTweens[i].id == id ) return _activeTweens[i]; } return null; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_SYSTEM_CONFIGURATION using System.Configuration; using Microsoft.Win32; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Shared; using Xunit; using System; using System.Collections.Generic; using System.IO; using Microsoft.Build.UnitTests; namespace Microsoft.Build.UnitTests.Evaluation { /// <summary> /// Unit tests for Importing from $(MSBuildExtensionsPath*) /// </summary> public class ImportFromMSBuildExtensionsPathTests : IDisposable { string toolsVersionToUse = null; public ImportFromMSBuildExtensionsPathTests() { toolsVersionToUse = new ProjectCollection().DefaultToolsVersion; } public void Dispose() { ToolsetConfigurationReaderTestHelper.CleanUp(); } [Fact] public void ImportFromExtensionsPathFound() { CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath", (p, l) => Assert.True(p.Build())); } [Fact] public void ImportFromExtensionsPathNotFound() { string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1()); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistent"))); var logger = new MockLogger(); projColln.RegisterLogger(logger); Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath)); logger.AssertLogContains("MSB4226"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } } } [Fact] public void ConditionalImportFromExtensionsPathNotFound() { string extnTargetsFileContentWithCondition = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FooBar</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\bar\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\bar\extn2.proj')""/> </Project> "; string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentWithCondition); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir1, Path.Combine("tmp", "nonexistent")}, null, (p, l) => { Assert.True(p.Build()); l.AssertLogContains("Running FromExtn"); l.AssertLogContains("PropertyFromExtn1: FooBar"); }); } [Fact] public void ImportFromExtensionsPathCircularImportError() { string extnTargetsFileContent1 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\foo\extn2.proj' /> </Project> "; string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn2'> <Message Text='Running FromExtn'/> </Target> <Import Project='{0}'/> </Project> "; string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn2.proj"), String.Format(extnTargetsFileContent2, mainProjectPath)); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir2, Path.Combine("tmp", "nonexistent"), extnDir1}, null, (p, l) => l.AssertLogContains("MSB4210")); } [Fact] public void ExtensionPathFallbackIsCaseInsensitive() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='Main'> <Message Text='Running Main'/> </Target> <Import Project='$(msbuildExtensionsPath)\foo\extn.proj'/> </Project>"; string extnTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running {0}'/> </Target> </Project> "; string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new[] { extnDir1 }, null, (project, logger) => { Console.WriteLine(logger.FullLog); Console.WriteLine("checking FromExtn"); Assert.True(project.Build("FromExtn")); Console.WriteLine("checking logcontains"); logger.AssertLogDoesntContain("MSB4057"); // Should not contain TargetDoesNotExist }); } [Fact] public void ImportFromExtensionsPathWithWildCard() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='Main'> <Message Text='Running Main'/> </Target> <Import Project='$(MSBuildExtensionsPath)\foo\*.proj'/> </Project>"; string extnTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='{0}'> <Message Text='Running {0}'/> </Target> </Project> "; // Importing a wildcard will union all matching results from all fallback locations. string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), string.Format(extnTargetsFileContent, "FromExtn1")); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), string.Format(extnTargetsFileContent, "FromExtn2")); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new[] {extnDir1, Path.Combine("tmp", "nonexistent"), extnDir2}, null, (project, logger) => { Console.WriteLine(logger.FullLog); Console.WriteLine("checking FromExtn1"); Assert.True(project.Build("FromExtn1")); Console.WriteLine("checking FromExtn2"); Assert.True(project.Build("FromExtn2")); Console.WriteLine("checking logcontains"); logger.AssertLogDoesntContain("MSB4057"); // Should not contain TargetDoesNotExist }); } [Fact] public void ImportFromExtensionsPathWithWildCardAndSelfImport() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='Main'> <Message Text='Running Main'/> </Target> <Import Project='$(MSBuildExtensionsPath)\circularwildcardtest\*.proj'/> </Project>"; string extnTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='{0}'> <Message Text='Running {0}'/> </Target> </Project>"; string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Import Project='$(MSBuildExtensionsPath)\circularwildcardtest\*.proj'/> <Target Name='{0}'> <Message Text='Running {0}'/> </Target> </Project>"; // Importing a wildcard will union all matching results from all fallback locations. string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("circularwildcardtest", "extn.proj"), string.Format(extnTargetsFileContent, "FromExtn1")); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("circularwildcardtest", "extn.proj"), string.Format(extnTargetsFileContent, "FromExtn2")); string extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("circularwildcardtest", "extn3.proj"), string.Format(extnTargetsFileContent2, "FromExtn3")); // Main project path is under "circularwildcardtest" // Note: This project will try to be imported again and cause a warning (MSB4210). This test should ensure that the // code does not stop looking in the fallback locations when this happens (extn3.proj should still be imported). string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory(Path.Combine("extensions2", "circularwildcardtest", "main.proj"), mainTargetsFileContent); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new[] { extnDir1, extnDir2, extnDir3 }, null, (project, logger) => { Console.WriteLine(logger.FullLog); Assert.True(project.Build("FromExtn1")); Assert.True(project.Build("FromExtn2")); Assert.True(project.Build("FromExtn3")); logger.AssertLogContains("MSB4210"); }); } [Fact] public void ImportFromExtensionsPathWithWildCardNothingFound() { string extnTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\non-existant\*.proj'/> </Project> "; string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {Path.Combine("tmp", "nonexistent"), extnDir1}, null, (p, l) => Assert.True(p.Build())); } [Fact] public void ImportFromExtensionsPathInvalidFile() { string extnTargetsFileContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistent"))); var logger = new MockLogger(); projColln.RegisterLogger(logger); Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath)); logger.AssertLogContains("MSB4024"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } } } [Fact] public void ImportFromExtensionsPathSearchOrder() { string extnTargetsFileContent1 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromFirstFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromSecondFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; // File with the same name available in two different extension paths, but the one from the first // directory in MSBuildExtensionsPath environment variable should get loaded string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] {extnDir2, Path.Combine("tmp", "nonexistent"), extnDir1}, null, (p, l) => { Assert.True(p.Build()); l.AssertLogContains("Running FromExtn"); l.AssertLogContains("PropertyFromExtn1: FromSecondFile"); }); } [Fact] public void ImportFromExtensionsPathSearchOrder2() { string extnTargetsFileContent1 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromFirstFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FromSecondFile</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project> "; // File with the same name available in two different extension paths, but the one from the first // directory in MSBuildExtensionsPath environment variable should get loaded string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1); string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2); string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); // MSBuildExtensionsPath* property value has highest priority for the lookups try { var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existent"), extnDir1)); var logger = new MockLogger(); projColln.RegisterLogger(logger); var project = projColln.LoadProject(mainProjectPath); project.SetProperty("MSBuildExtensionsPath", extnDir2); project.ReevaluateIfNecessary(); Assert.True(project.Build()); logger.AssertLogContains("Running FromExtn"); logger.AssertLogContains("PropertyFromExtn1: FromSecondFile"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } if (extnDir2 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true); } } } [Fact] public void ImportOrderFromExtensionsPath32() { CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath32", (p, l) => Assert.True(p.Build())); } [Fact] public void ImportOrderFromExtensionsPath64() { CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath64", (p, l) => Assert.True(p.Build())); } // Use MSBuildExtensionsPath, MSBuildExtensionsPath32 and MSBuildExtensionsPath64 in the build [Fact] public void ImportFromExtensionsPathAnd32And64() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn{0}' DependsOnTargets='{1}'> <Message Text='Running FromExtn{0}'/> </Target> {2} </Project> "; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value=""" + /*v4Folder*/"." + @"""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""{0}"" /> <property name=""MSBuildExtensionsPath32"" value=""{1}"" /> <property name=""MSBuildExtensionsPath64"" value=""{2}"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null, extnDir2 = null, extnDir3 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />")); extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"), String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />")); extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"), String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty)); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3)); var reader = GetStandardConfigurationReader(); var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(reader); var logger = new MockLogger(); projColln.RegisterLogger(logger); var project = projColln.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn3"); logger.AssertLogContains("Running FromExtn2"); logger.AssertLogContains("Running FromExtn"); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } if (extnDir2 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true); } if (extnDir3 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true); } } } // Fall-back path that has a property in it: $(FallbackExpandDir1) [Fact] public void ExpandExtensionsPathFallback() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\\foo\\extn.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" /> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> {["FallbackExpandDir1"] = extnDir1}); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); var project = projectCollection.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } } // Fall-back path that has a property in it: $(FallbackExpandDir1) [Fact] public void ExpandExtensionsPathFallbackInErrorMessage() { string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" /> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent()); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath)); // Expanded $(FallbackExpandDir) will appear in quotes in the log logger.AssertLogContains("\"" + extnDir1 + "\""); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } } // Fall-back search path with custom variable [Fact] public void FallbackImportWithIndirectReference() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <VSToolsPath>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v99</VSToolsPath> </PropertyGroup> <Import Project='$(VSToolsPath)\DNX\Microsoft.DNX.Props' Condition=""Exists('$(VSToolsPath)\DNX\Microsoft.DNX.Props')"" /> <Target Name='Main' DependsOnTargets='FromExtn' /> </Project>"; string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" /> <property name=""VSToolsPath"" value=""$(FallbackExpandDir1)\Microsoft\VisualStudio\v99"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("Microsoft", "VisualStudio", "v99", "DNX", "Microsoft.DNX.Props"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); var project = projectCollection.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } } // Fall-back search path on a property that is not defined. [Fact] public void FallbackImportWithUndefinedProperty() { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" /> <Target Name='Main' DependsOnTargets='FromExtn' /> </Project>"; string extnTargetsFileContentTemplate = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> </Project>"; var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; string extnDir1 = null; string mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"), extnTargetsFileContentTemplate); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); var project = projectCollection.LoadProject(mainProjectPath); Assert.True(project.Build("Main")); logger.AssertLogContains("Running FromExtn"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } } [Fact] public void FallbackImportWithFileNotFoundWhenPropertyNotDefined() { // Import something from $(UndefinedProperty) string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Import Project='$(UndefinedProperty)\filenotfound.props' /> <Target Name='Main' DependsOnTargets='FromExtn' /> </Project>"; string extnDir1 = null; string mainProjectPath = null; try { // The path to "extensions1" fallback should exist, but the file doesn't need to extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"), string.Empty); // Implement fallback for UndefinedProperty, but don't define the property. var configFileContents = @" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value="".""/> <property name=""MSBuildBinPath"" value="".""/> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""UndefinedProperty"" value=""" + extnDir1 + @""" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"; mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent); ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents); var reader = GetStandardConfigurationReader(); var projectCollection = new ProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 }); projectCollection.ResetToolsetsForTests(reader); var logger = new MockLogger(); projectCollection.RegisterLogger(logger); Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath)); logger.AssertLogContains(@"MSB4226: The imported project """ + Path.Combine("$(UndefinedProperty)", "filenotfound.props") + @""" was not found. Also, tried to find"); } finally { FileUtilities.DeleteNoThrow(mainProjectPath); FileUtilities.DeleteDirectoryNoThrow(extnDir1, true); } } void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyName, Action<Project, MockLogger> action) { string extnDir1 = null, extnDir2 = null, mainProjectPath = null; try { extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1(extnPathPropertyName)); extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"), GetExtensionTargetsFileContent2(extnPathPropertyName)); mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent(extnPathPropertyName)); CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, extnPathPropertyName, new string[] {extnDir1, extnDir2}, null, action); } finally { if (extnDir1 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true); } if (extnDir2 != null) { FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true); } if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } } } void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action<string[]> setExtensionsPath, Action<Project, MockLogger> action) { try { var projColln = new ProjectCollection(); projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader(extnPathPropertyName, extnDirs)); var logger = new MockLogger(); projColln.RegisterLogger(logger); var project = projColln.LoadProject(mainProjectPath); action(project, logger); } finally { if (mainProjectPath != null) { FileUtilities.DeleteNoThrow(mainProjectPath); } if (extnDirs != null) { foreach (var extnDir in extnDirs) { FileUtilities.DeleteDirectoryNoThrow(extnDir, recursive: true); } } } } private ToolsetConfigurationReader WriteConfigFileAndGetReader(string extnPathPropertyName, params string[] extnDirs) { string combinedExtnDirs = extnDirs != null ? String.Join(";", extnDirs) : String.Empty; ToolsetConfigurationReaderTestHelper.WriteConfigFile(@" <configuration> <configSections> <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" /> </configSections> <msbuildToolsets default=""" + toolsVersionToUse + @"""> <toolset toolsVersion=""" + toolsVersionToUse + @"""> <property name=""MSBuildToolsPath"" value=""."" /> <property name=""MSBuildBinPath"" value=""."" /> <projectImportSearchPaths> <searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @"""> <property name=""" + extnPathPropertyName + @""" value=""" + combinedExtnDirs + @""" /> </searchPaths> </projectImportSearchPaths> </toolset> </msbuildToolsets> </configuration>"); return GetStandardConfigurationReader(); } string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFilePath, string fileContents) { var extnDir = Path.Combine(ObjectModelHelpers.TempProjectDir, extnDirName); Directory.CreateDirectory(Path.Combine(extnDir, Path.GetDirectoryName(relativeFilePath))); File.WriteAllText(Path.Combine(extnDir, relativeFilePath), fileContents); return extnDir; } string GetMainTargetFileContent(string extensionsPathPropertyName="MSBuildExtensionsPath") { string mainTargetsFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='Main' DependsOnTargets='FromExtn'> <Message Text='PropertyFromExtn1: $(PropertyFromExtn1)'/> </Target> <Import Project='$({0})\foo\extn.proj'/> </Project>"; return String.Format(mainTargetsFileContent, extensionsPathPropertyName); } string GetExtensionTargetsFileContent1(string extensionsPathPropertyName="MSBuildExtensionsPath") { string extnTargetsFileContent1 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn1>FooBar</PropertyFromExtn1> </PropertyGroup> <Target Name='FromExtn'> <Message Text='Running FromExtn'/> </Target> <Import Project='$({0})\bar\extn2.proj'/> </Project> "; return String.Format(extnTargetsFileContent1, extensionsPathPropertyName); } string GetExtensionTargetsFileContent2(string extensionsPathPropertyName="MSBuildExtensionsPath") { string extnTargetsFileContent2 = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <PropertyGroup> <PropertyFromExtn2>Abc</PropertyFromExtn2> </PropertyGroup> <Target Name='FromExtn2'> <Message Text='Running FromExtn2'/> </Target> </Project> "; return extnTargetsFileContent2; } private ToolsetConfigurationReader GetStandardConfigurationReader() { return new ToolsetConfigurationReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest); } } } #endif
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using MLifter.DAL; using MLifter.DAL.Interfaces; namespace MLifter.Controls { public partial class TextStyleEdit : UserControl { private bool actualizing = false; private ITextStyle style; public ITextStyle Style { get { return style; } set { style = value; LoadStyle(); } } public event EventHandler Changed; protected virtual void OnChanged(EventArgs e) { if (Changed != null) Changed(this, e); } private Dictionary<FontFamily, FontFamilyContainer> families = new Dictionary<FontFamily, FontFamilyContainer>(); public TextStyleEdit() { InitializeComponent(); tableOtherElements.HeaderRenderer = new XPTable.Renderers.GradientHeaderRenderer(); //manually localized resource strings tableOtherElements.NoItemsText = Properties.Resources.STYLEEDIT_NOITEMSTEXT; buttonColumnDelete.ToolTipText = Properties.Resources.STYLEEDIT_TOOLTIP_DELETE; textColumnName.Text = Properties.Resources.STYLEEDIT_COLUMN_STYLENAME; textColumnValue.Text = Properties.Resources.STYLEEDIT_COLUMN_STYLEVALUE; foreach (FontFamily family in FontFamily.Families) { families.Add(family, new FontFamilyContainer(family)); comboBoxFontFamily.Items.Add(families[family]); } comboBoxFontSizeUnit.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, FontSizeUnit.Pixel)); comboBoxFontSizeUnit.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, FontSizeUnit.Percent)); comboBoxHAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, MLifter.DAL.Interfaces.HorizontalAlignment.None)); comboBoxHAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, MLifter.DAL.Interfaces.HorizontalAlignment.Left)); comboBoxHAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, MLifter.DAL.Interfaces.HorizontalAlignment.Center)); comboBoxHAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, MLifter.DAL.Interfaces.HorizontalAlignment.Right)); comboBoxVAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, VerticalAlignment.None)); comboBoxVAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, VerticalAlignment.Top)); comboBoxVAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, VerticalAlignment.Middle)); comboBoxVAlign.Items.Add(new EnumLocalizer(Properties.Resources.ResourceManager, VerticalAlignment.Bottom)); } /// <summary> /// Loads the style. /// </summary> /// <remarks>Documented by Dev05, 2007-10-31</remarks> private void LoadStyle() { if (style == null) return; actualizing = true; comboBoxColorPickerBack.Color = style.BackgroundColor != Color.Empty ? style.BackgroundColor : Color.White; comboBoxColorPickerFore.Color = style.ForeColor != Color.Empty ? style.ForeColor : Color.White; if (style.FontFamily != null) comboBoxFontFamily.SelectedItem = families[style.FontFamily]; else comboBoxFontFamily.SelectedIndex = 0; checkBoxFontStyleNone.Checked = style.FontStyle == CSSFontStyle.None; checkBoxFontStyleRegular.Checked = (style.FontStyle & CSSFontStyle.Regular) == CSSFontStyle.Regular; checkBoxFontStyleBold.Checked = (style.FontStyle & CSSFontStyle.Bold) == CSSFontStyle.Bold; checkBoxFontStyleItalic.Checked = (style.FontStyle & CSSFontStyle.Italic) == CSSFontStyle.Italic; checkBoxFontStyleStrikeout.Checked = (style.FontStyle & CSSFontStyle.Strikeout) == CSSFontStyle.Strikeout; checkBoxFontStyleUnderline.Checked = (style.FontStyle & CSSFontStyle.Underline) == CSSFontStyle.Underline; EnumLocalizer.SelectItem(comboBoxFontSizeUnit, style.FontSizeUnit); numericUpDownFontSize.Value = (style.FontSize == 0) ? 12 : style.FontSize; EnumLocalizer.SelectItem(comboBoxHAlign, style.HorizontalAlign); EnumLocalizer.SelectItem(comboBoxVAlign, style.VerticalAlign); checkBoxBackColor.Checked = style.BackgroundColor.Name != "Empty" && style.BackgroundColor.Name != "0"; checkBoxFontFamily.Checked = style.FontFamily != null; checkBoxFontSize.Checked = style.FontSize > 0; checkBoxForeColor.Checked = style.ForeColor.Name != "Empty" && style.ForeColor.Name != "0"; checkBoxHAlign.Checked = style.HorizontalAlign != MLifter.DAL.Interfaces.HorizontalAlignment.None; checkBoxVAlign.Checked = style.VerticalAlign != VerticalAlignment.None; foreach (KeyValuePair<string, string> pair in style.OtherElements) { XPTable.Models.Row row = new XPTable.Models.Row(); tableOtherElements.TableModel.Rows.Add(row); row.Cells.Add(new XPTable.Models.Cell("x")); row.Cells.Add(new XPTable.Models.Cell(pair.Key)); row.Cells.Add(new XPTable.Models.Cell(pair.Value)); } AddEmtyRow(); EnableControls(); actualizing = false; } /// <summary> /// Adds the emty row. /// </summary> /// <remarks>Documented by Dev05, 2007-11-02</remarks> private void AddEmtyRow() { List<XPTable.Models.Row> rowsToDelete = new List<XPTable.Models.Row>(); foreach (XPTable.Models.Row rowToCheck in tableOtherElements.TableModel.Rows) { if (rowToCheck.Cells[1].Text.Length == 0 && rowToCheck.Cells[2].Text.Length == 0) rowsToDelete.Add(rowToCheck); } foreach (XPTable.Models.Row rowToDelete in rowsToDelete) tableOtherElements.TableModel.Rows.Remove(rowToDelete); XPTable.Models.Row row = new XPTable.Models.Row(); tableOtherElements.TableModel.Rows.Add(row); row.Cells.Add(new XPTable.Models.Cell("x")); row.Cells.Add(new XPTable.Models.Cell("")); row.Cells.Add(new XPTable.Models.Cell("")); } /// <summary> /// Values the changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2007-10-31</remarks> private void ValueChanged(object sender, EventArgs e) { if (!actualizing) Actualize(sender); } /// <summary> /// Actualizes this instance. /// </summary> /// <param name="sender">The sender.</param> /// <remarks>Documented by Dev05, 2007-10-31</remarks> private void Actualize(object sender) { actualizing = true; EnableControls(); AddEmtyRow(); style.OtherElements.Clear(); foreach (XPTable.Models.Row rowToCheck in tableOtherElements.TableModel.Rows) { rowToCheck.Cells[1].Text = rowToCheck.Cells[1].Text.Trim(); if (rowToCheck.Cells[1].Text.Length != 0 && rowToCheck.Cells[2].Text.Length != 0) { if (style.OtherElements.ContainsKey(rowToCheck.Cells[1].Text)) style.OtherElements[rowToCheck.Cells[1].Text] = rowToCheck.Cells[2].Text; else style.OtherElements.Add(rowToCheck.Cells[1].Text, rowToCheck.Cells[2].Text); } } //if (!checkBoxFontStyleNone.Checked && !checkBoxFontStyleStrikeout.Checked && !checkBoxFontStyleUnderline.Checked) // checkBoxFontStyleRegular.Checked = true; //else // checkBoxFontStyleRegular.Checked = false; if (checkBoxForeColor.Checked) style.ForeColor = comboBoxColorPickerFore.Color; else style.ForeColor = Color.Empty; if (checkBoxBackColor.Checked) style.BackgroundColor = comboBoxColorPickerBack.Color; else style.BackgroundColor = Color.Empty; if (checkBoxFontFamily.Checked) style.FontFamily = (comboBoxFontFamily.SelectedItem as FontFamilyContainer).FontFamily; else style.FontFamily = null; if (checkBoxFontStyleNone.Checked) style.FontStyle = CSSFontStyle.None; else { if (sender.Equals(checkBoxFontStyleRegular) && ((CheckBox)sender).Checked) { checkBoxFontStyleUnderline.Checked = false; checkBoxFontStyleStrikeout.Checked = false; } if ((sender.Equals(checkBoxFontStyleUnderline) || sender.Equals(checkBoxFontStyleStrikeout)) && ((CheckBox)sender).Checked) { if (sender.Equals(checkBoxFontStyleStrikeout) && ((CheckBox)sender).Checked) checkBoxFontStyleUnderline.Checked = false; if (sender.Equals(checkBoxFontStyleUnderline) && ((CheckBox)sender).Checked) checkBoxFontStyleStrikeout.Checked = false; checkBoxFontStyleRegular.Checked = false; } if (checkBoxFontStyleRegular.Checked) { style.FontStyle = CSSFontStyle.Regular; } else { if (checkBoxFontStyleUnderline.Checked) style.FontStyle = CSSFontStyle.Underline; else if (checkBoxFontStyleStrikeout.Checked) style.FontStyle = CSSFontStyle.Strikeout; } if (checkBoxFontStyleBold.Checked) style.FontStyle |= CSSFontStyle.Bold; if (checkBoxFontStyleItalic.Checked) style.FontStyle |= CSSFontStyle.Italic; } if (checkBoxFontSize.Checked) style.FontSize = (int)numericUpDownFontSize.Value; else style.FontSize = 0; style.FontSizeUnit = (FontSizeUnit)((EnumLocalizer)comboBoxFontSizeUnit.SelectedItem).value; if (checkBoxHAlign.Checked) style.HorizontalAlign = (MLifter.DAL.Interfaces.HorizontalAlignment)((EnumLocalizer)comboBoxHAlign.SelectedItem).value; else style.HorizontalAlign = MLifter.DAL.Interfaces.HorizontalAlignment.None; if (checkBoxVAlign.Checked) style.VerticalAlign = (VerticalAlignment)((EnumLocalizer)comboBoxVAlign.SelectedItem).value; else style.VerticalAlign = VerticalAlignment.None; OnChanged(EventArgs.Empty); actualizing = false; } /// <summary> /// Enables the controls. /// </summary> /// <remarks>Documented by Dev05, 2007-10-31</remarks> private void EnableControls() { comboBoxColorPickerBack.Enabled = checkBoxBackColor.Checked; comboBoxColorPickerFore.Enabled = checkBoxForeColor.Checked; comboBoxFontFamily.Enabled = checkBoxFontFamily.Checked; comboBoxFontSizeUnit.Enabled = checkBoxFontSize.Checked; comboBoxHAlign.Enabled = checkBoxHAlign.Checked; comboBoxVAlign.Enabled = checkBoxVAlign.Checked; numericUpDownFontSize.Enabled = checkBoxFontSize.Checked; checkBoxFontStyleRegular.Enabled = !checkBoxFontStyleNone.Checked; checkBoxFontStyleBold.Enabled = !checkBoxFontStyleNone.Checked; checkBoxFontStyleItalic.Enabled = !checkBoxFontStyleNone.Checked; checkBoxFontStyleStrikeout.Enabled = !checkBoxFontStyleNone.Checked; checkBoxFontStyleUnderline.Enabled = !checkBoxFontStyleNone.Checked; } /// <summary> /// Handles the CellButtonClicked event of the tableOtherElements control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="XPTable.Events.CellButtonEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2007-11-02</remarks> private void tableOtherElements_CellButtonClicked(object sender, XPTable.Events.CellButtonEventArgs e) { tableOtherElements.TableModel.Rows.RemoveAt(e.Cell.Row.Index); if (!actualizing) Actualize(sender); } /// <summary> /// Handles the CellPropertyChanged event of the tableOtherElements control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="XPTable.Events.CellEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2007-11-02</remarks> private void tableOtherElements_CellPropertyChanged(object sender, XPTable.Events.CellEventArgs e) { if (!actualizing) Actualize(sender); } } public class FontFamilyContainer { public FontFamily FontFamily; public FontFamilyContainer(FontFamily family) { FontFamily = family; } public override string ToString() { return FontFamily.Name; } } }
#region Apache Notice /***************************************************************************** * $Revision: 405046 $ * $LastChangedDate: 2006-05-08 15:21:44 +0200 (lun., 08 mai 2006) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Text; using IBatisNet.Common.Utilities.Objects.Members; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.Configuration.Sql.Dynamic.Elements; using IBatisNet.Common.Utilities.Objects; namespace IBatisNet.DataMapper.Configuration.Sql.Dynamic.Handlers { /// <summary> /// ConditionalTagHandler. /// </summary> public abstract class ConditionalTagHandler : BaseTagHandler { #region Const /// <summary> /// /// </summary> public const long NOT_COMPARABLE = long.MinValue; #endregion /// <summary> /// Initializes a new instance of the <see cref="ConditionalTagHandler"/> class. /// </summary> /// <param name="accessorFactory">The accessor factory.</param> public ConditionalTagHandler(AccessorFactory accessorFactory) : base(accessorFactory) { } #region Methods /// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="tag"></param> /// <param name="parameterObject"></param> /// <returns></returns> public abstract bool IsCondition(SqlTagContext ctx, SqlTag tag, object parameterObject); /// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="tag"></param> /// <param name="parameterObject"></param> /// <returns></returns> public override int DoStartFragment(SqlTagContext ctx, SqlTag tag, Object parameterObject) { if (IsCondition(ctx, tag, parameterObject)) { return BaseTagHandler.INCLUDE_BODY; } else { return BaseTagHandler.SKIP_BODY; } } /// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="tag"></param> /// <param name="parameterObject"></param> /// <param name="bodyContent"></param> /// <returns></returns> public override int DoEndFragment(SqlTagContext ctx, SqlTag tag, Object parameterObject, StringBuilder bodyContent) { return BaseTagHandler.INCLUDE_BODY; } /// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="sqlTag"></param> /// <param name="parameterObject"></param> /// <returns></returns> protected long Compare(SqlTagContext ctx, SqlTag sqlTag, object parameterObject) { Conditional tag = (Conditional)sqlTag; string propertyName = tag.Property; string comparePropertyName = tag.CompareProperty; string compareValue = tag.CompareValue; object value1 = null; Type type = null; if (propertyName != null && propertyName.Length > 0) { value1 = ObjectProbe.GetMemberValue(parameterObject, propertyName, this.AccessorFactory); type = value1.GetType(); } else { value1 = parameterObject; if (value1 != null) { type = parameterObject.GetType(); } else { type = typeof(object); } } if (comparePropertyName != null && comparePropertyName.Length > 0) { object value2 = ObjectProbe.GetMemberValue(parameterObject, comparePropertyName, this.AccessorFactory); return CompareValues(type, value1, value2); } else if (compareValue != null && compareValue != "") { return CompareValues(type, value1, compareValue); } else { throw new DataMapperException("Error comparing in conditional fragment. Uknown 'compare to' values."); } } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="value1"></param> /// <param name="value2"></param> /// <returns></returns> protected long CompareValues(Type type, object value1, object value2) { long result = NOT_COMPARABLE; if (value1 == null || value2 == null) { result = value1 == value2 ? 0 : NOT_COMPARABLE; } else { if (value2.GetType() != type) { value2 = ConvertValue(type, value2.ToString()); } if (value2 is string && type != typeof(string)) { value1 = value1.ToString(); } if (!(value1 is IComparable && value2 is IComparable)) { value1 = value1.ToString(); value2 = value2.ToString(); } result = ((IComparable)value1).CompareTo(value2); } return result; } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> protected object ConvertValue(Type type, string value) { if (type == typeof(String)) { return value; } else if (type == typeof(bool)) { return System.Convert.ToBoolean(value); } else if (type == typeof(Byte)) { return System.Convert.ToByte(value); } else if (type == typeof(Char)) { return System.Convert.ToChar(value.Substring(0, 1));//new Character(value.charAt(0)); } else if (type == typeof(DateTime)) { try { return System.Convert.ToDateTime(value); } catch (Exception e) { throw new DataMapperException("Error parsing date. Cause: " + e.Message, e); } } else if (type == typeof(Decimal)) { return System.Convert.ToDecimal(value); } else if (type == typeof(Double)) { return System.Convert.ToDouble(value); } else if (type == typeof(Int16)) { return System.Convert.ToInt16(value); } else if (type == typeof(Int32)) { return System.Convert.ToInt32(value); } else if (type == typeof(Int64)) { return System.Convert.ToInt64(value); } else if (type == typeof(Single)) { return System.Convert.ToSingle(value); } else { return value; } } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.Lync { public partial class LyncAddLyncUserPlan { /// <summary> /// asyncTasks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks; /// <summary> /// Image1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image Image1; /// <summary> /// locTitle control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTitle; /// <summary> /// messageBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox; /// <summary> /// secPlan control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlan; /// <summary> /// Plan control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel Plan; /// <summary> /// txtPlan control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPlan; /// <summary> /// valRequirePlan control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequirePlan; /// <summary> /// secPlanFeatures control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeatures; /// <summary> /// PlanFeatures control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PlanFeatures; /// <summary> /// chkIM control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkIM; /// <summary> /// chkMobility control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkMobility; /// <summary> /// chkConferencing control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkConferencing; /// <summary> /// chkEnterpriseVoice control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkEnterpriseVoice; /// <summary> /// secPlanFeaturesFederation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesFederation; /// <summary> /// PlanFeaturesFederation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PlanFeaturesFederation; /// <summary> /// chkFederation control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkFederation; /// <summary> /// chkRemoteUserAccess control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkRemoteUserAccess; /// <summary> /// secPlanFeaturesArchiving control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesArchiving; /// <summary> /// PlanFeaturesArchiving control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PlanFeaturesArchiving; /// <summary> /// locArchivingPolicy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locArchivingPolicy; /// <summary> /// ddArchivingPolicy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddArchivingPolicy; /// <summary> /// secPlanFeaturesMeeting control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesMeeting; /// <summary> /// PlanFeaturesMeeting control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PlanFeaturesMeeting; /// <summary> /// chkAllowOrganizeMeetingsWithExternalAnonymous control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox chkAllowOrganizeMeetingsWithExternalAnonymous; /// <summary> /// secPlanFeaturesTelephony control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secPlanFeaturesTelephony; /// <summary> /// PlanFeaturesTelephony control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel PlanFeaturesTelephony; /// <summary> /// locTelephony control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTelephony; /// <summary> /// ddTelephony control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddTelephony; /// <summary> /// pnEnterpriseVoice control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnEnterpriseVoice; /// <summary> /// locTelephonyProvider control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTelephonyProvider; /// <summary> /// tbTelephoneProvider control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbTelephoneProvider; /// <summary> /// btnAccept control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnAccept; /// <summary> /// AcceptRequiredValidator control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator AcceptRequiredValidator; /// <summary> /// locDialPlan control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locDialPlan; /// <summary> /// ddTelephonyDialPlanPolicy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddTelephonyDialPlanPolicy; /// <summary> /// locVoicePolicy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locVoicePolicy; /// <summary> /// ddTelephonyVoicePolicy control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddTelephonyVoicePolicy; /// <summary> /// pnServerURI control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnServerURI; /// <summary> /// locServerURI control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locServerURI; /// <summary> /// tbServerURI control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbServerURI; /// <summary> /// btnAdd control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnAdd; /// <summary> /// ValidationSummary1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Printing; namespace Factotum { public partial class InspectedComponentView : Form { // ---------------------------------------------------------------------- // Initialization // ---------------------------------------------------------------------- EOutage curOutage; EInspectorCollection reviewers; // Form constructor public InspectedComponentView(Guid outageID) { curOutage = new EOutage(outageID); InitializeComponent(); // Take care of settings that are not as easily managed in the designer. InitializeControls(); } // Take care of the non-default DataGridView settings that are not as easily managed // in the designer. private void InitializeControls() { // Set these combos to their defaults cboHasMin.SelectedIndex = (int)FilterYesNoAll.ShowAll; cboSubmitted.SelectedIndex = (int)FilterYesNoAll.ShowAll; cboFinal.SelectedIndex = (int)FilterYesNoAll.ShowAll; cboUtFieldCplt.SelectedIndex = (int)FilterYesNoAll.ShowAll; cboPrepComplete.SelectedIndex = (int)FilterYesNoAll.ShowAll; cboStatusComplete.SelectedIndex = (int)FilterYesNoAll.ShowAll; reviewers = EInspector.ListForOutage((Guid)curOutage.ID, false, true); reviewers[0].InspectorName = "All"; cboReviewer.DataSource = reviewers; cboReviewer.DisplayMember = "InspectorName"; cboReviewer.ValueMember = "ID"; cboReviewer.SelectedIndex = 0; } private void UpdateReviewersComboSource() { Guid? curReviewerID = null; if (cboReviewer.SelectedValue != null) curReviewerID = (Guid)cboReviewer.SelectedValue; reviewers = EInspector.ListForOutage((Guid)curOutage.ID, false, true); reviewers[0].InspectorName = "All"; cboReviewer.DataSource = reviewers; cboReviewer.DisplayMember = "InspectorName"; cboReviewer.ValueMember = "ID"; if (curReviewerID != null) cboReviewer.SelectedValue = curReviewerID; else cboReviewer.SelectedIndex = 0; } // Set the status filter to show active tools by default // and update the tool selector combo box private void InspectedComponentView_Load(object sender, EventArgs e) { // Apply the current filters and set the selector row. // Passing a null selects the first row if there are any rows. UpdateSelector(null); // Now that we have some rows and columns, we can do some customization. CustomizeGrid(); // Need to do this because the customization clears the row selection. SelectGridRow(null); // We don't want these to get triggered except by the user this.cboHasMin.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.txtComponentID.TextChanged += new System.EventHandler(HandleApplyFilters); this.txtReportID.TextChanged += new System.EventHandler(HandleApplyFilters); this.cboUtFieldCplt.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.cboReviewer.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.cboSubmitted.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.cboFinal.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.cboPrepComplete.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); this.cboStatusComplete.SelectedIndexChanged += new System.EventHandler(HandleApplyFilters); EInspectedComponent.Changed += new EventHandler<EntityChangedEventArgs>(EInspectedComponent_Changed); EInspector.InspectorOutageAssignmentsChanged += new EventHandler(EInspector_InspectorOutageAssignmentsChanged); } private void InspectedComponentView_FormClosed(object sender, FormClosedEventArgs e) { EInspectedComponent.Changed -= new EventHandler<EntityChangedEventArgs>(EInspectedComponent_Changed); EInspector.InspectorOutageAssignmentsChanged -= new EventHandler(EInspector_InspectorOutageAssignmentsChanged); } // ---------------------------------------------------------------------- // Event Handlers // ---------------------------------------------------------------------- void EInspector_InspectorOutageAssignmentsChanged(object sender, EventArgs e) { UpdateReviewersComboSource(); } void EInspectedComponent_Changed(object sender, EntityChangedEventArgs e) { UpdateSelector(e.ID); } // Handle the user's decision to edit the current tool private void EditCurrentSelection() { // Make sure there's a row selected if (dgvReportList.SelectedRows.Count != 1) return; Guid? currentEditItem = (Guid?)(dgvReportList.SelectedRows[0].Cells["ID"].Value); // First check to see if an instance of the form set to the selected ID already exists if (!Globals.CanActivateForm(this, "InspectedComponentEdit", currentEditItem)) { // Open the edit form with the currently selected ID. InspectedComponentEdit frm = new InspectedComponentEdit(currentEditItem); frm.MdiParent = this.MdiParent; frm.Show(); } } private void btnValidate_Click(object sender, EventArgs e) { ShowValidator(); } private void ShowValidator() { Form frm; // Make sure there's a row selected if (dgvReportList.SelectedRows.Count != 1) return; Guid? currentEditItem = (Guid?)(dgvReportList.SelectedRows[0].Cells["ID"].Value); // First check to see if an instance of the form set to the selected ID already exists if (!Globals.CanActivateForm(this, "ReportValidator", currentEditItem, out frm)) { // Open the form with the currently selected ID. frm = new ReportValidator((Guid)currentEditItem); frm.MdiParent = this.MdiParent; frm.Show(); } else { ((ReportValidator)frm).DoValidation(); } } // This handles the datagridview double-click as well as button click void btnEdit_Click(object sender, System.EventArgs e) { EditCurrentSelection(); } private void dgvReportList_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) EditCurrentSelection(); } // Handle the user's decision to add a new tool private void btnAdd_Click(object sender, EventArgs e) { InspectedComponentEdit frm = new InspectedComponentEdit(null, curOutage.ID); frm.MdiParent = this.MdiParent; frm.Show(); } // Handle the user's decision to delete the selected tool private void btnDelete_Click(object sender, EventArgs e) { if (dgvReportList.SelectedRows.Count != 1) { MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum"); return; } Guid? currentEditItem = (Guid?)(dgvReportList.SelectedRows[0].Cells["ID"].Value); if (Globals.IsFormOpen(this, "InspectedComponentEdit", currentEditItem)) { MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum"); return; } EInspectedComponent InspectedComponent = new EInspectedComponent(currentEditItem); InspectedComponent.Delete(true); if (InspectedComponent.InspComponentErrMsg != null) { MessageBox.Show(InspectedComponent.InspComponentErrMsg, "Factotum"); InspectedComponent.InspComponentErrMsg = null; } } private void HandleApplyFilters(object sender, EventArgs e) { ApplyFilters(); } private void ShowStatusReport() { StatusReport frm; frm = new StatusReport(); frm.filterReportID = txtReportID.Text; frm.filtercomponentID = txtComponentID.Text; frm.filterSubmitted = (FilterYesNoAll)cboSubmitted.SelectedIndex; frm.filterPrepComplete = (FilterYesNoAll)cboPrepComplete.SelectedIndex; frm.filterUtFieldComplete = (FilterYesNoAll)cboUtFieldCplt.SelectedIndex; frm.filterStatusComplete = (FilterYesNoAll)cboStatusComplete.SelectedIndex; frm.filterFinal = (FilterYesNoAll)cboFinal.SelectedIndex; frm.filterHasMin = (FilterYesNoAll)cboHasMin.SelectedIndex; if (cboReviewer.SelectedValue == null) frm.filterReviewer = null; else frm.filterReviewer = (Guid?)cboReviewer.SelectedValue; frm.ShowDialog(); bool updateForUtFieldComplete = false; bool updateForSubmitted = false; DialogResult test; if (frm.printedUtFieldComplete) { test = MessageBox.Show("Update the 'Completion Reported' status of 'UT field complete' reports?", "Factotum: Update 'Completion Reported' status?", MessageBoxButtons.YesNo); updateForUtFieldComplete = test == DialogResult.Yes; } if (frm.printedSubmitted) { test = MessageBox.Show("Update the 'Completion Reported' status of 'Submitted' reports?", "Factotum: Update 'Completion Reported' status?", MessageBoxButtons.YesNo); updateForSubmitted = test == DialogResult.Yes; } if (updateForUtFieldComplete || updateForSubmitted) { EInspectedComponent.UpdateCompletionReported(updateForUtFieldComplete, updateForSubmitted); } } private void btnStatusRept_Click(object sender, EventArgs e) { ShowStatusReport(); } private void btnPreview_Click(object sender, EventArgs e) { PreviewReport(); } private void PreviewReport() { if (dgvReportList.SelectedRows.Count != 1) { MessageBox.Show("Please select a Report to print first.", "Factotum"); return; } EInspectedComponent inspComponent = new EInspectedComponent((Guid?)dgvReportList.SelectedRows[0].Cells["ID"].Value); MainReport curReport = new MainReport((Guid)inspComponent.ID); curReport.Print(false); } private void PrintReport() { if (dgvReportList.SelectedRows.Count != 1) { MessageBox.Show("Please select a Report to print first.", "Factotum"); return; } EInspectedComponent inspComponent = new EInspectedComponent((Guid?)dgvReportList.SelectedRows[0].Cells["ID"].Value); MainReport curReport = new MainReport((Guid)inspComponent.ID); curReport.Print(true); } private void btnPrint_Click(object sender, EventArgs e) { PrintReport(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } // ---------------------------------------------------------------------- // Private utilities // ---------------------------------------------------------------------- // Update the tool selector combo box by filling its items based on current data and filters. // Then set the currently displayed item to that of the supplied ID. // If the supplied ID isn't on the list because of the current filter state, just show the // first item if there is one. private void UpdateSelector(Guid? id) { // Save the sort specs if there are any, so we can re-apply them SortOrder sortOrder = dgvReportList.SortOrder; int sortCol = -1; if (sortOrder != SortOrder.None) sortCol = dgvReportList.SortedColumn.Index; // Update the grid view selector DataView dv = EInspectedComponent.GetDefaultDataViewForOutage(curOutage.ID); dgvReportList.DataSource = dv; ApplyFilters(); // Re-apply the sort specs if (sortOrder == SortOrder.Ascending) dgvReportList.Sort(dgvReportList.Columns[sortCol], ListSortDirection.Ascending); else if (sortOrder == SortOrder.Descending) dgvReportList.Sort(dgvReportList.Columns[sortCol], ListSortDirection.Descending); // Select the current row SelectGridRow(id); } private void CustomizeGrid() { // Apply a default sort dgvReportList.Sort(dgvReportList.Columns["InspComponentEdsNumber"], ListSortDirection.Ascending); // Fix up the column headings dgvReportList.Columns["InspComponentEdsNumber"].HeaderText = "EDS#"; dgvReportList.Columns["InspComponentName"].HeaderText = "Report ID"; dgvReportList.Columns["InspComponentComponentName"].HeaderText = "Component ID"; dgvReportList.Columns["InspComponentWorkOrder"].HeaderText = "Work Order"; dgvReportList.Columns["InspNumberOfInspections"].HeaderText = "Inspections"; dgvReportList.Columns["InspComponentInspectorName"].HeaderText = "Reviewer"; dgvReportList.Columns["InspComponentGridProcedureName"].HeaderText = "Grid Proc."; dgvReportList.Columns["InspComponentIsReadyToInspect"].HeaderText = "Prep Cplt."; dgvReportList.Columns["InspComponentIsUtFieldComplete"].HeaderText = "UT Field Cplt."; dgvReportList.Columns["InspComponentMinCount"].HeaderText = "Mins"; dgvReportList.Columns["InspComponentIsFinal"].HeaderText = "Final"; dgvReportList.Columns["InspComponentReportSubmittedOn"].HeaderText = "Submitted"; dgvReportList.Columns["InspComponentCompletionReportedOn"].HeaderText = "Status Complete"; dgvReportList.Columns["InspComponentAreaSpecifier"].HeaderText = "Spec. Area"; dgvReportList.Columns["InspComponentPageCountOverride"].HeaderText = "Page Count Override"; // Hide some columns dgvReportList.Columns["ID"].Visible = false; dgvReportList.Columns["InspComponentInsID"].Visible = false; dgvReportList.Columns["InspComponentPageCountOverride"].Visible = false; dgvReportList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } // Apply the current filters to the DataView. The DataGridView will auto-refresh. private void ApplyFilters() { if (dgvReportList.DataSource == null) return; StringBuilder sb = new StringBuilder("", 255); if (txtReportID.Text.Length > 0) sb.Append(" And InspComponentName Like '" + txtReportID.Text + "*'"); if (txtComponentID.Text.Length > 0) sb.Append(" And InspComponentComponentName Like '" + txtComponentID.Text + "*'"); if (cboUtFieldCplt.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentIsUtFieldComplete = " + (cboUtFieldCplt.SelectedIndex == (int)FilterYesNoAll.Yes ? "'Yes'" : "'No'")); if (cboPrepComplete.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentIsReadyToInspect = " + (cboPrepComplete.SelectedIndex == (int)FilterYesNoAll.Yes ? "'Yes'" : "'No'")); if (cboSubmitted.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentReportSubmittedOn" + (cboSubmitted.SelectedIndex == (int)FilterYesNoAll.Yes ? " is not NULL" : " is NULL")); if (cboStatusComplete.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentCompletionReportedOn" + (cboStatusComplete.SelectedIndex == (int)FilterYesNoAll.Yes ? " is not NULL" : " is NULL")); if (cboFinal.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentIsFinal = " + (cboFinal.SelectedIndex == (int)FilterYesNoAll.Yes ? "'Yes'" : "'No'")); if (cboHasMin.SelectedIndex != (int)FilterYesNoAll.ShowAll) sb.Append(" And InspComponentMinCount " + (cboHasMin.SelectedIndex == (int)FilterYesNoAll.Yes ? " > 0" : " <= 0")); if ((Guid?)cboReviewer.SelectedValue != null) sb.Append(" And InspComponentInsID = '" + cboReviewer.SelectedValue + "'"); DataView dv = (DataView)dgvReportList.DataSource; dv.RowFilter = sb.Length > 5 ? sb.ToString().Substring(5) : ""; } // Select the row with the specified ID if it is currently displayed and scroll to it. // If the ID is not in the list, private void SelectGridRow(Guid? id) { bool found = false; int rows = dgvReportList.Rows.Count; if (rows == 0) return; int r = 0; DataGridViewCell firstCell = dgvReportList.FirstDisplayedCell; if (id != null && firstCell != null ) { // Find the row with the specified key id and select it. for (r = 0; r < rows; r++) { if ((Guid?)dgvReportList.Rows[r].Cells["ID"].Value == id) { dgvReportList.CurrentCell = dgvReportList[firstCell.ColumnIndex, r]; dgvReportList.Rows[r].Selected = true; found = true; break; } } } if (found) { if (!dgvReportList.Rows[r].Displayed) { // Scroll to the selected row if the ID was in the list. dgvReportList.FirstDisplayedScrollingRowIndex = r; } } else if (firstCell != null) { // Select the first item dgvReportList.CurrentCell = firstCell; dgvReportList.Rows[0].Selected = true; } } private void InspectedComponentView_SizeChanged(object sender, EventArgs e) { // There seems to be a bug where this column becomes visible when the window is restored // after minimizing, then editing a report. if (dgvReportList != null && WindowState != FormWindowState.Minimized) dgvReportList.Columns["ID"].Visible = false; } private void validateToolStripMenuItem_Click(object sender, EventArgs e) { ShowValidator(); dgvReportList.ContextMenuStrip = null; } private void componentReportPreviewToolStripMenuItem_Click(object sender, EventArgs e) { PreviewReport(); } private void printComponentReportToolStripMenuItem_Click(object sender, EventArgs e) { PrintReport(); } private void editReportToolStripMenuItem_Click(object sender, EventArgs e) { EditCurrentSelection(); } private void dgvReportList_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { DataGridView grid = sender as DataGridView; Point p; p = grid.PointToClient(Control.MousePosition); dgvReportList.Rows[e.RowIndex].Selected = true; contextMenuStrip1.Show(dgvReportList, p.X,p.Y); } } } }
// --------------------------------------------------------------------------- // Copyright (C) 2006 Microsoft Corporation All Rights Reserved // --------------------------------------------------------------------------- #define CODE_ANALYSIS using System.CodeDom; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Workflow.Activities.Common; using System.Workflow.ComponentModel.Compiler; namespace System.Workflow.Activities.Rules { #region RuleExpressionWalker public static class RuleExpressionWalker { #region IRuleExpression wrapper factories for CodeDom class CustomExpressionWrapper : RuleExpressionInternal { private IRuleExpression ruleExpr; internal CustomExpressionWrapper(IRuleExpression ruleExpr) { this.ruleExpr = ruleExpr; } internal override void AnalyzeUsage(CodeExpression expression, RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier) { ruleExpr.AnalyzeUsage(analysis, isRead, isWritten, qualifier); } internal override CodeExpression Clone(CodeExpression expression) { return ruleExpr.Clone(); } internal override void Decompile(CodeExpression expression, StringBuilder decompilation, CodeExpression parentExpression) { ruleExpr.Decompile(decompilation, parentExpression); } internal override RuleExpressionResult Evaluate(CodeExpression expression, RuleExecution execution) { return ruleExpr.Evaluate(execution); } internal override bool Match(CodeExpression leftExpression, CodeExpression rightExpression) { return ruleExpr.Match(rightExpression); } internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten) { return ruleExpr.Validate(validation, isWritten); } } class TypeWrapperTuple { internal Type codeDomType; internal RuleExpressionInternal internalExpression; internal TypeWrapperTuple(Type type, RuleExpressionInternal internalExpression) { this.codeDomType = type; this.internalExpression = internalExpression; } } static TypeWrapperTuple[] typeWrappers = new TypeWrapperTuple[] { new TypeWrapperTuple(typeof(CodeThisReferenceExpression), new ThisExpression()), new TypeWrapperTuple(typeof(CodePrimitiveExpression), new PrimitiveExpression()), new TypeWrapperTuple(typeof(CodeFieldReferenceExpression), new FieldReferenceExpression()), new TypeWrapperTuple(typeof(CodePropertyReferenceExpression), new PropertyReferenceExpression()), new TypeWrapperTuple(typeof(CodeBinaryOperatorExpression), new BinaryExpression()), new TypeWrapperTuple(typeof(CodeMethodInvokeExpression), new MethodInvokeExpression()), new TypeWrapperTuple(typeof(CodeIndexerExpression), new IndexerPropertyExpression()), new TypeWrapperTuple(typeof(CodeArrayIndexerExpression), new ArrayIndexerExpression()), new TypeWrapperTuple(typeof(CodeDirectionExpression), new DirectionExpression()), new TypeWrapperTuple(typeof(CodeTypeReferenceExpression), new TypeReferenceExpression()), new TypeWrapperTuple(typeof(CodeCastExpression), new CastExpression()), new TypeWrapperTuple(typeof(CodeObjectCreateExpression), new ObjectCreateExpression()), new TypeWrapperTuple(typeof(CodeArrayCreateExpression), new ArrayCreateExpression()) }; private static RuleExpressionInternal GetExpression(CodeExpression expression) { Type exprType = expression.GetType(); int numTypeWrappers = typeWrappers.Length; for (int i = 0; i < numTypeWrappers; ++i) { TypeWrapperTuple tuple = typeWrappers[i]; if (exprType == tuple.codeDomType) return tuple.internalExpression; } // It's not a builtin one... try a user extension expression. if (expression is IRuleExpression ruleExpr) return new CustomExpressionWrapper(ruleExpr); return null; } #endregion public static RuleExpressionInfo Validate(RuleValidation validation, CodeExpression expression, bool isWritten) { if (validation == null) throw new ArgumentNullException("validation"); // See if we've visited this node before. // Always check if written = true RuleExpressionInfo resultExprInfo = null; if (!isWritten) resultExprInfo = validation.ExpressionInfo(expression); if (resultExprInfo == null) { // First time we've seen this node. RuleExpressionInternal ruleExpr = GetExpression(expression); if (ruleExpr == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, expression.GetType().FullName); ValidationError error = new ValidationError(message, ErrorNumbers.Error_CodeExpressionNotHandled); error.UserData[RuleUserDataKeys.ErrorObject] = expression; if (validation.Errors == null) { string typeName = string.Empty; if ((validation.ThisType != null) && (validation.ThisType.Name != null)) { typeName = validation.ThisType.Name; } string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Messages.ErrorsCollectionMissing, typeName); throw new InvalidOperationException(exceptionMessage); } else { validation.Errors.Add(error); } return null; } resultExprInfo = validation.ValidateSubexpression(expression, ruleExpr, isWritten); } return resultExprInfo; } public static void AnalyzeUsage(RuleAnalysis analysis, CodeExpression expression, bool isRead, bool isWritten, RulePathQualifier qualifier) { if (analysis == null) throw new ArgumentNullException("analysis"); RuleExpressionInternal ruleExpr = GetExpression(expression); ruleExpr.AnalyzeUsage(expression, analysis, isRead, isWritten, qualifier); } public static RuleExpressionResult Evaluate(RuleExecution execution, CodeExpression expression) { if (execution == null) throw new ArgumentNullException("execution"); RuleExpressionInternal ruleExpr = GetExpression(expression); return ruleExpr.Evaluate(expression, execution); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")] public static void Decompile(StringBuilder stringBuilder, CodeExpression expression, CodeExpression parentExpression) { RuleExpressionInternal ruleExpr = GetExpression(expression); ruleExpr.Decompile(expression, stringBuilder, parentExpression); } [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public static bool Match(CodeExpression firstExpression, CodeExpression secondExpression) { // If they're both null, they match. if (firstExpression == null && secondExpression == null) return true; // If only one of them is null, there's no match. if (firstExpression == null || secondExpression == null) return false; if (firstExpression.GetType() != secondExpression.GetType()) return false; RuleExpressionInternal ruleExpr1 = GetExpression(firstExpression); return ruleExpr1.Match(firstExpression, secondExpression); } public static CodeExpression Clone(CodeExpression originalExpression) { if (originalExpression == null) return null; RuleExpressionInternal ruleExpr = GetExpression(originalExpression); CodeExpression newExpr = ruleExpr.Clone(originalExpression); ConditionHelper.CloneUserData(originalExpression, newExpr); return newExpr; } } #endregion #region CodeDomStatementWalker (internal) public static class CodeDomStatementWalker { #region RuleCodeDomStatement wrapper factories for CodeDom private delegate RuleCodeDomStatement WrapperCreator(CodeStatement statement); private static RuleCodeDomStatement GetStatement(CodeStatement statement) { Type statementType = statement.GetType(); RuleCodeDomStatement wrapper = null; if (statementType == typeof(CodeExpressionStatement)) { wrapper = ExpressionStatement.Create(statement); } else if (statementType == typeof(CodeAssignStatement)) { wrapper = AssignmentStatement.Create(statement); } else { string message = string.Format(CultureInfo.CurrentCulture, Messages.CodeStatementNotHandled, statement.GetType().FullName); NotSupportedException exception = new NotSupportedException(message); exception.Data[RuleUserDataKeys.ErrorObject] = statement; throw exception; } return wrapper; } #endregion public static bool Validate(RuleValidation validation, CodeStatement statement) { RuleCodeDomStatement ruleStmt = GetStatement(statement); return ruleStmt.Validate(validation); } internal static void Execute(RuleExecution execution, CodeStatement statement) { RuleCodeDomStatement ruleStmt = GetStatement(statement); ruleStmt.Execute(execution); } internal static void AnalyzeUsage(RuleAnalysis analysis, CodeStatement statement) { RuleCodeDomStatement ruleStmt = GetStatement(statement); ruleStmt.AnalyzeUsage(analysis); } internal static void Decompile(StringBuilder stringBuilder, CodeStatement statement) { RuleCodeDomStatement ruleStmt = GetStatement(statement); ruleStmt.Decompile(stringBuilder); } internal static bool Match(CodeStatement firstStatement, CodeStatement secondStatement) { // If they're both null, they match. if (firstStatement == null && secondStatement == null) return true; // If only one of them is null, there's no match. if (firstStatement == null || secondStatement == null) return false; if (firstStatement.GetType() != secondStatement.GetType()) return false; RuleCodeDomStatement ruleStmt = GetStatement(firstStatement); return ruleStmt.Match(secondStatement); } internal static CodeStatement Clone(CodeStatement statement) { if (statement == null) return null; RuleCodeDomStatement ruleStmt = GetStatement(statement); return ruleStmt.Clone(); } } #endregion }
using System; /// <summary> /// Nullable.Compare<T>(Nullable<T>,Nullable<T>)[v-juwa] /// </summary> public class NullableCompare { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Verify two Nullable<T> objects are null"; const string c_TEST_ID = "P001"; char? n1 = null; char? n2 = null; int expectedResult = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<char>(n1, n2); if (expectedResult != result) { string errorDesc = "Return value is not " + expectedResult + " as expected: Actual(" + result + ")"; errorDesc += " when n1 and n2 are null "; TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e+"\n n1 and n2 are null"); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Verify n1 is null and n2 has value"; const string c_TEST_ID = "P002"; int? n1 = null; int? n2 = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<int>(n1, n2); if (result>= 0) { string errorDesc = "Return value is less than zero as expected: Actual(" + result + ")"; errorDesc += " \n n1 is null "; errorDesc += "\n n2 is " + n2; TestLibrary.TestFramework.LogError("003 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004 " + "TestID_" + c_TEST_ID, "Unexpected exception: " + e + "\n n1 is null and n2 is " + n2); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Verify n1 has value and n2 is null"; const string c_TEST_ID = "P003"; int? n1 = TestLibrary.Generator.GetInt32(-55); int? n2 = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<int>(n1, n2); if (result <= 0) { string errorDesc = "Return value is less than zero as expected: Actual(" + result + ")"; errorDesc += " \n n1 is "+ n1; errorDesc += "\n n2 is null"; TestLibrary.TestFramework.LogError("005 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e + "\n n1 is "+ n1+" and n2 is null"); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Verify n1 and n2 are euqal"; const string c_TEST_ID = "P004"; char? n1 = TestLibrary.Generator.GetChar(-55); char? n2 = n1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<char>(n1, n2); if (result != 0) { string errorDesc = "Return value is not zero as expected: Actual(" + result + ")"; errorDesc += " \n n1 is " + n1; errorDesc += "\n n2 is " + n2 ; TestLibrary.TestFramework.LogError("007 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e + "\n n1 is " + n1 + " and n2 is "+n2); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Verify n1 less than n2"; const string c_TEST_ID = "P005"; Random rand = new Random(-55); int? n1 =rand.Next(Int32.MinValue,Int32.MaxValue) ; int? n2 = n1+1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<int>(n1, n2); if (result >= 0) { string errorDesc = "Return value is not less than zero as expected: Actual(" + result + ")"; errorDesc += " \n n1 is " + n1; errorDesc += "\n n2 is " + n2; TestLibrary.TestFramework.LogError("009 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e + "\n n1 is " + n1 + " and n2 is " + n2); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; const string c_TEST_DESC = "PosTest6: Verify n1 greater than n2"; const string c_TEST_ID = "P006"; Random rand = new Random(-55); int? n1 = rand.Next(Int32.MinValue+1, Int32.MaxValue); int? n2 = n1 - 1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { int result = Nullable.Compare<int>(n1, n2); if (result <= 0) { string errorDesc = "Return value is not greater than zero as expected: Actual(" + result + ")"; errorDesc += " \n n1 is " + n1; errorDesc += "\n n2 is " + n2; TestLibrary.TestFramework.LogError("011 " + "TestID_" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e + "\n n1 is " + n1 + " and n2 is " + n2); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { NullableCompare test = new NullableCompare(); TestLibrary.TestFramework.BeginTestCase("Nullable.Compare<T>(Nullable<T>,Nullable<T>)"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
namespace PokerTell.Statistics.Tests.ViewModels { using System.Linq; using Infrastructure.Enumerations.PokerHand; using Infrastructure.Interfaces; using Infrastructure.Interfaces.PokerHand; using Infrastructure.Interfaces.Statistics; using Infrastructure.Services; using Interfaces; using Moq; using NUnit.Framework; using Statistics.ViewModels; using Statistics.ViewModels.StatisticsSetDetails; using Tools.FunctionalCSharp; using UnitTests.Tools; [TestFixture] // Resharper disable InconsistentNaming internal class DetailedStatisticsAnalyzerViewModelTests { #region Constants and Fields StubBuilder _stub; IDetailedStatisticsAnalyzerViewModel _sut; IDetailedPreFlopStatisticsViewModel _preFlopStatisticsViewModelStub; IDetailedPostFlopHeroActsStatisticsViewModel _postFlopActionStatisticsViewModelStub; IDetailedPostFlopHeroReactsStatisticsViewModel _postFlopReactionStatisticsViewModelStub; Mock<IRepositoryHandBrowserViewModel> _repositoryBrowserVM_Mock; #endregion #region Public Methods [Test] public void AddViewModel_Always_SetsCurrentViewModelToAddedViewModel() { var addedViewModel = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(addedViewModel) .CurrentViewModel.ShouldBeEqualTo(addedViewModel); } [Test] public void AddViewModel_CurrentViewModelIsNotLastInHistoryList_AllViewModelsBehindItAreRemoved() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); var addedViewModel = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .CurrentViewModel = viewModel0; _sut.AddViewModel(addedViewModel) .ViewModelHistory .ShouldContain(viewModel0) .ShouldNotContain(viewModel1) .ShouldContain(addedViewModel); } [Test] public void AddViewModel_ViewModelHistoryContainsOneItem_AddsViewModelToEndOFHistoryList() { var previouslyAddedViewModel = _stub.Out<IDetailedStatisticsViewModel>(); var addedViewModel = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(previouslyAddedViewModel); _sut.AddViewModel(addedViewModel) .ViewModelHistory[1].ShouldBeEqualTo(addedViewModel); } [Test] public void AddViewModel_ViewModelHistoryListIsNull_InitializesViewModelHistoryWithViewModel() { var addedViewModel = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(addedViewModel) .ViewModelHistory[0].ShouldBeEqualTo(addedViewModel); } [Test] public void NavigateBackwardCommandCanExecute_CurrentViewModelIsFirstInViewModelHistory_ReturnsFalse() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .CurrentViewModel = viewModel0; _sut.NavigateBackwardCommand.CanExecute(null).ShouldBeFalse(); } [Test] public void NavigateBackwardCommandCanExecute_CurrentViewModelIsNotFirstInViewModelHistory_ReturnsTrue() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .NavigateBackwardCommand.CanExecute(null).ShouldBeTrue(); } [Test] public void NavigateBackwardCommandExecute_CurrentViewModelIsSecondInViewModelHistory_CurrentViewModelIsFirst() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .NavigateBackwardCommand.Execute(null); _sut.CurrentViewModel.ShouldBeEqualTo(viewModel0); } [Test] public void NavigateForwardCommandCanExecute_CurrentViewModelIsLastInViewModelHistory_ReturnsFalse() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .NavigateForwardCommand.CanExecute(null).ShouldBeFalse(); } [Test] public void NavigateForwardCommandCanExecute_CurrentViewModelIsNotLastInViewModelHistory_ReturnsTrue() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .CurrentViewModel = viewModel0; _sut.NavigateForwardCommand.CanExecute(null).ShouldBeTrue(); } [Test] public void NavigateForwardCommandExecute_CurrentViewModelIsFirstInViewModelHistory_CurrentViewModelIsSecond() { var viewModel0 = _stub.Out<IDetailedStatisticsViewModel>(); var viewModel1 = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(viewModel0) .AddViewModel(viewModel1) .CurrentViewModel = viewModel0; _sut.NavigateForwardCommand.Execute(null); _sut.CurrentViewModel.ShouldBeEqualTo(viewModel1); } [Test] public void ViewModelRaisesChildViewModelChanged_ItWasAddedLast_CurrentViewModelIsSetToChildViewModel() { var addedViewModel = new Mock<IDetailedStatisticsViewModel>(); var childViewModel = _stub.Out<IDetailedStatisticsViewModel>(); _sut.AddViewModel(addedViewModel.Object); addedViewModel.Raise(vm => vm.ChildViewModelChanged += null, childViewModel); _sut.CurrentViewModel.ShouldBeEqualTo(childViewModel); } [Test] public void Visible_ViewModelHistoryIsNull_ReturnsFalse() { _sut.Visible.ShouldBeFalse(); } [Test] public void Visible_ViewModelHistoryIsNotEmpty_ReturnsTrue() { _sut.AddViewModel(_stub.Out<IDetailedStatisticsViewModel>()) .Visible.ShouldBeTrue(); } [Test] public void InitializeWith_StreetIsPreFlop_CurrentViewModelIsDetailedPreFlopStatisticsViewModel() { var statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.PreFlop) .Out; _sut.InitializeWith(statisticsSetStub); _sut.CurrentViewModel.ShouldBeEqualTo(_preFlopStatisticsViewModelStub); } [Test] public void InitializeWith_StreetIsFlopAndActionIs_HeroActs_CurrentViewModelIsDetailedPostFlopActionStatisticsViewModel() { var statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.Flop) .Get(s => s.ActionSequence).Returns(ActionSequences.HeroActs) .Out; _sut.InitializeWith(statisticsSetStub); _sut.CurrentViewModel.ShouldBe(_postFlopActionStatisticsViewModelStub); } [Test] public void InitializeWith_StreetIsFlopAndActionIs_OppB_CurrentViewModelIsDetailedPostFlopActionStatisticsViewModel() { var statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.Flop) .Get(s => s.ActionSequence).Returns(ActionSequences.OppB) .Out; _sut.InitializeWith(statisticsSetStub); _sut.CurrentViewModel.ShouldBe(_postFlopReactionStatisticsViewModelStub); } [Test] public void InitializeWith_StreetIsFlopAndActionIs_HeroXOppB_CurrentViewModelIsDetailedPostFlopActionStatisticsViewModel() { var statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.Flop) .Get(s => s.ActionSequence).Returns(ActionSequences.HeroXOppB) .Out; _sut.InitializeWith(statisticsSetStub); _sut.CurrentViewModel.ShouldBe(_postFlopReactionStatisticsViewModelStub); } [Test] public void InitializeWith_StreetIsFlopAndActionIs_Illegal_ThrowsMatchNotFoundException() { var statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.Flop) .Get(s => s.ActionSequence).Returns(ActionSequences.OppBHeroC) .Out; Assert.Throws<MatchNotFoundException>(() => _sut.InitializeWith(statisticsSetStub)); } [Test] public void InitializeWith_Always_InitializesViewModelHistoryWithCurrentViewModel() { IActionSequenceStatisticsSet statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.PreFlop) .Out; _sut.InitializeWith(statisticsSetStub); _sut.ViewModelHistory .ShouldHaveCount(1) .First().ShouldBe(_sut.CurrentViewModel); } [Test] public void InitializeWith_StatisticsSet_InitializesNewViewModelWithStatisticsSet() { IActionSequenceStatisticsSet statisticsSetStub = _stub.Setup<IActionSequenceStatisticsSet>() .Get(s => s.Street).Returns(Streets.PreFlop) .Out; var preFlopStatisticsViewModelMock = new Mock<IDetailedPreFlopStatisticsViewModel>(); _sut = new DetailedStatisticsAnalyzerViewModel( new Constructor<IDetailedPreFlopStatisticsViewModel>(() => preFlopStatisticsViewModelMock.Object), _stub.Out<IConstructor<IDetailedPostFlopHeroActsStatisticsViewModel>>(), _stub.Out<IConstructor<IDetailedPostFlopHeroReactsStatisticsViewModel>>(), _repositoryBrowserVM_Mock.Object); _sut.InitializeWith(statisticsSetStub); preFlopStatisticsViewModelMock.Verify(vm => vm.InitializeWith(statisticsSetStub)); } [SetUp] public void _Init() { _stub = new StubBuilder(); _preFlopStatisticsViewModelStub = _stub.Out<IDetailedPreFlopStatisticsViewModel>(); _postFlopActionStatisticsViewModelStub = _stub.Out<IDetailedPostFlopHeroActsStatisticsViewModel>(); _postFlopReactionStatisticsViewModelStub = _stub.Out<IDetailedPostFlopHeroReactsStatisticsViewModel>(); _repositoryBrowserVM_Mock = new Mock<IRepositoryHandBrowserViewModel>(); _sut = new DetailedStatisticsAnalyzerViewModel( new Constructor<IDetailedPreFlopStatisticsViewModel>(() => _preFlopStatisticsViewModelStub), new Constructor<IDetailedPostFlopHeroActsStatisticsViewModel>(() => _postFlopActionStatisticsViewModelStub), new Constructor<IDetailedPostFlopHeroReactsStatisticsViewModel>(() => _postFlopReactionStatisticsViewModelStub), _repositoryBrowserVM_Mock.Object); } #endregion } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.NLogIntegration.Logging { using System; using MassTransit.Logging; using NLog; /// <summary> /// A logger that wraps to NLog. See http://stackoverflow.com/questions/7412156/how-to-retain-callsite-information-when-wrapping-nlog /// </summary> public class NLogLog : ILog { readonly NLog.Logger _log; /// <summary> /// Create a new NLog logger instance. /// </summary> /// <param name="log"></param> /// <param name="name">Name of type to log as.</param> public NLogLog(NLog.Logger log, string name) { if (name == null) throw new ArgumentNullException(nameof(name)); _log = log; } public bool IsDebugEnabled => _log.IsDebugEnabled; public bool IsInfoEnabled => _log.IsInfoEnabled; public bool IsWarnEnabled => _log.IsWarnEnabled; public bool IsErrorEnabled => _log.IsErrorEnabled; public bool IsFatalEnabled => _log.IsFatalEnabled; public void Log(MassTransit.Logging.LogLevel level, object obj) { _log.Log(GetNLogLevel(level), obj); } public void Log(MassTransit.Logging.LogLevel level, object obj, Exception exception) { _log.Log(GetNLogLevel(level), exception, obj?.ToString() ?? ""); } public void Log(MassTransit.Logging.LogLevel level, LogOutputProvider messageProvider) { _log.Log(GetNLogLevel(level), ToGenerator(messageProvider)); } public void LogFormat(MassTransit.Logging.LogLevel level, IFormatProvider formatProvider, string format, params object[] args) { _log.Log(GetNLogLevel(level), formatProvider, format, args); } public void LogFormat(MassTransit.Logging.LogLevel level, string format, params object[] args) { _log.Log(GetNLogLevel(level), format, args); } public void Debug(object obj) { _log.Log(NLog.LogLevel.Debug, obj); } public void Debug(object obj, Exception exception) { _log.Log(NLog.LogLevel.Debug, exception, obj?.ToString() ?? ""); } public void Debug(LogOutputProvider messageProvider) { _log.Debug(ToGenerator(messageProvider)); } public void Info(object obj) { _log.Log(NLog.LogLevel.Info, obj); } public void Info(object obj, Exception exception) { _log.Log(NLog.LogLevel.Info, exception, obj?.ToString() ?? ""); } public void Info(LogOutputProvider messageProvider) { _log.Info(ToGenerator(messageProvider)); } public void Warn(object obj) { _log.Log(NLog.LogLevel.Warn, obj); } public void Warn(object obj, Exception exception) { _log.Log(NLog.LogLevel.Warn, exception, obj?.ToString() ?? ""); } public void Warn(LogOutputProvider messageProvider) { _log.Warn(ToGenerator(messageProvider)); } public void Error(object obj) { _log.Log(NLog.LogLevel.Error, obj); } public void Error(object obj, Exception exception) { _log.Log(NLog.LogLevel.Error, exception, obj?.ToString() ?? ""); } public void Error(LogOutputProvider messageProvider) { _log.Error(ToGenerator(messageProvider)); } public void Fatal(object obj) { _log.Log(NLog.LogLevel.Fatal, obj); } public void Fatal(object obj, Exception exception) { _log.Log(NLog.LogLevel.Fatal, exception, obj?.ToString() ?? ""); } public void Fatal(LogOutputProvider messageProvider) { _log.Fatal(ToGenerator(messageProvider)); } public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, formatProvider, format, args); } public void DebugFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Debug, format, args); } public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Info, formatProvider, format, args); } public void InfoFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Info, format, args); } public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, formatProvider, format, args); } public void WarnFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Warn, format, args); } public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Error, formatProvider, format, args); } public void ErrorFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Error, format, args); } public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, formatProvider, format, args); } public void FatalFormat(string format, params object[] args) { _log.Log(NLog.LogLevel.Fatal, format, args); } NLog.LogLevel GetNLogLevel(MassTransit.Logging.LogLevel level) { if (level == MassTransit.Logging.LogLevel.Fatal) return NLog.LogLevel.Fatal; if (level == MassTransit.Logging.LogLevel.Error) return NLog.LogLevel.Error; if (level == MassTransit.Logging.LogLevel.Warn) return NLog.LogLevel.Warn; if (level == MassTransit.Logging.LogLevel.Info) return NLog.LogLevel.Info; if (level == MassTransit.Logging.LogLevel.Debug) return NLog.LogLevel.Debug; if (level == MassTransit.Logging.LogLevel.All) return NLog.LogLevel.Trace; return NLog.LogLevel.Off; } LogMessageGenerator ToGenerator(LogOutputProvider provider) { return () => { var obj = provider(); return obj?.ToString() ?? ""; }; } public void Shutdown() { _log.Factory.Flush(); } } }
using System; using GeneticSharp.Domain.Randomizations; using System.Linq; using System.Collections.Generic; using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Crossovers; using GeneticSharp.Domain.Mutations; using GeneticSharp.Domain.Populations; using GeneticSharp.Domain.Reinsertions; using GeneticSharp.Domain.Selections; using GeneticSharp.Infrastructure.Framework.Threading; namespace GeneticSharp.Domain { /// <summary> /// A Speecies fr use in CCE /// </summary> public sealed class CCESpecies { // This class containts everything a species needs in CCE /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name {get;set;} /// <summary> /// Gets or sets the I. /// </summary> /// <value>The I.</value> public int ID { get; set;} /// <summary> /// The offspring. /// </summary> public IList<IChromosome> Offspring; /// <summary> /// The parents /// </summary> public IList<IChromosome> Parents; private bool _debugging = false; private System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); #region Constants /// <summary> /// The default crossover probability. /// </summary> public const float DefaultCrossoverProbability = 0.75f; /// <summary> /// The default mutation probability. /// </summary> public const float DefaultMutationProbability = 0.1f; #endregion /// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.CCESpecies"/> class. /// </summary> public CCESpecies() { CrossoverProbability = DefaultCrossoverProbability; MutationProbability = DefaultMutationProbability; } /// <summary> /// Creates the new generation of children. /// </summary> public void GenerateChildren() { if (_debugging) { Console.WriteLine ("Species '{0}' generating children", Name); timer.Start (); } OrderChromosomes (); // Do the whole selection, crossover, etc Parents = SelectParents(); if (_debugging) { Console.WriteLine ("Species '{0}' selected parents. Took {1}", Name, timer.Elapsed.ToString ()); timer.Stop (); timer.Start (); } Offspring = Cross(Parents); if (_debugging) { Console.WriteLine ("Species '{0}' did crossover. Took {1}", Name, timer.Elapsed.ToString ()); timer.Stop (); timer.Start (); } Mutate(Offspring); if (_debugging) { Console.WriteLine ("Species '{0}' mutated. Took {1}", Name, timer.Elapsed.ToString ()); timer.Stop (); } if (_debugging) { Console.WriteLine ("Species '{0}' repairing.", Name); timer.Start (); } Repair (Offspring); if (_debugging) { Console.WriteLine ("Species '{0}' repaired. Took {1}", Name, timer.Elapsed); timer.Stop (); } } /// <summary> /// Ends the current generation. /// </summary> public void EndCurrentGeneration() { if (_debugging) { timer.Start (); } //var coll = Population.CurrentGeneration.Chromosomes == null ? Offspring : Population.CurrentGeneration.Chromosomes;// parents not used var coll = Offspring; // null in first round I think if (coll == null) coll = Population.CurrentGeneration.Chromosomes; if (_debugging) { if (coll == Offspring) { Console.WriteLine ("Collection is Offspring"); if (coll == null) Console.WriteLine ("IT IS NULL"); } else if (coll == Population.CurrentGeneration.Chromosomes) { Console.WriteLine ("Collection is CurrentGeneration.Chromosomes"); } Console.WriteLine ("{0} in the coll list", coll.Count); } var newGenerationChromosomes = Reinsert(coll, Parents); if (_debugging) { Console.WriteLine ("{0} new chromosomes returned from reinsertion", newGenerationChromosomes.Count); Console.WriteLine ("Species '{0}' reinserted. Took {1}", Name, timer.Elapsed.ToString ()); timer.Stop (); timer.Start (); } OrderChromosomes (); Population.EndCurrentGeneration (); Population.CreateNewGeneration(newGenerationChromosomes); if (_debugging) { Console.WriteLine ("Species '{0}' created new generation. Took {1}", Name, timer.Elapsed.ToString ()); timer.Stop (); //timer.Start (); } } /// <summary> /// Orders the chromosomes. /// </summary> public void OrderChromosomes() { Population.CurrentGeneration.Chromosomes = Population.CurrentGeneration.Chromosomes.OrderByDescending(c => c.Fitness.Value).ToList(); } /// <summary> /// Selects the parents. /// </summary> /// <returns>The parents.</returns> private IList<IChromosome> SelectParents() { if(_debugging) Console.WriteLine("Selecting parents from"); var _selection = Selection.SelectChromosomes(Population.MinSize, Population.CurrentGeneration); if (_debugging) Console.WriteLine ("Selected {0} parents", _selection.Count); return _selection; } /// <summary> /// Crosses the specified parents. /// </summary> /// <param name="parents">The parents.</param> /// <returns>The result chromosomes.</returns> private IList<IChromosome> Cross(IList<IChromosome> parents) { var offspring = new List<IChromosome>(); for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber) { var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList(); // If match the probability cross is made, otherwise the offspring is an exact copy of the parents. // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can // have some rest chromosomes. if (selectedParents.Count == Crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= CrossoverProbability) { offspring.AddRange(Crossover.Cross(selectedParents)); } } if (_debugging) { Console.WriteLine ("{0} parents created {1} children", parents.Count, offspring.Count); if (offspring.Count < parents.Count) { Console.WriteLine ("Time for debugging! This is a bp"); } } return offspring; } /// <summary> /// Mutate the specified chromosomes. /// </summary> /// <param name="chromosomes">The chromosomes.</param> private void Mutate(IList<IChromosome> chromosomes) { foreach (var c in chromosomes) { Mutation.Mutate(c, MutationProbability); } } private void Repair(IList<IChromosome> chromosomes) { foreach (var c in chromosomes) { Reparation.Repair (c); } } /// <summary> /// Reinsert the specified offspring and parents. /// </summary> /// <param name="offspring">The offspring chromosomes.</param> /// <param name="parents">The parents chromosomes.</param> /// <returns> /// The reinserted chromosomes. /// </returns> private IList<IChromosome> Reinsert(IList<IChromosome> offspring, IList<IChromosome> parents) { try{ while (offspring.Count < Population.MinSize) { offspring.Add(parents [RandomizationProvider.Current.GetInt (0, parents.Count - 1)]); // if(offspring.Count == 0) // offspring.Add(parents.First().CreateNew()); // else // offspring.Add(offspring.First().CreateNew()); } if(parents == null) parents = new List<IChromosome>(); return Reinsertion.SelectChromosomes(Population, offspring, parents); } catch { Console.WriteLine ("GET ON THE GROUND FUCKO THIS IS A BP"); return null; } } /// <summary> /// Gets the population. /// </summary> /// <value>The population.</value> public IPopulation Population { get; set; } /// <summary> /// Gets or sets the selection operator. /// </summary> public ISelection Selection { get; set; } /// <summary> /// Gets or sets the crossover operator. /// </summary> /// <value>The crossover.</value> public ICrossover Crossover { get; set; } /// <summary> /// Gets or sets the crossover probability. /// </summary> public float CrossoverProbability { get; set; } /// <summary> /// Gets or sets the mutation operator. /// </summary> public IMutation Mutation { get; set; } /// <summary> /// Gets or sets the mutation probability. /// </summary> public float MutationProbability { get; set; } /// <summary> /// Gets or sets the reinsertion operator. /// </summary> public IReinsertion Reinsertion { get; set; } /// <summary> /// Gets or sets the reparation. /// </summary> /// <value>The reparation.</value> public IReparation Reparation { get; set; } /// <summary> /// Gets the best chromosome. /// </summary> /// <value>The best chromosome.</value> public IChromosome BestChromosome { get { return Population.BestChromosome; } } } }
namespace FluentLinqToSql.Tests.ActiveRecord { using System; using System.Collections.Generic; using System.Collections.Specialized; using FluentLinqToSql.ActiveRecord; using NUnit.Framework; //From MvcContrib http://mvccontrib.org [TestFixture] public class NameValueDeserializerTester { private NameValueCollection collection; private NameValueDeserializer nvd; [SetUp] public void Setup() { collection = new NameValueCollection(); nvd = new NameValueDeserializer(); } [Test] public void EmptyPrefixThrows() { collection["junk"] = "stuff"; typeof(ArgumentException).ShouldBeThrownBy(() => nvd.Deserialize(collection, string.Empty, typeof(Customer))); } [Test] public void NullTargetTypeThrows() { collection["junk"] = "stuff"; typeof(ArgumentNullException).ShouldBeThrownBy(() => nvd.Deserialize(collection, "junk", null)); } [Test] public void ListPropertyIsSkippedIfNotInitializedAndReadOnly() { collection["list.ReadonlyIds[0]"] = "10"; collection["list.ReadonlyIds[1]"] = "20"; var list = nvd.Deserialize<GenericListClass>(collection, "list"); Assert.IsNotNull(list); Assert.IsNull(list.ReadonlyIds); } [Test] public void ErrorsSettingPropertiesAreIgnored() { collection["emp.Age"] = "-1"; var emp = nvd.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp); Assert.AreEqual(0, emp.Age); } [Test] public void ComplexPropertyIsSkippedIfNotInitializedAndReadOnly() { collection["emp.BatPhone.Number"] = "800-DRK-KNGT"; var emp = nvd.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp); Assert.IsNull(emp.BatPhone); } [Test] public void DeserializeSimpleObject() { collection["cust.Id"] = "10"; var cust = nvd.Deserialize<Customer>(collection, "cust"); Assert.IsNotNull(cust); Assert.AreEqual(10, cust.Id); } [Test] public void DeserializeSimpleObjectNoPrefix() { collection["Id"] = "10"; var cust = nvd.Deserialize<Customer>(collection); Assert.IsNotNull(cust); Assert.AreEqual(10, cust.Id); } [Test] public void DeserializeSimpleArray() { collection["array.Ids[0]"] = "10"; collection["array.Ids[1]"] = "20"; var array = nvd.Deserialize<ArrayClass>(collection, "array"); Assert.IsNotNull(array); Assert.AreEqual(2, array.Ids.Length); Assert.AreEqual(10, array.Ids[0]); Assert.AreEqual(20, array.Ids[1]); } [Test] public void DeserializeSimpleArrayNoPrefix() { collection["Ids[0]"] = "10"; collection["Ids[1]"] = "20"; var array = nvd.Deserialize<ArrayClass>(collection); Assert.IsNotNull(array); Assert.AreEqual(2, array.Ids.Length); Assert.AreEqual(10, array.Ids[0]); Assert.AreEqual(20, array.Ids[1]); } [Test] public void DeserializeSimpleArrayFromMultiple() { collection.Add("array.ids", "10"); collection.Add("array.ids", "20"); var array = nvd.Deserialize<ArrayClass>(collection, "array"); Assert.IsNotNull(array); Assert.AreEqual(2, array.Ids.Length); Assert.AreEqual(10, array.Ids[0]); Assert.AreEqual(20, array.Ids[1]); } [Test] public void DeserializeSimpleArrayFromMultipleNoPrefix() { collection.Add("ids", "10"); collection.Add("ids", "20"); var array = nvd.Deserialize<ArrayClass>(collection); Assert.IsNotNull(array); Assert.AreEqual(2, array.Ids.Length); Assert.AreEqual(10, array.Ids[0]); Assert.AreEqual(20, array.Ids[1]); } [Test] public void DeserializePrimitiveArray() { collection["ids[0]"] = "10"; collection["ids[1]"] = "20"; var array = (int[])nvd.Deserialize(collection, "ids", typeof(int[])); Assert.IsNotNull(array); Assert.AreEqual(2, array.Length); Assert.AreEqual(10, array[0]); Assert.AreEqual(20, array[1]); } [Test] public void DeserializePrimitiveArrayFromMultiple() { collection.Add("ids", "10"); collection.Add("ids", "20"); var array = (int[])nvd.Deserialize(collection, "ids", typeof(int[])); Assert.IsNotNull(array); Assert.AreEqual(2, array.Length); Assert.AreEqual(10, array[0]); Assert.AreEqual(20, array[1]); } [Test] public void DeserializePrimitiveGenericList() { collection["ids[0]"] = "10"; collection["ids[1]"] = "20"; var list = nvd.Deserialize<List<int>>(collection, "ids"); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); Assert.AreEqual(10, list[0]); Assert.AreEqual(20, list[1]); } [Test] public void DeserializePrimitiveGenericListFromMultiple() { collection.Add("ids", "10"); collection.Add("ids", "20"); var list = nvd.Deserialize<List<int>>(collection, "ids"); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); Assert.AreEqual(10, list[0]); Assert.AreEqual(20, list[1]); } [Test] public void DeserializeEnumGenericListFromMultiple() { collection.Add("testEnum", "0"); collection.Add("testEnum", "2"); var list = nvd.Deserialize<List<TestEnum>>(collection, "testEnum"); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); Assert.AreEqual(TestEnum.One, list[0]); Assert.AreEqual(TestEnum.Three, list[1]); } [Test] public void DeserializeSimpleGenericList() { collection["list.Ids[0]"] = "10"; collection["list.Ids[1]"] = "20"; var list = nvd.Deserialize<GenericListClass>(collection, "list"); Assert.IsNotNull(list); Assert.AreEqual(2, list.Ids.Count); Assert.AreEqual(10, list.Ids[0]); Assert.AreEqual(20, list.Ids[1]); } [Test] public void DeserializeSimpleGenericListNoPrefix() { collection["Ids[0]"] = "10"; collection["Ids[1]"] = "20"; var list = nvd.Deserialize<GenericListClass>(collection); Assert.IsNotNull(list); Assert.AreEqual(2, list.Ids.Count); Assert.AreEqual(10, list.Ids[0]); Assert.AreEqual(20, list.Ids[1]); } [Test] public void DeserializeSimpleGenericListFromMultiple() { collection.Add("list.Ids", "10"); collection.Add("list.Ids", "20"); var list = nvd.Deserialize<GenericListClass>(collection, "list"); Assert.IsNotNull(list); Assert.AreEqual(2, list.Ids.Count); Assert.AreEqual(10, list.Ids[0]); Assert.AreEqual(20, list.Ids[1]); } [Test] public void DeserializeSimpleGenericListFromMultipleNoPrefix() { collection.Add("Ids", "10"); collection.Add("Ids", "20"); var list = nvd.Deserialize<GenericListClass>(collection); Assert.IsNotNull(list); Assert.AreEqual(2, list.Ids.Count); Assert.AreEqual(10, list.Ids[0]); Assert.AreEqual(20, list.Ids[1]); } [Test] public void DeserializeComplexGenericList() { collection["emp.OtherPhones[0].Number"] = "800-555-1212"; collection["emp.OtherPhones[1].Number"] = "800-867-5309"; collection["emp.OtherPhones[1].AreaCodes[0]"] = "800"; collection["emp.OtherPhones[1].AreaCodes[1]"] = "877"; var emp = nvd.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp); Assert.AreEqual(2, emp.OtherPhones.Count); Assert.AreEqual("800-555-1212", emp.OtherPhones[0].Number); Assert.AreEqual("800-867-5309", emp.OtherPhones[1].Number); Assert.AreEqual(2, emp.OtherPhones[1].AreaCodes.Count); Assert.AreEqual("800", emp.OtherPhones[1].AreaCodes[0]); Assert.AreEqual("877", emp.OtherPhones[1].AreaCodes[1]); } [Test] public void DeserializeComplexGenericListNoPrefix() { collection["OtherPhones[0].Number"] = "800-555-1212"; collection["OtherPhones[1].Number"] = "800-867-5309"; collection["OtherPhones[1].AreaCodes[0]"] = "800"; collection["OtherPhones[1].AreaCodes[1]"] = "877"; var emp = nvd.Deserialize<Employee>(collection); Assert.IsNotNull(emp); Assert.AreEqual(2, emp.OtherPhones.Count); Assert.AreEqual("800-555-1212", emp.OtherPhones[0].Number); Assert.AreEqual("800-867-5309", emp.OtherPhones[1].Number); Assert.AreEqual(2, emp.OtherPhones[1].AreaCodes.Count); Assert.AreEqual("800", emp.OtherPhones[1].AreaCodes[0]); Assert.AreEqual("877", emp.OtherPhones[1].AreaCodes[1]); } [Test] public void DeserializeWithEmptyArray() { collection["array.Name"] = "test"; var array = nvd.Deserialize<ArrayClass>(collection, "array"); Assert.IsNotNull(array); Assert.AreEqual(0, array.Ids.Length); } [Test] public void DeserializeWithEmptyArrayNoPrefix() { collection["Name"] = "test"; var array = nvd.Deserialize<ArrayClass>(collection); Assert.IsNotNull(array); Assert.AreEqual(0, array.Ids.Length); } [Test] public void DeserializeComplexObject() { collection["emp.Id"] = "20"; collection["emp.Phone.Number"] = "800-555-1212"; var emp = nvd.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp); Assert.AreEqual(20, emp.Id); Assert.AreEqual("800-555-1212", emp.Phone.Number); } [Test] public void DeserializeComplexObjectNoPrefix() { collection["Id"] = "20"; collection["Phone.Number"] = "800-555-1212"; var emp = nvd.Deserialize<Employee>(collection); Assert.IsNotNull(emp); Assert.AreEqual(20, emp.Id); Assert.AreEqual("800-555-1212", emp.Phone.Number); } [Test] public void EmptyValuesUseDefaultOfType() { collection["cust.Id"] = ""; var cust = nvd.Deserialize<Customer>(collection, "cust"); Assert.IsNotNull(cust); Assert.AreEqual(0, cust.Id); } [Test] public void EmptyValuesUseDefaultOfTypeNoPrefix() { collection["Id"] = ""; var cust = nvd.Deserialize<Customer>(collection); Assert.IsNotNull(cust); Assert.AreEqual(0, cust.Id); } [Test] public void NoMatchingValuesReturnsNewedObjectNoPrefix() { collection["Ip"] = "10"; var cust = nvd.Deserialize<Customer>(collection); Assert.IsNotNull(cust); } [Test] public void DeserializeTrueBool() { collection["bool.myBool"] = "true,false"; var boolClass = nvd.Deserialize<BoolClass>(collection, "bool"); Assert.AreEqual(true, boolClass.MyBool); } [Test] public void DeserializeTrueBoolNoPrefix() { collection["myBool"] = "true,false"; var boolClass = nvd.Deserialize<BoolClass>(collection); Assert.AreEqual(true, boolClass.MyBool); } [Test] public void DeserializeFalseBool() { collection["bool.myBool"] = "false"; var boolClass = nvd.Deserialize<BoolClass>(collection, "bool"); Assert.AreEqual(false, boolClass.MyBool); } [Test] public void DeserializeFalseBoolNoPrefix() { collection["myBool"] = "false"; var boolClass = nvd.Deserialize<BoolClass>(collection); Assert.AreEqual(false, boolClass.MyBool); } [Test] public void EmptyCollectionReturnsNull() { var cust = nvd.Deserialize<Customer>(null, "cust"); Assert.IsNull(cust); } [Test] public void EmptyCollectionReturnsNullNoPrefix() { var cust = nvd.Deserialize<Customer>(null); Assert.IsNull(cust); } [Test] public void NoRequestForPropertyShouldNotInstantiateProperty() { collection["emp.Id"] = "20"; collection["emp.Phone.Number"] = "800-555-1212"; var deserializer = new NameValueDeserializer(); var emp = deserializer.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp, "Employee should not be null."); Assert.IsNotNull(emp.Phone, "Employee phone should not be null."); Assert.IsNull(emp.BatPhone, "Employee OtherPhones should be null because it was not in request parameters."); } [Test] public void NoRequestForPropertyShouldNotInstantiatePropertyNoPrefix() { collection["Id"] = "20"; collection["Phone.Number"] = "800-555-1212"; var deserializer = new NameValueDeserializer(); var emp = deserializer.Deserialize<Employee>(collection, "emp"); Assert.IsNotNull(emp, "Employee should not be null."); Assert.IsNotNull(emp.Phone, "Employee phone should not be null."); Assert.IsNull(emp.BatPhone, "Employee OtherPhones should be null because it was not in request parameters."); } [Test] public void ShouldNotThrowWithNullValues() { collection[null] = null; var deserializer = new NameValueDeserializer(); deserializer.Deserialize(collection, "cust", typeof(Customer)); } [Test] public void ShouldNotThrowWithNullValuesNoPrefix() { collection[null] = null; var deserializer = new NameValueDeserializer(); deserializer.Deserialize(collection, typeof(Customer)); } public class Customer { public int Id { get; set; } public Employee Employee { get; set; } } public class ArrayClass { public string Name { get; set; } public int[] Ids { get; set; } } public class BoolClass { public bool MyBool { get; set; } } public class GenericListClass { public string Name { get; set; } public IList<int> Ids { get; set; } private const IList<int> _readonlyIds = null; public IList<int> ReadonlyIds { get { return _readonlyIds; } } } public class Employee { private readonly Phone _phone = new Phone(); private readonly List<Phone> _otherPhones = new List<Phone>(); public int Id { get; set; } public Phone Phone { get { return _phone; } } private const Phone _batPhone = null; public Phone BatPhone { get { return _batPhone; } } public IList<Phone> OtherPhones { get { return _otherPhones; } } public Customer Customer { get; set; } private int _age; public int Age { get { return _age; } set { if (value < 0) throw new ArgumentException("Age must be greater than 0"); _age = value; } } } public class Phone { private readonly List<string> _areaCodes = new List<string>(); public string Number { get; set; } public IList<string> AreaCodes { get { return _areaCodes; } } } public enum TestEnum { One, Two, Three } } public static class NVDExtensions { internal static T Deserialize<T>(this NameValueDeserializer nvd, NameValueCollection collection, string prefix) where T : new() { return (T)nvd.Deserialize(collection, prefix, typeof(T)); } internal static T Deserialize<T>(this NameValueDeserializer nvd, NameValueCollection collection) where T : new() { return (T)nvd.Deserialize(collection, null, typeof(T)); } internal static object Deserialize(this NameValueDeserializer nvd, NameValueCollection collection, Type targetType) { return nvd.Deserialize(collection, null, targetType); } } }
using System; using NUnit.Framework; using VDS.RDF; using VDS.RDF.Parsing; using System.Collections.Generic; using it.unifi.dsi.stlab.networkreasoner.model.gas; namespace it.unifi.dsi.stlab.networkreasoner.model.rdfinterface.tests { [TestFixture()] public class SpecifingSimpleGasNetworks { [Test()] public void instantiate_an_object_from_triple_type_specification () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); Graph g = new Graph (); g.NamespaceMap.AddNamespace ("obj", UriFactory.Create ("http://example.org/object/")); g.NamespaceMap.AddNamespace ("type", UriFactory.Create ("http://example.org/type/")); g.NamespaceMap.AddNamespace ("csharp", UriFactory.Create ("http://example.org/csharp/")); g.NamespaceMap.AddNamespace ("rdf", UriFactory.Create ("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); IUriNode type = g.CreateUriNode ("type:aType"); IUriNode csharpEffectiveTypePred = g.CreateUriNode ("csharp:qualified-fullname"); ILiteralNode csharpEffectiveType = g.CreateLiteralNode ( "it.unifi.dsi.stlab.networkreasoner.model.rdfinterface.tests.DummyTypeForInstantiation, it.unifi.dsi.stlab.networkreasoner.model.rdfinterface.tests"); Triple typeSpecification = new Triple ( type, csharpEffectiveTypePred, csharpEffectiveType); Object instance = loader.Instantiate (typeSpecification); Assert.IsInstanceOf (typeof(DummyTypeForInstantiation), instance); } [Test()] public void load_specification_into_a_graph () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-with-gadgets-without-edges.nt"; IGraph g = new Graph (); loader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Assert.AreEqual (19, g.Triples.Count); } [Test()] public void instantiate_objects_inside_a_graph_with_only_one_node_specification () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-checking-object-instantiation.nt"; IGraph g = new Graph (); loader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Dictionary<String, Object> objectsByUri = loader.InstantiateObjects (g); Assert.AreEqual (3, objectsByUri.Count); String singleObjectKey = "http://stlab.dsi.unifi.it/networkreasoner/node/single-node"; String loadGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load"; String supplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/gadget/supply"; Assert.IsTrue (objectsByUri.ContainsKey (singleObjectKey)); Assert.IsTrue (objectsByUri.ContainsKey (loadGadgetKey)); Assert.IsTrue (objectsByUri.ContainsKey (supplyGadgetKey)); Assert.IsInstanceOf (typeof(DummyTypeForInstantiation), objectsByUri [singleObjectKey]); Assert.IsInstanceOf (typeof(AnotherDummyObject), objectsByUri [loadGadgetKey]); Assert.IsInstanceOf (typeof(MoreDummyObject), objectsByUri [supplyGadgetKey]); } [Test()] public void set_literal_properties () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-checking-literal-properties.nt"; IGraph g = new Graph (); loader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Dictionary<String, Object> objectsByUri = loader.InstantiateObjects (g); loader.setPropertiesOnInstances (objectsByUri, g); Assert.AreEqual (4, objectsByUri.Count); String loadGadget1Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load1"; String loadGadget2Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load2"; String supplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/gadget/supply"; String nodeKey = "http://stlab.dsi.unifi.it/networkreasoner/node/node"; Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget1Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget2Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetSupply), objectsByUri [supplyGadgetKey]); Assert.IsInstanceOf (typeof(GasNodeTopological), objectsByUri [nodeKey]); var loadGadget1 = objectsByUri [loadGadget1Key] as GasNodeGadgetLoad; var loadGadget2 = objectsByUri [loadGadget2Key] as GasNodeGadgetLoad; var supplyGadget = objectsByUri [supplyGadgetKey] as GasNodeGadgetSupply; var node = objectsByUri [nodeKey] as GasNodeTopological; Assert.AreEqual (463.98, loadGadget1.Load); Assert.AreEqual (756.38, loadGadget2.Load); Assert.AreEqual (157.34, supplyGadget.SetupPressure); Assert.AreEqual (785.23, supplyGadget.MaxQ); Assert.AreEqual (100.00, supplyGadget.MinQ); Assert.AreEqual ("single node", node.Identifier); Assert.AreEqual (35, node.Height); Assert.AreEqual ("this is the very first node that we build with our system.", node.Comment); } [Test()] public void load_vertices_equipped_with_gadgets () { var specLoader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-loading-equipped-vertices.nt"; IGraph g = new Graph (); specLoader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Dictionary<String, Object> objectsByUri = specLoader.InstantiateObjects (g); specLoader.setPropertiesOnInstances (objectsByUri, g); Assert.AreEqual (7, objectsByUri.Count); String loadGadget1Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load1"; String loadGadget2Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load2"; String supplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/gadget/supply"; String nodeKey = "http://stlab.dsi.unifi.it/networkreasoner/node/node"; String nodeToBeEquippedWithSupplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/node/node-to-be-equipped-with-supply-gadget"; String loaderKey = "http://stlab.dsi.unifi.it/networkreasoner/node/loader"; String supplierKey = "http://stlab.dsi.unifi.it/networkreasoner/node/supplier"; Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget1Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget2Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetSupply), objectsByUri [supplyGadgetKey]); Assert.IsInstanceOf (typeof(GasNodeTopological), objectsByUri [nodeKey]); Assert.IsInstanceOf (typeof(GasNodeTopological), objectsByUri [nodeToBeEquippedWithSupplyGadgetKey]); Assert.IsInstanceOf (typeof(GasNodeWithGadget), objectsByUri [loaderKey]); Assert.IsInstanceOf (typeof(GasNodeWithGadget), objectsByUri [supplierKey]); var loadGadget1 = objectsByUri [loadGadget1Key] as GasNodeGadgetLoad; var loadGadget2 = objectsByUri [loadGadget2Key] as GasNodeGadgetLoad; var supplyGadget = objectsByUri [supplyGadgetKey] as GasNodeGadgetSupply; var node = objectsByUri [nodeKey] as GasNodeTopological; var nodeToBeEquippedWithSupplyGadget = objectsByUri [nodeToBeEquippedWithSupplyGadgetKey] as GasNodeTopological; var loader = objectsByUri [loaderKey] as GasNodeWithGadget; var supplier = objectsByUri [supplierKey] as GasNodeWithGadget; Assert.AreEqual (463.98, loadGadget1.Load); Assert.AreEqual (756.38, loadGadget2.Load); Assert.AreEqual (157.34, supplyGadget.SetupPressure); Assert.AreEqual (785.23, supplyGadget.MaxQ); Assert.AreEqual (100.00, supplyGadget.MinQ); Assert.AreEqual ("I'll be a loader", node.Identifier); Assert.AreEqual (35, node.Height); Assert.AreEqual ("this is the very first node that we build with our system.", node.Comment); Assert.AreEqual ("I'll be a supplier", nodeToBeEquippedWithSupplyGadget.Identifier); Assert.AreEqual (46, nodeToBeEquippedWithSupplyGadget.Height); Assert.AreEqual ("", nodeToBeEquippedWithSupplyGadget.Comment); Assert.IsNotNull (loader.Equipped); Assert.IsNotNull (loader.Gadget); Assert.AreSame (node, loader.Equipped); Assert.AreSame (loadGadget1, loader.Gadget); Assert.IsNotNull (supplier.Equipped); Assert.IsNotNull (supplier.Gadget); Assert.AreSame (nodeToBeEquippedWithSupplyGadget, supplier.Equipped); Assert.AreSame (supplyGadget, supplier.Gadget); } [Test()] public void load_vertices_equipped_with_gadgets_substituting_decorator_objects () { var specLoader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-loading-equipped-vertices-with-decoration-substitution.nt"; IGraph g = new Graph (); Dictionary<String, Object> objectsByUri; specLoader.ReifySpecification (filenameToParse, g, out objectsByUri); Assert.AreEqual (5, objectsByUri.Count); String loadGadget1Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load1"; String loadGadget2Key = "http://stlab.dsi.unifi.it/networkreasoner/gadget/load2"; String supplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/gadget/supply"; String nodeKey = "http://stlab.dsi.unifi.it/networkreasoner/node/node"; String nodeToBeEquippedWithSupplyGadgetKey = "http://stlab.dsi.unifi.it/networkreasoner/node/node-to-be-equipped-with-supply-gadget"; String loaderKey = "http://stlab.dsi.unifi.it/networkreasoner/node/loader"; String supplierKey = "http://stlab.dsi.unifi.it/networkreasoner/node/supplier"; Assert.IsFalse (objectsByUri.ContainsKey (nodeKey)); Assert.IsFalse (objectsByUri.ContainsKey (nodeToBeEquippedWithSupplyGadgetKey)); Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget1Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetLoad), objectsByUri [loadGadget2Key]); Assert.IsInstanceOf (typeof(GasNodeGadgetSupply), objectsByUri [supplyGadgetKey]); Assert.IsInstanceOf (typeof(GasNodeWithGadget), objectsByUri [loaderKey]); Assert.IsInstanceOf (typeof(GasNodeWithGadget), objectsByUri [supplierKey]); var loadGadget1 = objectsByUri [loadGadget1Key] as GasNodeGadgetLoad; var loadGadget2 = objectsByUri [loadGadget2Key] as GasNodeGadgetLoad; var supplyGadget = objectsByUri [supplyGadgetKey] as GasNodeGadgetSupply; var loader = objectsByUri [loaderKey] as GasNodeWithGadget; var supplier = objectsByUri [supplierKey] as GasNodeWithGadget; Assert.IsNotNull (loader.Equipped); Assert.IsNotNull (loader.Gadget); Assert.IsInstanceOf (typeof(GasNodeTopological), loader.Equipped); Assert.IsNotNull (supplier.Equipped); Assert.IsNotNull (supplier.Gadget); Assert.IsInstanceOf (typeof(GasNodeTopological), supplier.Equipped); var node = loader.Equipped as GasNodeTopological; var nodeToBeEquippedWithSupplyGadget = supplier.Equipped as GasNodeTopological; Assert.AreEqual (463.98, loadGadget1.Load); Assert.AreEqual (756.38, loadGadget2.Load); Assert.AreEqual (157.34, supplyGadget.SetupPressure); Assert.AreEqual (785.23, supplyGadget.MaxQ); Assert.AreEqual (100.00, supplyGadget.MinQ); Assert.AreEqual ("I'll be a loader", node.Identifier); Assert.AreEqual (35, node.Height); Assert.AreEqual ("this is the very first node that we build with our system.", node.Comment); Assert.AreEqual ("I'll be a supplier", nodeToBeEquippedWithSupplyGadget.Identifier); Assert.AreEqual (46, nodeToBeEquippedWithSupplyGadget.Height); Assert.AreEqual ("", nodeToBeEquippedWithSupplyGadget.Comment); } [Test()] public void build_edges_and_set_object_properties () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-checking-edge-and-uri-objects.nt"; IGraph g = new Graph (); Dictionary<String, Object> objectsByUri; loader.ReifySpecification (filenameToParse, g, out objectsByUri); Assert.AreEqual (8, objectsByUri.Count); String nodeAKey = "http://stlab.dsi.unifi.it/networkreasoner/network/nodeA"; String nodeBKey = "http://stlab.dsi.unifi.it/networkreasoner/network/nodeB"; String nodeCKey = "http://stlab.dsi.unifi.it/networkreasoner/network/nodeC"; String nodeDKey = "http://stlab.dsi.unifi.it/networkreasoner/network/nodeD"; String edgeADKey = "http://stlab.dsi.unifi.it/networkreasoner/network/edgeAD-physical"; String edgeABKey = "http://stlab.dsi.unifi.it/networkreasoner/network/edgeAB-physical"; String edgeBCKey = "http://stlab.dsi.unifi.it/networkreasoner/network/edgeBC-physical"; String edgeDBKey = "http://stlab.dsi.unifi.it/networkreasoner/network/edgeDB-physical"; // we do not check the types for nodes since we have already // a test case for them. Assert.IsInstanceOf (typeof(GasEdgePhysical), objectsByUri [edgeADKey]); Assert.IsInstanceOf (typeof(GasEdgePhysical), objectsByUri [edgeABKey]); Assert.IsInstanceOf (typeof(GasEdgePhysical), objectsByUri [edgeBCKey]); Assert.IsInstanceOf (typeof(GasEdgePhysical), objectsByUri [edgeDBKey]); var nodeA = objectsByUri [nodeAKey] as GasNodeTopological; var nodeB = objectsByUri [nodeBKey] as GasNodeTopological; var nodeC = objectsByUri [nodeCKey] as GasNodeTopological; var nodeD = objectsByUri [nodeDKey] as GasNodeTopological; var edgeAD = objectsByUri [edgeADKey] as GasEdgePhysical; var edgeAB = objectsByUri [edgeABKey] as GasEdgePhysical; var edgeBC = objectsByUri [edgeBCKey] as GasEdgePhysical; var edgeDB = objectsByUri [edgeDBKey] as GasEdgePhysical; Assert.IsInstanceOf (typeof(GasEdgeTopological), edgeAD.Described); Assert.IsInstanceOf (typeof(GasEdgeTopological), edgeAB.Described); Assert.IsInstanceOf (typeof(GasEdgeTopological), edgeBC.Described); Assert.IsInstanceOf (typeof(GasEdgeTopological), edgeDB.Described); var edgeADTopological = edgeAD.Described as GasEdgeTopological; var edgeABTopological = edgeAB.Described as GasEdgeTopological; var edgeBCTopological = edgeBC.Described as GasEdgeTopological; var edgeDBTopological = edgeDB.Described as GasEdgeTopological; Assert.AreEqual (45.968, edgeAD.Diameter); Assert.AreSame (nodeD, edgeADTopological.EndNode); Assert.AreEqual (1500, edgeAD.Length); Assert.AreEqual (12.35, edgeAD.MaxSpeed); Assert.AreEqual (1.7, edgeAD.Roughness); Assert.AreSame (nodeA, edgeADTopological.StartNode); Assert.AreEqual (4.8, edgeAB.Diameter); Assert.AreSame (nodeB, edgeABTopological.EndNode); Assert.AreEqual (150, edgeAB.Length); Assert.AreEqual (4, edgeAB.MaxSpeed); Assert.AreEqual (4.7, edgeAB.Roughness); Assert.AreSame (nodeA, edgeABTopological.StartNode); Assert.AreEqual (5.968, edgeBC.Diameter); Assert.AreSame (nodeC, edgeBCTopological.EndNode); Assert.AreEqual (3400, edgeBC.Length); Assert.AreEqual (2.35, edgeBC.MaxSpeed); Assert.AreEqual (17, edgeBC.Roughness); Assert.AreSame (nodeB, edgeBCTopological.StartNode); Assert.AreEqual (459.68, edgeDB.Diameter); Assert.AreSame (nodeB, edgeDBTopological.EndNode); Assert.AreEqual (15000, edgeDB.Length); Assert.AreEqual (123, edgeDB.MaxSpeed); Assert.AreEqual (17, edgeDB.Roughness); Assert.AreSame (nodeD, edgeDBTopological.StartNode); } [Test()] public void load_main_network_object () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-loading-the-main-network-object.nt"; IGraph g = new Graph (); loader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Dictionary<String, Object> objectsByUri = loader.InstantiateObjects (g); loader.setPropertiesOnInstances (objectsByUri, g); var mainNetwork = loader.FindMainNetwork (objectsByUri, g); Assert.IsInstanceOf (typeof(GasNetwork), mainNetwork); var gasNetwork = mainNetwork as GasNetwork; Assert.AreEqual ("This network represent a gas network, actually an empty network.", gasNetwork.Description); CollectionAssert.IsEmpty (gasNetwork.Edges); CollectionAssert.IsEmpty (gasNetwork.Nodes); } [Test()] public void check_if_parser_receiver_is_correctly_set_in_main_network_object () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-loading-the-main-network-object-with-result-receiver.nt"; IGraph g = new Graph (); loader.LoadFileIntoGraphReraisingParseException (filenameToParse, g); Dictionary<String, Object> objectsByUri = loader.InstantiateObjects (g); loader.setPropertiesOnInstances (objectsByUri, g); var mainNetwork = loader.FindMainNetwork (objectsByUri, g); var parserResultReceiver = loader.GetParserResultReceiverFrom (objectsByUri, g); Assert.IsInstanceOf (typeof(GasParserResultReceiver), parserResultReceiver); var gasNetwork = mainNetwork as GasNetwork; Assert.AreSame (gasNetwork.ParserResultReceiver, parserResultReceiver); } [Test()] public void load_a_complete_network_with_a_main_object_defined_in_specification () { var loader = SpecificationLoader.MakeNTurtleSpecificationLoader (); var filenameToParse = "../../nturtle-specifications/gas/specification-for-loading-a-network-with-a-main-object-defined-in-it.nt"; var network = loader.Load<GasNetwork> (filenameToParse); Assert.IsNotNull (network); Assert.IsInstanceOf (typeof(GasNetwork), network); Assert.IsNotNull (network.ParserResultReceiver); Assert.AreEqual ("This network represent a gas network", network.Description); Assert.AreEqual (4, network.Nodes.Count); Assert.AreEqual (4, network.Edges.Count); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Text; using System.IO; using System.Net; namespace fyiReporting.RDL { ///<summary> /// PageTextHtml handles text that should to be formatted as HTML. It only handles /// a subset of HTML (e.g. "<b>,<br>, ..." ///</summary> public class PageTextHtml : PageText, IEnumerable, ICloneable { List<PageItem> _items=null; Stack _StyleStack; // work variable when processing styles float _TotalHeight=0; public PageTextHtml(string t) : base(t) { } /// <summary> /// Reset will force a recalculation of the embedded PageItems; /// </summary> public void Reset() { _items = null; } public float TotalHeight { get { if (_items == null) throw new Exception("Build method must be called prior to referencing TotalHeight."); return _TotalHeight; } } public void Build(Graphics g) { System.Drawing.Drawing2D.Matrix transform = g.Transform; try { g.ResetTransform(); BuildPrivate(g); } finally { g.Transform = transform; } return; } private void BuildPrivate(Graphics g) { PageText model = new PageText(""); model.AllowSelect = false; model.Page = this.Page; model.HyperLink=null; model.Tooltip=null; int fontSizeModel = 3; if (_items != null) // this has already been built return; _items = new List<PageItem>(); _StyleStack = new Stack(); // The first item is always a text box with the border and background attributes PageText pt = new PageText(""); pt.AllowSelect = true; // This item represents HTML item for selection in RdlViewer pt.Page = this.Page; pt.HtmlParent = this; pt.X = this.X; pt.Y = this.Y; pt.H = this.H; pt.W = this.W; pt.CanGrow = false; pt.SI = this.SI.Clone() as StyleInfo; pt.SI.PaddingBottom = pt.SI.PaddingLeft = pt.SI.PaddingRight = pt.SI.PaddingTop = 0; pt.SI.TextAlign = TextAlignEnum.Left; _items.Add(pt); // Now we create multiple items that represent what is in the box PageTextHtmlLexer hl = new PageTextHtmlLexer(this.Text); List<string> tokens = hl.Lex(); float textWidth = this.W - pt.SI.PaddingLeft - pt.SI.PaddingRight; // Now set the default style for the rest of the members StyleInfo si = this.SI.Clone() as StyleInfo; si.BStyleBottom = si.BStyleLeft = si.BStyleRight = si.BStyleTop = BorderStyleEnum.None; pt.SI.TextAlign = TextAlignEnum.Left; pt.SI.VerticalAlign = VerticalAlignEnum.Top; si.BackgroundColor = Color.Empty; si.BackgroundGradientType = BackgroundGradientTypeEnum.None; si.BackgroundImage = null; bool bFirstInLine=true; StringBuilder sb = new StringBuilder(); // this will hold the accumulating line float lineXPos=0; float xPos = 0; float yPos = 0; float maxLineHeight=0; float maxDescent=0; float descent; // working value for descent SizeF ms; bool bWhiteSpace=false; List<PageItem> lineItems = new List<PageItem>(); foreach (string token in tokens) { if (token[0] == PageTextHtmlLexer.HTMLCMD) // indicates an HTML command { // we need to create a PageText since the styleinfo is changing if (sb.Length != 0) { pt = new PageText(sb.ToString()); pt.AllowSelect = false; pt.Page = this.Page; pt.HtmlParent = this; pt.HyperLink = model.HyperLink; pt.Tooltip = model.Tooltip; pt.NoClip = true; sb = new StringBuilder(); pt.X = this.X + lineXPos; pt.Y = this.Y + yPos; pt.CanGrow = false; pt.SI = CurrentStyle(si).Clone() as StyleInfo; _items.Add(pt); lineItems.Add(pt); ms = this.MeasureString(pt.Text, pt.SI, g, out descent); maxDescent = Math.Max(maxDescent, descent); pt.W = ms.Width; pt.H = ms.Height; pt.Descent = descent; maxLineHeight = Math.Max(maxLineHeight, ms.Height); lineXPos = xPos; } // Now reset the styleinfo StyleInfo cs = CurrentStyle(si); string ltoken = token.Substring(1,Math.Min(token.Length-1,10)).ToLower(); if (ltoken == "<b>" || ltoken == "<strong>") cs.FontWeight = FontWeightEnum.Bold; else if (ltoken == "</b>" || ltoken == "</strong>") cs.FontWeight = FontWeightEnum.Normal; else if (ltoken == "<i>" || ltoken == "<cite>" || ltoken == "<var>" || ltoken == "<em>") cs.FontStyle = FontStyleEnum.Italic; else if (ltoken == "</i>" || ltoken == "</cite>" || ltoken == "</var>" || ltoken == "</em>") cs.FontStyle = FontStyleEnum.Normal; else if (ltoken == "<code>" || ltoken == "<samp>") cs.FontFamily = "Courier New"; else if (ltoken == "</code>" || ltoken == "</samp>") cs.FontFamily = this.SI.FontFamily; else if (ltoken == "<kbd>") { cs.FontFamily = "Courier New"; cs.FontWeight = FontWeightEnum.Bold; } else if (ltoken == "</kdd>") { cs.FontFamily = this.SI.FontFamily; cs.FontWeight = FontWeightEnum.Normal; } else if (ltoken == "<big>") { // big makes it bigger by 20% for each time over the baseline of 3 fontSizeModel++; float inc = 1; for (int i=3; i < fontSizeModel; i++) { inc += .2f; } float h = this.SI.FontSize * inc; cs.FontSize = h; } else if (ltoken == "</big>") { // undoes the effect of big fontSizeModel--; float inc = 1; for (int i=3; i < fontSizeModel; i++) { inc += .2f; } float h = this.SI.FontSize / inc; cs.FontSize = h; } else if (ltoken == "<small>") { // small makes it smaller by 20% for each time under the baseline of 3 fontSizeModel--; float inc = 1; for (int i=3; i > fontSizeModel; i--) { inc += .2f; } float h = this.SI.FontSize / inc; cs.FontSize = h; } else if (ltoken == "</small>") { // undoes the effect of small fontSizeModel++; float inc = 1; for (int i=3; i > fontSizeModel; i--) { inc += .2f; } float h = this.SI.FontSize * inc; cs.FontSize = h; } else if (ltoken.StartsWith("<br")) { yPos += maxLineHeight; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } else if (ltoken.StartsWith("<hr")) { // Add a line // Process existing line if any yPos += maxLineHeight; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; PageLine pl = new PageLine(); pl.AllowSelect = false; pl.Page = this.Page; const int horzLineHeight = 10; pl.SI = cs.Clone() as StyleInfo; pl.SI.BStyleLeft = BorderStyleEnum.Ridge; pl.Y = pl.Y2 = this.Y + yPos + horzLineHeight / 2; pl.X = this.X; pl.X2 = pl.X + this.W; _items.Add(pl); yPos += horzLineHeight; // skip past horizontal line } else if (ltoken.StartsWith("<p")) { yPos += maxLineHeight * 2; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } else if (ltoken.StartsWith("<a")) { BuildAnchor(token.Substring(1), cs, model); } else if (ltoken.StartsWith("<img")) { PageImage pimg = BuildImage(g, token.Substring(1), cs, model); if (pimg != null) // We got an image; add to process list { pimg.Y = this.Y + yPos; pimg.X = this.X; _items.Add(pimg); yPos += pimg.H; // Increment y position maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } } else if (ltoken == "</a>") { model.HyperLink = model.Tooltip = null; PopStyle(); } else if (ltoken.StartsWith("<span")) { HandleStyle(token.Substring(1), si); } else if (ltoken == "</span>") { // we really should match span and font but it shouldn't matter very often? PopStyle(); } else if (ltoken.StartsWith("<font")) { HandleFont(token.Substring(1), si); } else if (ltoken == "</font>") { // we really should match span and font but it shouldn't matter very often? PopStyle(); } continue; } if (token == PageTextHtmlLexer.WHITESPACE) { if (!bFirstInLine) bWhiteSpace = true; continue; } if (token != PageTextHtmlLexer.EOF) { string ntoken; if (token == PageTextHtmlLexer.NBSP.ToString()) ntoken = bWhiteSpace ? " " : " "; else ntoken = bWhiteSpace ? " " + token : token; ntoken = ntoken.Replace(PageTextHtmlLexer.NBSP, ' '); bWhiteSpace = false; // can only use whitespace once ms = this.MeasureString(ntoken, CurrentStyle(si), g, out descent); if (xPos + ms.Width < textWidth) { bFirstInLine = false; sb.Append(ntoken); maxDescent = Math.Max(maxDescent, descent); maxLineHeight = Math.Max(maxLineHeight, ms.Height); xPos += ms.Width; continue; } } else if (sb.Length == 0) // EOF and no previous string means we're done continue; pt = new PageText(sb.ToString()); pt.AllowSelect = false; pt.Page = this.Page; pt.HtmlParent = this; pt.NoClip = true; pt.HyperLink = model.HyperLink; pt.Tooltip = model.Tooltip; sb = new StringBuilder(); sb.Append(token.Replace(PageTextHtmlLexer.NBSP, ' ')); pt.SI = CurrentStyle(si).Clone() as StyleInfo; ms = this.MeasureString(pt.Text, pt.SI, g, out descent); pt.X = this.X + lineXPos; pt.Y = this.Y + yPos; pt.H = ms.Height; pt.W = ms.Width; pt.Descent = descent; pt.CanGrow = false; _items.Add(pt); lineItems.Add(pt); maxDescent = Math.Max(maxDescent, descent); maxLineHeight = Math.Max(maxLineHeight, ms.Height); yPos += maxLineHeight; // Increment y position NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); lineXPos = maxLineHeight = maxDescent = 0; // start line height over // Now set the xPos just after the current token ms = this.MeasureString(token, CurrentStyle(si), g, out descent); xPos = ms.Width; } _TotalHeight = yPos; // set the calculated height of the result _StyleStack = null; return; } private void BuildAnchor(string token, StyleInfo oldsi, PageText model) { StyleInfo si= oldsi.Clone() as StyleInfo; // always push a StyleInfo _StyleStack.Push(si); // since they will always be popped Hashtable ht = ParseHtmlCmd(token); string href = (string) ht["href"]; if (href == null || href.Length < 1) return; model.HyperLink = model.Tooltip = href; si.TextDecoration = TextDecorationEnum.Underline; si.Color = Color.Blue; } private PageImage BuildImage(Graphics g, string token, StyleInfo oldsi, PageText model) { PageTextHtmlCmdLexer hc = new PageTextHtmlCmdLexer(token.Substring(4)); Hashtable ht = hc.Lex(); string src = (string)ht["src"]; if (src == null || src.Length < 1) return null; string alt = (string)ht["alt"]; string height = (string)ht["height"]; string width = (string)ht["width"]; string align = (string)ht["align"]; Stream strm = null; System.Drawing.Image im = null; PageImage pi = null; try { // Obtain the image stream if (src.StartsWith("http:") || src.StartsWith("file:") || src.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(src); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(src, System.IO.FileMode.Open, FileAccess.Read); im = System.Drawing.Image.FromStream(strm); int h = im.Height; int w = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; imf = ImageFormat.Jpeg; im.Save(ostrm, imf); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, w, h); pi.AllowSelect = false; pi.Page = this.Page; pi.HyperLink = model.HyperLink; pi.Tooltip = alt == null ? model.Tooltip : alt; pi.X = 0; pi.Y = 0; pi.W = RSize.PointsFromPixels(g, width != null? Convert.ToInt32(width): w); pi.H = RSize.PointsFromPixels(g, height != null? Convert.ToInt32(height): h); pi.SI = new StyleInfo(); } catch { pi = null; } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } return pi; } private StyleInfo CurrentStyle(StyleInfo def) { if (_StyleStack == null || _StyleStack.Count == 0) return def; else return (StyleInfo) _StyleStack.Peek(); } private void HandleStyle(string token, StyleInfo model) { StyleInfo si= model.Clone() as StyleInfo; // always push a StyleInfo _StyleStack.Push(si); // since they will always be popped Hashtable ht = ParseHtmlCmd(token); string style = (string) ht["style"]; HandleStyleString(style, si); return; } private void HandleFont(string token, StyleInfo model) { StyleInfo si = model.Clone() as StyleInfo; // always push a StyleInfo _StyleStack.Push(si); // since they will always be popped PageTextHtmlCmdLexer hc = new PageTextHtmlCmdLexer(token.Substring(5)); Hashtable ht = hc.Lex(); string style = (string)ht["style"]; HandleStyleString(style, si); string color = (string)ht["color"]; if (color != null && color.Length > 0) si.Color = XmlUtil.ColorFromHtml(color, si.Color); string size = (string)ht["size"]; if (size != null && size.Length > 0) HandleStyleFontSize(si, size); string face = (string)ht["face"]; if (face != null && face.Length > 0) si.FontFamily = face; return; } private void HandleStyleString(string style, StyleInfo si) { if (style == null || style.Length < 1) return; string[] styleList = style.Split(new char[] {';'}); foreach (string item in styleList) { string[] val = item.Split(new char[] {':'}); if (val.Length != 2) continue; // must be illegal syntax string tval = val[1].Trim(); switch (val[0].ToLower().Trim()) { case "background": case "background-color": si.BackgroundColor = XmlUtil.ColorFromHtml(tval, si.Color); break; case "color": si.Color = XmlUtil.ColorFromHtml(tval, si.Color); break; case "font-family": si.FontFamily = tval; break; case "font-size": HandleStyleFontSize(si, tval); break; case "font-style": if (tval == "italic") si.FontStyle = FontStyleEnum.Italic; break; case "font-weight": HandleStyleFontWeight(si, tval); break; } } return; } private void HandleStyleFontSize(StyleInfo si, string size) { try { int i = size.IndexOf("pt"); if (i > 0) { size = size.Remove(i, 2); float n = (float) Convert.ToDouble(size); if (size[0] == '+') si.FontSize += n; else si.FontSize = n; return; } i = size.IndexOf("%"); if (i > 0) { size = size.Remove(i, 1); float n = (float) Convert.ToDouble(size); si.FontSize = n*si.FontSize; return; } switch (size) { case "xx-small": si.FontSize = 6; break; case "x-small": si.FontSize = 8; break; case "small": si.FontSize = 10; break; case "medium": si.FontSize = 12; break; case "large": si.FontSize = 14; break; case "x-large": si.FontSize = 16; break; case "xx-large": si.FontSize = 18; break; case "1": si.FontSize = 8; break; case "2": si.FontSize = 10; break; case "3": si.FontSize = 12; break; case "4": si.FontSize = 14; break; case "5": si.FontSize = 18; break; case "6": si.FontSize = 24; break; case "7": si.FontSize = 36; break; } } catch {} // lots of user errors will cause an exception; ignore return; } private void HandleStyleFontWeight(StyleInfo si, string w) { try { switch (w) { case "bold": si.FontWeight = FontWeightEnum.Bold; break; case "bolder": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight < FontWeightEnum.W900) si.FontWeight++; } else if (si.FontWeight == FontWeightEnum.Normal) si.FontWeight = FontWeightEnum.W700; else if (si.FontWeight == FontWeightEnum.Bold) si.FontWeight = FontWeightEnum.W900; else if (si.FontWeight != FontWeightEnum.Bolder) si.FontWeight = FontWeightEnum.Normal; break; case "lighter": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight > FontWeightEnum.W100) si.FontWeight--; } else if (si.FontWeight == FontWeightEnum.Normal) si.FontWeight = FontWeightEnum.W300; else if (si.FontWeight == FontWeightEnum.Bold) si.FontWeight = FontWeightEnum.W400; else if (si.FontWeight != FontWeightEnum.Lighter) si.FontWeight = FontWeightEnum.Normal; break; case "normal": si.FontWeight = FontWeightEnum.Normal; break; case "100": si.FontWeight = FontWeightEnum.W100; break; case "200": si.FontWeight = FontWeightEnum.W200; break; case "300": si.FontWeight = FontWeightEnum.W300; break; case "400": si.FontWeight = FontWeightEnum.W400; break; case "500": si.FontWeight = FontWeightEnum.W500; break; case "600": si.FontWeight = FontWeightEnum.W600; break; case "700": si.FontWeight = FontWeightEnum.W700; break; case "800": si.FontWeight = FontWeightEnum.W800; break; case "900": si.FontWeight = FontWeightEnum.W900; break; } } catch {} // lots of user errors will cause an exception; ignore return; } private void PopStyle() { if (_StyleStack != null && _StyleStack.Count > 0) _StyleStack.Pop(); } private void NormalizeLineHeight(List<PageItem> lineItems, float maxLineHeight, float maxDescent) { foreach (PageItem pi in lineItems) { if (pi is PageText) { // force the text to line up PageText pt = (PageText) pi; if (pt.H >= maxLineHeight) continue; pt.Y += maxLineHeight - pt.H; if (pt.Descent > 0 && pt.Descent < maxDescent) pt.Y -= (maxDescent - pt.Descent); } } lineItems.Clear(); } private Hashtable ParseHtmlCmd(string token) { Hashtable ht = new Hashtable(); // find the start and the end of the command int start = token.IndexOf(' '); // look for first blank if (start < 0) return ht; int end = token.LastIndexOf('>'); if (end < 0 || end <= start) return ht; string cmd = token.Substring(start, end - start); string[] keys = cmd.Split(new char[] {'='}); if (keys == null || keys.Length < 2) return ht; try { for (int i = 0; i < keys.Length - 1; i += 2) { // remove " from the value if any string v = keys[i + 1]; if (v.Length > 0 && (v[0] == '"' || v[0] == '\'')) v = v.Substring(1); if (v.Length > 0 && (v[v.Length - 1] == '"' || v[v.Length - 1] == '\'')) v = v.Substring(0, v.Length - 1); // normalize key to lower case string key = keys[i].ToLower().Trim(); ht.Add(key, v); } } catch { } // there are any number of ill formed strings that could cause problems; keep what we've found return ht; } private SizeF MeasureString(string s, StyleInfo si, Graphics g, out float descent) { Font drawFont=null; StringFormat drawFormat=null; SizeF ms = SizeF.Empty; descent = 0; if (s == null || s.Length == 0) return ms; try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) fs |= System.Drawing.FontStyle.Italic; // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } try { FontFamily ff = si.GetFontFamily(); drawFont = new Font(ff, si.FontSize, fs); // following algorithm comes from the C# Font Metrics documentation float descentPixel = si.FontSize * ff.GetCellDescent(fs) / ff.GetEmHeight(fs); descent = RSize.PointsFromPixels(g, descentPixel); } catch { drawFont = new Font("Arial", si.FontSize, fs); // usually because font not found descent = 0; } drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Near; CharacterRange[] cr = {new CharacterRange(0, s.Length)}; drawFormat.SetMeasurableCharacterRanges(cr); Region[] rs = new Region[1]; rs = g.MeasureCharacterRanges(s, drawFont, new RectangleF(0,0,float.MaxValue,float.MaxValue), drawFormat); RectangleF mr = rs[0].GetBounds(g); ms.Height = RSize.PointsFromPixels(g, mr.Height); // convert to points from pixels ms.Width = RSize.PointsFromPixels(g, mr.Width); // convert to points from pixels return ms; } finally { if (drawFont != null) drawFont.Dispose(); if (drawFormat != null) drawFont.Dispose(); } } #region IEnumerable Members public IEnumerator GetEnumerator() { if (_items == null) return null; return _items.GetEnumerator(); } #endregion #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } }
namespace RentalManagement.Migrations { using System; using System.Data.Entity.Migrations; public partial class reinit : DbMigration { public override void Up() { CreateTable( "dbo.Apartments", c => new { Id = c.Int(nullable: false, identity: true), IsAvailable = c.Boolean(nullable: false), DateAvailable = c.DateTime(nullable: false), RentPerMonth = c.Decimal(nullable: false, precision: 18, scale: 2), Unit = c.Int(nullable: false), NumberBedrooms = c.Double(nullable: false), NumberBathrooms = c.Double(nullable: false), Features = c.String(), RentalPropertyId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RentalProperties", t => t.RentalPropertyId, cascadeDelete: true) .Index(t => t.RentalPropertyId); CreateTable( "dbo.RentalProperties", c => new { Id = c.Int(nullable: false, identity: true), StreetAddress = c.String(), ZipCode = c.Int(nullable: false), PropertyManagerId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.PropertyManagers", t => t.PropertyManagerId, cascadeDelete: true) .Index(t => t.PropertyManagerId); CreateTable( "dbo.PropertyManagers", c => new { Id = c.Int(nullable: false, identity: true), EmailAddress = c.String(), PhoneNumber = c.String(), Name = c.String(), ApplicationUserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUserId) .Index(t => t.ApplicationUserId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.MaintainenceRequests", c => new { Id = c.Int(nullable: false, identity: true), TimeAndDateOfRequest = c.DateTime(nullable: false), Request = c.String(), ApartmentId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Apartments", t => t.ApartmentId, cascadeDelete: true) .Index(t => t.ApartmentId); CreateTable( "dbo.Payments", c => new { Id = c.Int(nullable: false, identity: true), Amount = c.Decimal(nullable: false, precision: 18, scale: 2), CardNumber = c.String(), ExpirationDate = c.String(), CardCode = c.String(), FirstName = c.String(), LastName = c.String(), Address = c.String(), City = c.String(), ZipCode = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.Tenants", c => new { Id = c.Int(nullable: false, identity: true), FirstName = c.String(), LastName = c.String(), Balance = c.Decimal(nullable: false, precision: 18, scale: 2), MoveInDate = c.DateTime(nullable: false), MoveOutDate = c.DateTime(nullable: false), OccupyingApartment = c.Boolean(nullable: false), EmailAddress = c.String(), InitialPassword = c.String(), ApartmentId = c.Int(nullable: false), ApplicationUserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Apartments", t => t.ApartmentId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUserId) .Index(t => t.ApartmentId) .Index(t => t.ApplicationUserId); } public override void Down() { DropForeignKey("dbo.Tenants", "ApplicationUserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Tenants", "ApartmentId", "dbo.Apartments"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.MaintainenceRequests", "ApartmentId", "dbo.Apartments"); DropForeignKey("dbo.Apartments", "RentalPropertyId", "dbo.RentalProperties"); DropForeignKey("dbo.RentalProperties", "PropertyManagerId", "dbo.PropertyManagers"); DropForeignKey("dbo.PropertyManagers", "ApplicationUserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropIndex("dbo.Tenants", new[] { "ApplicationUserId" }); DropIndex("dbo.Tenants", new[] { "ApartmentId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.MaintainenceRequests", new[] { "ApartmentId" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.PropertyManagers", new[] { "ApplicationUserId" }); DropIndex("dbo.RentalProperties", new[] { "PropertyManagerId" }); DropIndex("dbo.Apartments", new[] { "RentalPropertyId" }); DropTable("dbo.Tenants"); DropTable("dbo.AspNetRoles"); DropTable("dbo.Payments"); DropTable("dbo.MaintainenceRequests"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.PropertyManagers"); DropTable("dbo.RentalProperties"); DropTable("dbo.Apartments"); } } }
/* * Copyright (c) 2006-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenMetaverse.Packets; namespace OpenMetaverse { /// <summary> /// Static helper functions and global variables /// </summary> public static class Helpers { /// <summary>This header flag signals that ACKs are appended to the packet</summary> public const byte MSG_APPENDED_ACKS = 0x10; /// <summary>This header flag signals that this packet has been sent before</summary> public const byte MSG_RESENT = 0x20; /// <summary>This header flags signals that an ACK is expected for this packet</summary> public const byte MSG_RELIABLE = 0x40; /// <summary>This header flag signals that the message is compressed using zerocoding</summary> public const byte MSG_ZEROCODED = 0x80; public static readonly string NewLine = Environment.NewLine; /// <summary> /// Passed to Logger.Log() to identify the severity of a log entry /// </summary> public enum LogLevel { /// <summary>No logging information will be output</summary> None, /// <summary>Non-noisy useful information, may be helpful in /// debugging a problem</summary> Info, /// <summary>A non-critical error occurred. A warning will not /// prevent the rest of the library from operating as usual, /// although it may be indicative of an underlying issue</summary> Warning, /// <summary>A critical error has occurred. Generally this will /// be followed by the network layer shutting down, although the /// stability of the library after an error is uncertain</summary> Error, /// <summary>Used for internal testing, this logging level can /// generate very noisy (long and/or repetitive) messages. Don't /// pass this to the Log() function, use DebugLog() instead. /// </summary> Debug }; /// <summary>Provide a single instance of the CultureInfo class to /// help parsing in situations where the grid assumes an en-us /// culture</summary> public static readonly System.Globalization.CultureInfo EnUsCulture = new System.Globalization.CultureInfo("en-us"); /// <summary> /// /// </summary> /// <param name="offset"></param> /// <returns></returns> public static short TEOffsetShort(float offset) { offset = Utils.Clamp(offset, -1.0f, 1.0f); offset *= 32767.0f; return (short)Math.Round(offset); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TEOffsetFloat(byte[] bytes, int pos) { float offset = (float)BitConverter.ToInt16(bytes, pos); return offset / 32767.0f; } /// <summary> /// /// </summary> /// <param name="rotation"></param> /// <returns></returns> public static short TERotationShort(float rotation) { const double TWO_PI = Math.PI * 2.0d; double remainder = Math.IEEERemainder(rotation, TWO_PI); return (short)Math.Round((remainder / TWO_PI) * 32767.0d); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TERotationFloat(byte[] bytes, int pos) { const float TWO_PI = (float)(Math.PI * 2.0d); return (float)((bytes[pos] | (bytes[pos + 1] << 8)) / 32767.0f) * TWO_PI; } public static byte TEGlowByte(float glow) { return (byte)(glow * 255.0f); } public static float TEGlowFloat(byte[] bytes, int pos) { return (float)bytes[pos] / 255.0f; } /// <summary> /// Given an X/Y location in absolute (grid-relative) terms, a region /// handle is returned along with the local X/Y location in that region /// </summary> /// <param name="globalX">The absolute X location, a number such as /// 255360.35</param> /// <param name="globalY">The absolute Y location, a number such as /// 255360.35</param> /// <param name="localX">The sim-local X position of the global X /// position, a value from 0.0 to 256.0</param> /// <param name="localY">The sim-local Y position of the global Y /// position, a value from 0.0 to 256.0</param> /// <returns>A 64-bit region handle that can be used to teleport to</returns> public static ulong GlobalPosToRegionHandle(float globalX, float globalY, out float localX, out float localY) { uint x = ((uint)globalX / 256) * 256; uint y = ((uint)globalY / 256) * 256; localX = globalX - (float)x; localY = globalY - (float)y; return Utils.UIntsToLong(x, y); } /// <summary> /// Converts a floating point number to a terse string format used for /// transmitting numbers in wearable asset files /// </summary> /// <param name="val">Floating point number to convert to a string</param> /// <returns>A terse string representation of the input number</returns> public static string FloatToTerseString(float val) { string s = string.Format("{0:.00}", val); // Trim trailing zeroes while (s[s.Length - 1] == '0') s = s.Remove(s.Length - 1, 1); // Remove superfluous decimal places after the trim if (s[s.Length - 1] == '.') s = s.Remove(s.Length - 1, 1); // Remove leading zeroes after a negative sign else if (s[0] == '-' && s[1] == '0') s = s.Remove(1, 1); // Remove leading zeroes in positive numbers else if (s[0] == '0') s = s.Remove(0, 1); return s; } /// <summary> /// Convert a variable length field (byte array) to a string, with a /// field name prepended to each line of the output /// </summary> /// <remarks>If the byte array has unprintable characters in it, a /// hex dump will be written instead</remarks> /// <param name="output">The StringBuilder object to write to</param> /// <param name="bytes">The byte array to convert to a string</param> /// <param name="fieldName">A field name to prepend to each line of output</param> internal static void FieldToString(StringBuilder output, byte[] bytes, string fieldName) { // Check for a common case if (bytes.Length == 0) return; bool printable = true; for (int i = 0; i < bytes.Length; ++i) { // Check if there are any unprintable characters in the array if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) { printable = false; break; } } if (printable) { if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } if (bytes[bytes.Length - 1] == 0x00) output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)); else output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length)); } else { for (int i = 0; i < bytes.Length; i += 16) { if (i != 0) output.Append('\n'); if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } for (int j = 0; j < 16; j++) { if ((i + j) < bytes.Length) output.Append(String.Format("{0:X2} ", bytes[i + j])); else output.Append(" "); } } } } /// <summary> /// Decode a zerocoded byte array, used to decompress packets marked /// with the zerocoded flag /// </summary> /// <remarks>Any time a zero is encountered, the next byte is a count /// of how many zeroes to expand. One zero is encoded with 0x00 0x01, /// two zeroes is 0x00 0x02, three zeroes is 0x00 0x03, etc. The /// first four bytes are copied directly to the output buffer. /// </remarks> /// <param name="src">The byte array to decode</param> /// <param name="srclen">The length of the byte array to decode. This /// would be the length of the packet up to (but not including) any /// appended ACKs</param> /// <param name="dest">The output byte array to decode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroDecode(byte[] src, int srclen, byte[] dest) { if (srclen > src.Length) throw new ArgumentException("srclen cannot be greater than src.Length"); uint zerolen = 0; int bodylen = 0; uint i = 0; try { Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen = 6; bodylen = srclen; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { for (byte j = 0; j < src[i + 1]; j++) { dest[zerolen++] = 0x00; } i++; } else { dest[zerolen++] = src[i]; } } // Copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } catch (Exception) { Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}", i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null)), LogLevel.Error); } return 0; } /// <summary> /// Encode a byte array with zerocoding. Used to compress packets marked /// with the zerocoded flag. Any zeroes in the array are compressed down /// to a single zero byte followed by a count of how many zeroes to expand /// out. A single zero becomes 0x00 0x01, two zeroes becomes 0x00 0x02, /// three zeroes becomes 0x00 0x03, etc. The first four bytes are copied /// directly to the output buffer. /// </summary> /// <param name="src">The byte array to encode</param> /// <param name="srclen">The length of the byte array to encode</param> /// <param name="dest">The output byte array to encode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroEncode(byte[] src, int srclen, byte[] dest) { uint zerolen = 0; byte zerocount = 0; Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen += 6; int bodylen; if ((src[0] & MSG_APPENDED_ACKS) == 0) { bodylen = srclen; } else { bodylen = srclen - src[srclen - 1] * 4 - 1; } uint i; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { zerocount++; if (zerocount == 0) { dest[zerolen++] = 0x00; dest[zerolen++] = 0xff; zerocount++; } } else { if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; zerocount = 0; } dest[zerolen++] = src[i]; } } if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; } // copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } /// <summary> /// Calculates the CRC (cyclic redundancy check) needed to upload inventory. /// </summary> /// <param name="creationDate">Creation date</param> /// <param name="saleType">Sale type</param> /// <param name="invType">Inventory type</param> /// <param name="type">Type</param> /// <param name="assetID">Asset ID</param> /// <param name="groupID">Group ID</param> /// <param name="salePrice">Sale price</param> /// <param name="ownerID">Owner ID</param> /// <param name="creatorID">Creator ID</param> /// <param name="itemID">Item ID</param> /// <param name="folderID">Folder ID</param> /// <param name="everyoneMask">Everyone mask (permissions)</param> /// <param name="flags">Flags</param> /// <param name="nextOwnerMask">Next owner mask (permissions)</param> /// <param name="groupMask">Group mask (permissions)</param> /// <param name="ownerMask">Owner mask (permisions)</param> /// <returns>The calculated CRC</returns> public static uint InventoryCRC(int creationDate, byte saleType, sbyte invType, sbyte type, UUID assetID, UUID groupID, int salePrice, UUID ownerID, UUID creatorID, UUID itemID, UUID folderID, uint everyoneMask, uint flags, uint nextOwnerMask, uint groupMask, uint ownerMask) { uint CRC = 0; // IDs CRC += assetID.CRC(); // AssetID CRC += folderID.CRC(); // FolderID CRC += itemID.CRC(); // ItemID // Permission stuff CRC += creatorID.CRC(); // CreatorID CRC += ownerID.CRC(); // OwnerID CRC += groupID.CRC(); // GroupID // CRC += another 4 words which always seem to be zero -- unclear if this is a UUID or what CRC += ownerMask; CRC += nextOwnerMask; CRC += everyoneMask; CRC += groupMask; // The rest of the CRC fields CRC += flags; // Flags CRC += (uint)invType; // InvType CRC += (uint)type; // Type CRC += (uint)creationDate; // CreationDate CRC += (uint)salePrice; // SalePrice CRC += (uint)((uint)saleType * 0x07073096); // SaleType return CRC; } /// <summary> /// Attempts to load a file embedded in the assembly /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName) { return GetResourceStream(resourceName, Settings.RESOURCE_DIR); } /// <summary> /// Attempts to load a file either embedded in the assembly or found in /// a given search path /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <param name="searchPath">An optional path that will be searched if /// the asset is not found embedded in the assembly</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName, string searchPath) { try { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream s = a.GetManifestResourceStream("OpenMetaverse.Resources." + resourceName); if (s != null) return s; } catch (Exception) { // Failed to load the resource from the assembly itself } try { return new System.IO.FileStream( System.IO.Path.Combine(System.IO.Path.Combine(System.Environment.CurrentDirectory, searchPath), resourceName), System.IO.FileMode.Open); } catch (Exception) { // Failed to load the resource from the given path } return null; } /// <summary> /// Converts a list of primitives to an object that can be serialized /// with the LLSD system /// </summary> /// <param name="prims">Primitives to convert to a serializable object</param> /// <returns>An object that can be serialized with LLSD</returns> public static StructuredData.LLSD PrimListToLLSD(List<Primitive> prims) { StructuredData.LLSDMap map = new OpenMetaverse.StructuredData.LLSDMap(prims.Count); for (int i = 0; i < prims.Count; i++) map.Add(prims[i].LocalID.ToString(), prims[i].GetLLSD()); return map; } /// <summary> /// Deserializes LLSD in to a list of primitives /// </summary> /// <param name="llsd">Structure holding the serialized primitive list, /// must be of the LLSDMap type</param> /// <returns>A list of deserialized primitives</returns> public static List<Primitive> LLSDToPrimList(StructuredData.LLSD llsd) { if (llsd.Type != StructuredData.LLSDType.Map) throw new ArgumentException("LLSD must be in the Map structure"); StructuredData.LLSDMap map = (StructuredData.LLSDMap)llsd; List<Primitive> prims = new List<Primitive>(map.Count); foreach (KeyValuePair<string, StructuredData.LLSD> kvp in map) { Primitive prim = Primitive.FromLLSD(kvp.Value); prim.LocalID = UInt32.Parse(kvp.Key); prims.Add(prim); } return prims; } public static AttachmentPoint StateToAttachmentPoint(uint state) { const uint ATTACHMENT_MASK = 0xF0; uint fixedState = (((byte)state & ATTACHMENT_MASK) >> 4) | (((byte)state & ~ATTACHMENT_MASK) << 4); return (AttachmentPoint)fixedState; } public static List<int> SplitBlocks(PacketBlock[] blocks, int packetOverhead) { List<int> splitPoints = new List<int>(); int size = 0; if (blocks != null && blocks.Length > 0) { splitPoints.Add(0); for (int i = 0; i < blocks.Length; i++) { size += blocks[i].Length; // If the next block will put this packet over the limit, add a split point if (i < blocks.Length - 1 && size + blocks[i + 1].Length + packetOverhead >= Settings.MAX_PACKET_SIZE) { splitPoints.Add(i + 1); size = 0; } } } return splitPoints; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Specialized; using System.Diagnostics.Contracts; namespace System.Web { // Summary: // Provides the client certificate fields issued by the client in response to // the server's request for the client's identity. public class HttpClientCertificate : NameValueCollection { // Summary: // Gets or sets the certificate issuer, in binary format. // // Returns: // The certificate issuer, expressed in binary format. public byte[] BinaryIssuer { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } // // Summary: // Gets the encoding of the certificate. // // Returns: // One of the CERT_CONTEXT.dwCertEncodingType values. extern public int CertEncoding { get; } // // Summary: // Gets a string containing the binary stream of the entire certificate content, // in ASN.1 format. // // Returns: // The client certificate. public byte[] Certificate { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } // // Summary: // Gets the unique ID for the client certificate, if provided. // // Returns: // The client certificate ID. public string Cookie { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // A set of flags that provide additional client certificate information. // // Returns: // A set of Boolean flags. extern public int Flags { get; } // // Summary: // Gets a value that indicates whether the client certificate is present. // // Returns: // true if the client certificate is present; otherwise, false. extern public bool IsPresent { get; } // // Summary: // A string that contains a list of subfield values containing information about // the certificate issuer. // // Returns: // The certificate issuer's information. public string Issuer { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // Gets a value that indicates whether the client certificate is valid. // // Returns: // true if the client certificate is valid; otherwise, false. extern public bool IsValid { get; } // // Summary: // Gets the number of bits in the digital certificate key size. For example, // 128. // // Returns: // The number of bits in the key size. extern public int KeySize { get; } // // Summary: // Gets the public key binary value from the certificate. // // Returns: // A byte array that contains the public key value. public byte[] PublicKey { get { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } } // // Summary: // Gets the number of bits in the server certificate private key. For example, // 1024. // // Returns: // The number of bits in the server certificate private key. extern public int SecretKeySize { get; } // // Summary: // Provides the certificate serial number as an ASCII representation of hexadecimal // bytes separated by hyphens. For example, 04-67-F3-02. // // Returns: // The certificate serial number. extern public string SerialNumber { get; } // // Summary: // Gets the issuer field of the server certificate. // // Returns: // The issuer field of the server certificate. public string ServerIssuer { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // Gets the subject field of the server certificate. // // Returns: // The subject field of the server certificate. public string ServerSubject { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // Gets the subject field of the client certificate. // // Returns: // The subject field of the client certificate. public string Subject { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } // // Summary: // Gets the date when the certificate becomes valid. The date varies with international // settings. // // Returns: // The date when the certificate becomes valid. extern public DateTime ValidFrom { get; } // // Summary: // Gets the certificate expiration date. // // Returns: // The certificate expiration date. extern public DateTime ValidUntil { get; } // Summary: // Returns individual client certificate fields by name. // // Parameters: // field: // The item in the collection to retrieve. // // Returns: // The value of the item specified by field. public override string Get(string field) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating two single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector2 : IEquatable<Vector2>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0). /// </summary> public static Vector2 Zero { get { return new Vector2(); } } /// <summary> /// Returns the vector (1,1). /// </summary> public static Vector2 One { get { return new Vector2(1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0). /// </summary> public static Vector2 UnitX { get { return new Vector2(1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1). /// </summary> public static Vector2 UnitY { get { return new Vector2(0.0f, 1.0f); } } #endregion Public Static Properties #region Public instance methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int hash = this.X.GetHashCode(); hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode()); return hash; } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector2 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector2; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector2)) return false; return Equals((Vector2)obj); } /// <summary> /// Returns a String representing this Vector2 instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator + " "; sb.Append("<"); sb.Append(this.X.ToString(format, formatProvider)); sb.Append(separator); sb.Append(this.Y.ToString(format, formatProvider)); sb.Append(">"); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector2.Dot(this, this); return (float)Math.Sqrt(ls); } else { float ls = X * X + Y * Y; return (float)Math.Sqrt((double)ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector2.Dot(this, this); } else { return X * X + Y * Y; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; float ls = Vector2.Dot(difference, difference); return (float)System.Math.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float ls = dx * dx + dy * dy; return (float)Math.Sqrt((double)ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; return Vector2.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; return dx * dx + dy * dy; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); return new Vector2( value.X * invNorm, value.Y * invNorm); } } /// <summary> /// Returns the reflection of a vector off a surface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 vector, Vector2 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector2.Dot(vector, normal); return vector - (2 * dot * normal); } else { float dot = vector.X * normal.X + vector.Y * normal.Y; return new Vector2( vector.X - 2.0f * dot * normal.X, vector.Y - 2.0f * dot * normal.Y); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specified min value is bigger than max value. float x = value1.X; x = (x > max.X) ? max.X : x; x = (x < min.X) ? min.X : x; float y = value1.Y; y = (y > max.Y) ? max.Y : y; y = (y < min.Y) ? min.Y : y; return new Vector2(x, y); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix3x2 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float yy2 = rotation.Y * y2; float zz2 = rotation.Z * z2; return new Vector2( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2)); } #endregion Public Static Methods #region Public operator methods // all the below methods should be inlined as they are // implemented over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 left, Vector2 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 left, Vector2 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Vector2 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Single right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Single left, Vector2 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Vector2 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Single divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return -value; } #endregion Public operator methods } }
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using System; using static Dapper.SqlMapper; namespace Flepper.QueryBuilder.DapperExtensions { public static class QueryBuilderExtensions { internal static FlepperDapperQuery AsFlepperDapperQuery(this IQueryCommand queryCommand) { if (queryCommand is FlepperDapperQuery flepperDapperQuery) return flepperDapperQuery; throw new NotSupportedException("Only instances of FlepperDapperQuery can execute this method."); } public static int Execute(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Execute(transaction, commandTimeout, commandType); } public static Task<int> ExecuteAsync(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().ExecuteAsync(transaction, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<dynamic> Query(this IQueryCommand queryCommand, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(transaction, buffered, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TFirst, TSecond, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TReturn>(this IQueryCommand queryCommand, Type[] types, Func<object[], TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(types, map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<T> Query<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query<T>(transaction, buffered, commandTimeout, commandType); } public static IEnumerable<TReturn> Query<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static IEnumerable<object> Query(this IQueryCommand queryCommand, Type type, string sql, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().Query(type, transaction, buffered, commandTimeout, commandType); } public static Task<IEnumerable<dynamic>> QueryAsync(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(transaction, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TFifth, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TSeventh, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TReturn>(this IQueryCommand queryCommand, Type[] types, Func<object[], TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(types, map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<object>> QueryAsync(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(type, transaction, commandTimeout, commandType); } public static Task<IEnumerable<TReturn>> QueryAsync<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn>(this IQueryCommand queryCommand, Func<TFirst, TSecond, TThird, TFourth, TFifth, TSixth, TReturn> map, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync(map, transaction, buffered, splitOn, commandTimeout, commandType); } public static Task<IEnumerable<T>> QueryAsync<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryAsync<T>(transaction, commandTimeout, commandType); } public static dynamic QueryFirst(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirst(transaction, commandTimeout, commandType); } public static object QueryFirst(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirst(transaction, commandTimeout, commandType); } public static T QueryFirst<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirst<T>(transaction, commandTimeout, commandType); } public static Task<object> QueryFirstAsync(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstAsync(type, transaction, commandTimeout, commandType); } public static Task<T> QueryFirstAsync<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstAsync<T>(transaction, commandTimeout, commandType); } public static T QueryFirstOrDefault<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstOrDefault<T>(transaction, commandTimeout, commandType); } public static object QueryFirstOrDefault(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstOrDefault(type, transaction, commandTimeout, commandType); } public static dynamic QueryFirstOrDefault(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstOrDefault(transaction, commandTimeout, commandType); } public static Task<object> QueryFirstOrDefaultAsync(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstOrDefaultAsync(type, transaction, commandTimeout, commandType); } public static Task<T> QueryFirstOrDefaultAsync<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryFirstOrDefaultAsync<T>(transaction, commandTimeout, commandType); } public static GridReader QueryMultiple(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryMultiple(transaction, commandTimeout, commandType); } public static Task<GridReader> QueryMultipleAsync(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QueryMultipleAsync(transaction, commandTimeout, commandType); } public static dynamic QuerySingle(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingle(transaction, commandTimeout, commandType); } public static object QuerySingle(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingle(type, transaction, commandTimeout, commandType); } public static T QuerySingle<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingle<T>(transaction, commandTimeout, commandType); } public static Task<T> QuerySingleAsync<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingleAsync<T>(transaction, commandTimeout, commandType); } public static Task<object> QuerySingleAsync(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingleAsync(type, transaction, commandTimeout, commandType); } public static T QuerySingleOrDefault<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingleOrDefault<T>(transaction, commandTimeout, commandType); } public static Task<dynamic> QuerySingleOrDefaultAsync<T>(this IQueryCommand queryCommand, Type type, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingleOrDefaultAsync(type, transaction, commandTimeout, commandType); } public static Task<T> QuerySingleOrDefaultAsync<T>(this IQueryCommand queryCommand, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) { return queryCommand.AsFlepperDapperQuery().QuerySingleOrDefaultAsync<T>(transaction, commandTimeout, commandType); } } }
using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Collections; using System.Collections.Generic; namespace Anima2D { [DisallowMultipleComponent] [CanEditMultipleObjects] [CustomEditor(typeof(SpriteMeshInstance))] public class SpriteMeshInstanceEditor : Editor { SpriteMeshInstance m_SpriteMeshInstance; SpriteMeshData m_SpriteMeshData; ReorderableList mBoneList = null; SerializedProperty m_SortingOrder; SerializedProperty m_SortingLayerID; SerializedProperty m_SpriteMeshProperty; SerializedProperty m_ColorProperty; SerializedProperty m_MaterialsProperty; SerializedProperty m_BoneTransformsProperty; int m_UndoGroup = -1; void OnEnable() { m_SpriteMeshInstance = target as SpriteMeshInstance; m_SortingOrder = serializedObject.FindProperty("m_SortingOrder"); m_SortingLayerID = serializedObject.FindProperty("m_SortingLayerID"); m_SpriteMeshProperty = serializedObject.FindProperty("m_SpriteMesh"); m_ColorProperty = serializedObject.FindProperty("m_Color"); m_MaterialsProperty = serializedObject.FindProperty("m_Materials.Array"); m_BoneTransformsProperty = serializedObject.FindProperty("m_BoneTransforms.Array"); UpgradeToMaterials(); UpdateSpriteMeshData(); SetupBoneList(); #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif } void UpgradeToMaterials() { if(Selection.transforms.Length == 1 && m_MaterialsProperty.arraySize == 0) { serializedObject.Update(); m_MaterialsProperty.InsertArrayElementAtIndex(0); m_MaterialsProperty.GetArrayElementAtIndex(0).objectReferenceValue = SpriteMeshUtils.defaultMaterial; serializedObject.ApplyModifiedProperties(); } } public void OnDisable() { if(target) { #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, false); #endif } } bool HasBindPoses() { bool hasBindPoses = false; if(m_SpriteMeshData && m_SpriteMeshData.bindPoses != null && m_SpriteMeshData.bindPoses.Length > 0) { hasBindPoses = true; } return hasBindPoses; } void SetupBoneList() { if(HasBindPoses() && m_BoneTransformsProperty.arraySize != m_SpriteMeshData.bindPoses.Length) { int oldSize = m_BoneTransformsProperty.arraySize; serializedObject.Update(); m_BoneTransformsProperty.arraySize = m_SpriteMeshData.bindPoses.Length; for(int i = oldSize; i < m_BoneTransformsProperty.arraySize; ++i) { SerializedProperty element = m_BoneTransformsProperty.GetArrayElementAtIndex(i); element.objectReferenceValue = null; } serializedObject.ApplyModifiedProperties(); } mBoneList = new ReorderableList(serializedObject,m_BoneTransformsProperty,!HasBindPoses(),true,!HasBindPoses(),!HasBindPoses()); mBoneList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { SerializedProperty boneProperty = mBoneList.serializedProperty.GetArrayElementAtIndex(index); rect.y += 1.5f; float labelWidth = 0f; if(HasBindPoses() && index < m_SpriteMeshData.bindPoses.Length) { labelWidth = EditorGUIUtility.labelWidth; EditorGUI.LabelField( new Rect(rect.x, rect.y, labelWidth, EditorGUIUtility.singleLineHeight), new GUIContent(m_SpriteMeshData.bindPoses[index].name)); } EditorGUI.BeginChangeCheck(); EditorGUI.PropertyField( new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, EditorGUIUtility.singleLineHeight), boneProperty, GUIContent.none); if(EditorGUI.EndChangeCheck()) { Transform l_NewTransform = boneProperty.objectReferenceValue as Transform; if(l_NewTransform && !l_NewTransform.GetComponent<Bone2D>()) { boneProperty.objectReferenceValue = null; } } }; mBoneList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Bones"); }; mBoneList.onSelectCallback = (ReorderableList list) => {}; } public override void OnInspectorGUI() { #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif EditorGUI.BeginChangeCheck(); serializedObject.Update(); EditorGUILayout.PropertyField(m_SpriteMeshProperty); serializedObject.ApplyModifiedProperties(); if(EditorGUI.EndChangeCheck()) { UpdateSpriteMeshData(); UpdateRenderers(); SetupBoneList(); } serializedObject.Update(); EditorGUILayout.PropertyField(m_ColorProperty); if(m_MaterialsProperty.arraySize == 0) { m_MaterialsProperty.InsertArrayElementAtIndex(0); } EditorGUILayout.PropertyField(m_MaterialsProperty.GetArrayElementAtIndex(0), new GUIContent("Material"), true, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUIExtra.SortingLayerField(new GUIContent("Sorting Layer"), m_SortingLayerID, EditorStyles.popup, EditorStyles.label); EditorGUILayout.PropertyField(m_SortingOrder, new GUIContent("Order in Layer")); EditorGUILayout.Space(); if(!HasBindPoses()) { List<Bone2D> bones = new List<Bone2D>(); EditorGUI.BeginChangeCheck(); Transform root = EditorGUILayout.ObjectField("Set bones",null,typeof(Transform),true) as Transform; if(EditorGUI.EndChangeCheck()) { if(root) { root.GetComponentsInChildren<Bone2D>(bones); } Undo.RegisterCompleteObjectUndo(m_SpriteMeshInstance,"set bones"); m_BoneTransformsProperty.arraySize = bones.Count; for(int i = 0; i < bones.Count; ++i) { m_BoneTransformsProperty.GetArrayElementAtIndex(i).objectReferenceValue = bones[i].transform; } UpdateRenderers(); } } EditorGUI.BeginChangeCheck(); if(mBoneList != null) { mBoneList.DoLayoutList(); } serializedObject.ApplyModifiedProperties(); if(EditorGUI.EndChangeCheck()) { UpdateRenderers(); } if(m_SpriteMeshInstance.spriteMesh) { if(SpriteMeshUtils.HasNullBones(m_SpriteMeshInstance)) { EditorGUILayout.HelpBox("Warning:\nBone list contains null references.", MessageType.Warning); } if(m_SpriteMeshInstance.spriteMesh.sharedMesh.bindposes.Length != m_SpriteMeshInstance.bones.Count) { EditorGUILayout.HelpBox("Warning:\nNumber of SpriteMesh Bind Poses and number of Bones does not match.", MessageType.Warning); } } } void UpdateSpriteMeshData() { m_SpriteMeshData = null; if(m_SpriteMeshProperty != null && m_SpriteMeshProperty.objectReferenceValue) { m_SpriteMeshData = SpriteMeshUtils.LoadSpriteMeshData(m_SpriteMeshProperty.objectReferenceValue as SpriteMesh); } } void UpdateRenderers() { m_UndoGroup = Undo.GetCurrentGroup(); EditorApplication.delayCall += DoUpdateRenderer; } void DoUpdateRenderer() { SpriteMeshUtils.UpdateRenderer(m_SpriteMeshInstance); #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif Undo.CollapseUndoOperations(m_UndoGroup); SceneView.RepaintAll(); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Threading; using Microsoft.PythonTools.Infrastructure; using Microsoft.Win32; namespace Microsoft.PythonTools { /// <summary> /// Provides information about a detected change to the registry. /// </summary> class RegistryChangedEventArgs : EventArgs { /// <summary> /// Creates a new event object. /// </summary> /// <param name="key">The key that was originally provided.</param> public RegistryChangedEventArgs(RegistryHive hive, RegistryView view, string key, bool isRecursive, bool isValueChange, bool isKeyChange, object tag) { Hive = hive; View = view; Key = key; IsRecursive = isRecursive; IsValueChanged = isValueChange; IsKeyChanged = isKeyChange; Tag = tag; } /// <summary> /// The registry hive originally provided to the watcher. /// </summary> public RegistryHive Hive { get; private set; } /// <summary> /// The registry view originally provided to the watcher. /// </summary> public RegistryView View { get; private set; } /// <summary> /// The key that was originally provided to the watcher. This may not /// have changed to trigger the event. /// </summary> public string Key { get; private set; } /// <summary> /// True if the key and all its subkeys and values were being watched. /// </summary> public bool IsRecursive { get; private set; } /// <summary> /// True if the key was being watched for value changes. This may be /// true even if it was not a value change that triggered the event. /// </summary> public bool IsValueChanged { get; private set; } /// <summary> /// True if the key was being watched for key changes. This may be /// true even if it was not a key change that triggered the event. /// </summary> public bool IsKeyChanged { get; private set; } /// <summary> /// The tag that was originally provided to the watcher. /// </summary> public object Tag { get; private set; } /// <summary> /// Set to True to prevent the watcher from being run again. This is /// False by default. /// </summary> public bool CancelWatcher { get; set; } } /// <summary> /// Represents the method that will handle a registry change event. /// </summary> delegate void RegistryChangedEventHandler(object sender, RegistryChangedEventArgs e); /// <summary> /// Provides notifications when registry values are modified. /// </summary> class RegistryWatcher : IDisposable { readonly object _eventsLock = new object(); readonly List<WatchEntry> _entries; List<RegistryWatcher> _extraWatchers; readonly AutoResetEvent _itemAdded; bool _shutdown; readonly Thread _thread; static Lazy<RegistryWatcher> _instance = new Lazy<RegistryWatcher>(() => new RegistryWatcher()); public static RegistryWatcher Instance { get { return _instance.Value; } } /// <summary> /// Creates a new registry watcher. Each watcher will consume one CPU /// thread for every 64 objects. /// </summary> public RegistryWatcher() { _entries = new List<WatchEntry>(); _entries.Add(new WatchEntry()); _itemAdded = _entries[0].EventHandle; _thread = new Thread(Worker); _thread.IsBackground = true; _thread.Start(this); } public void Dispose() { if (_shutdown == false) { _shutdown = true; _itemAdded.Set(); var extras = _extraWatchers; _extraWatchers = null; if (extras != null) { foreach (var watcher in extras) { watcher.Dispose(); } } } } /// <summary> /// Starts listening for notifications in the specified registry key. /// /// Each part of the key must be provided separately so that the watcher /// can open its own handle. /// </summary> /// <param name="hive">The hive to watch</param> /// <param name="view">The view to watch</param> /// <param name="key">The key to watch</param> /// <param name="handler">The event handler to invoke</param> /// <param name="recursive">True to watch all subkeys as well</param> /// <param name="notifyValueChange"> /// True to notify if a value is added, removed or updated. /// </param> /// <param name="notifyKeyChange"> /// True to notify if a subkey is added or removed. /// </param> /// <param name="tag"> /// An arbitrary identifier to include with any raised events. /// </param> /// <exception cref="ArgumentException"> /// The specified registry key does not exist. /// </exception> /// <returns>An opaque token that can be pased to Remove.</returns> /// <remarks> /// This is a thin layer over <see cref="TryAdd"/> that will throw an /// exception when the return value would be null. /// </remarks> public object Add( RegistryHive hive, RegistryView view, string key, RegistryChangedEventHandler handler, bool recursive = false, bool notifyValueChange = true, bool notifyKeyChange = true, object tag = null ) { var res = TryAdd(hive, view, key, handler, recursive, notifyValueChange, notifyKeyChange, tag); if (res == null) { throw new ArgumentException("Key does not exist"); } return res; } /// <summary> /// Starts listening for notifications in the specified registry key. /// /// Each part of the key must be provided separately so that the watcher /// can open its own handle. /// </summary> /// <param name="hive">The hive to watch</param> /// <param name="view">The view to watch</param> /// <param name="key">The key to watch</param> /// <param name="handler">The event handler to invoke</param> /// <param name="recursive">True to watch all subkeys as well</param> /// <param name="notifyValueChange"> /// True to notify if a value is added, removed or updated. /// </param> /// <param name="notifyKeyChange"> /// True to notify if a subkey is added or removed. /// </param> /// <param name="tag"> /// An arbitrary identifier to include with any raised events. /// </param> /// <returns> /// An opaque token that can be pased to Remove, or null if the watcher /// could not be added. /// </returns> public object TryAdd( RegistryHive hive, RegistryView view, string key, RegistryChangedEventHandler handler, bool recursive = false, bool notifyValueChange = true, bool notifyKeyChange = true, object tag = null ) { if (key == null) { throw new ArgumentNullException("key"); } if (handler == null) { throw new ArgumentNullException("handler"); } if (!(notifyValueChange | notifyKeyChange)) { throw new InvalidOperationException("Must wait for at least one type of change"); } var args = new RegistryChangedEventArgs( hive, view, key, recursive, notifyValueChange, notifyKeyChange, tag ); int currentWatcher = -1; RegistryWatcher watcher; bool needNewThread; var token = TryAddInternal(handler, args, out needNewThread); while (needNewThread) { if (_extraWatchers == null) { _extraWatchers = new List<RegistryWatcher>(); } currentWatcher += 1; if (currentWatcher >= _extraWatchers.Count) { watcher = new RegistryWatcher(); _extraWatchers.Add(watcher); } else { watcher = _extraWatchers[currentWatcher]; } token = watcher.TryAddInternal(handler, args, out needNewThread); } return token; } private object TryAddInternal( RegistryChangedEventHandler handler, RegistryChangedEventArgs args, out bool needNewThread ) { WatchEntry newEntry; needNewThread = false; lock (_eventsLock) { if (_entries.Count >= MAXIMUM_WAIT_OBJECTS) { needNewThread = true; return null; } newEntry = WatchEntry.TryCreate(handler, args); if (newEntry == null) { return null; } _entries.Add(newEntry); } _itemAdded.Set(); return newEntry; } /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(object token) { if (token == null) { throw new ArgumentNullException("token"); } var entry = token as WatchEntry; if (entry == null) { return false; } lock (_eventsLock) { if (_entries.Remove(entry)) { entry.Unregister(); return true; } } var extras = _extraWatchers; if (extras != null) { foreach (var watcher in extras) { if (watcher.Remove(token)) { return true; } } } return false; } private static void Worker(object param) { var self = (RegistryWatcher)param; WaitHandle[] handles; WatchEntry[] entries; int triggeredHandle; while (!self._shutdown) { lock (self._eventsLock) { entries = self._entries.ToArray(); handles = entries.Select(e => e.EventHandle).ToArray(); } triggeredHandle = WaitHandle.WaitAny(handles); if (triggeredHandle >= 0 && triggeredHandle < entries.Length && entries[triggeredHandle] != null) { if (!entries[triggeredHandle].Invoke(self)) { self.Remove(entries[triggeredHandle]); } } } } private sealed class WatchEntry : IDisposable { private readonly AutoResetEvent _eventHandle; private readonly RegistryKey _key; private readonly RegistryChangedEventHandler _callback; private readonly RegistryChangedEventArgs _args; private bool _registered; /// <summary> /// Creates a WatchEntry that has an event but does not watch a /// registry key. All functions become no-ops, but /// <see cref="EventHandle"/> is valid. /// </summary> public WatchEntry() { _eventHandle = new AutoResetEvent(false); } private WatchEntry( RegistryKey key, RegistryChangedEventHandler callback, RegistryChangedEventArgs args ) { _key = key; _eventHandle = new AutoResetEvent(false); _callback = callback; _args = args; Register(); } public static WatchEntry TryCreate(RegistryChangedEventHandler callback, RegistryChangedEventArgs args) { RegistryKey key; using (var baseKey = RegistryKey.OpenBaseKey(args.Hive, args.View)) { key = baseKey.OpenSubKey(args.Key, RegistryKeyPermissionCheck.Default, RegistryRights.Notify); } if (key == null) { return null; } return new WatchEntry(key, callback, args); } public void Dispose() { _eventHandle.Dispose(); if (_key != null) { _key.Close(); } } public AutoResetEvent EventHandle { get { return _eventHandle; } } public void Register() { if (_key == null) { return; } RegNotifyChangeKeyValue( _key, _eventHandle, _args.IsRecursive, (_args.IsValueChanged ? RegNotifyChange.Value : 0) | (_args.IsKeyChanged ? RegNotifyChange.Name : 0)); _registered = true; } public void Unregister() { if (_key == null) { return; } if (_registered) { lock (this) { _registered = false; _key.Close(); } } } /// <summary> /// Invokes the associated event handler. /// </summary> /// <returns>True if the watcher will be run again; false if the /// entry has been closed and can be removed.</returns> public bool Invoke(RegistryWatcher sender) { if (_key == null) { // Returns true so we don't try and remove null entries from // the list. return true; } if (!_registered) { return false; } _callback(sender, _args); if (_args.CancelWatcher) { Unregister(); return false; } lock (this) { // only re-register if we haven't been closed if (_registered) { try { Register(); } catch (Win32Exception ex) { // If we fail to re-register (probably because the // key has been deleted), there's nothing that can // be done. Fail if we're debugging, otherwise just // continue without registering the watcher again. Debug.Fail("Error registering registry watcher: " + ex.ToString()); _registered = false; } } } return true; } } const int MAXIMUM_WAIT_OBJECTS = 64; [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")] [DllImport("advapi32", EntryPoint = "RegNotifyChangeKeyValue", CallingConvention = CallingConvention.Winapi)] private static extern int _RegNotifyChangeKeyValue(SafeHandle hKey, bool bWatchSubtree, RegNotifyChange dwNotifyFilter, SafeHandle hEvent, bool fAsynchronous); [Flags] enum RegNotifyChange : uint { Name = 1, // REG_NOTIFY_CHANGE_NAME Attributes = 2, // REG_NOTIFY_CHANGE_ATTRIBUTES Value = 4, // REG_NOTIFY_CHANGE_LAST_SET Security = 8, // REG_NOTIFY_CHANGE_SECURITY ThreadAgnostic = 0x10000000 // REG_NOTIFY_THREAD_AGNOSTIC (Windows 8 only) } static void RegNotifyChangeKeyValue(RegistryKey key, WaitHandle notifyEvent, bool recursive = false, RegNotifyChange filter = RegNotifyChange.Value) { int error = _RegNotifyChangeKeyValue( key.Handle, recursive, filter, notifyEvent.SafeWaitHandle, true); if (error != 0) { throw new Win32Exception(error); } } private static RegistryHive ParseRegistryKey(string key, out string subkey) { int firstPart = key.IndexOf('\\'); if (firstPart < 0 || !key.StartsWithOrdinal("HKEY", ignoreCase: true)) { throw new ArgumentException("Invalid registry key: " + key, "key"); } var hive = key.Remove(firstPart); subkey = key.Substring(firstPart + 1); if (hive.Equals("HKEY_CURRENT_USER", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.CurrentUser; } else if (hive.Equals("HKEY_LOCAL_MACHINE", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.LocalMachine; } else if (hive.Equals("HKEY_CLASSES_ROOT", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.ClassesRoot; } else if (hive.Equals("HKEY_USERS", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.Users; } else if (hive.Equals("HKEY_CURRENT_CONFIG", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.CurrentConfig; } else if (hive.Equals("HKEY_PERFORMANCE_DATA", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.PerformanceData; } else if (hive.Equals("HKEY_DYN_DATA", StringComparison.OrdinalIgnoreCase)) { return RegistryHive.DynData; } throw new ArgumentException("Invalid registry key: " + key, "key"); } internal static bool GetRegistryKeyLocation(RegistryKey key, out RegistryHive hive, out RegistryView view, out string subkey) { if (key != null) { hive = ParseRegistryKey(key.Name, out subkey); view = key.View; return true; } else { hive = RegistryHive.CurrentUser; view = RegistryView.Default; subkey = null; return false; } } } }
// Based on https://github.com/makotech222/Ultralight-Stride3d_Integration // - See that repo's Readme for instructions #define TRACE_Touch #define TRACE_Keyboard #if Ultralight using System; using System.IO; using System.Linq; using LionFire.Dependencies; using Microsoft.Extensions.Logging; using Stride.Core; using Stride.Engine; using Stride.Graphics; using Stride.Rendering.Sprites; using Stride.UI.Controls; using LogLevel = Microsoft.Extensions.Logging.LogLevel; using System.Collections.Concurrent; using System.Reflection; using Microsoft.Extensions.Hosting; using ImpromptuNinjas.UltralightSharp.Safe; using MouseButton = ImpromptuNinjas.UltralightSharp.Enums.MouseButton; using MouseEventType = ImpromptuNinjas.UltralightSharp.Enums.MouseEventType; using ImpromptuString = ImpromptuNinjas.UltralightSharp.String; using LionFire.Stride3D.Input; using System.Diagnostics; using Keys = Stride.Input.Keys; using LiveSharp; using MediatR; using System.Threading.Tasks; using System.Threading; #if LiveSharp using LionFire.LiveSharp; #endif using LionFire.Threading; using LionFire.Dispatching; using Stride.Audio; namespace LionFire.Stride3D.UI { // TODO: Analyze for threadsafety. // Docs: // The Ultralight API is not thread-safe at this time-- calling the API from multiple threads is not supported and will lead // to subtle issues / application instability. The library does not need to run on the main thread though-- you can create // the Renderer on another thread and make all calls to the API on that thread. public class UltralightUIScriptDispatcher #if LiveSharp : INotificationHandler<UpdatedMethodNotification> , INotificationHandler<UpdatedResourceNotification> #endif { #if LiveSharp Task INotificationHandler<UpdatedMethodNotification>.Handle(UpdatedMethodNotification notification, CancellationToken cancellationToken) => UltralightUIScript.Instance?.OnUpdatedMethodNotification(notification); Task INotificationHandler<UpdatedResourceNotification>.Handle(UpdatedResourceNotification notification, CancellationToken cancellationToken) => UltralightUIScript.Instance?.OnUpdatedResourceNotification(notification); #endif } /// <remarks> /// Sets up Ultralight to draws to Grid > Image "img" /// Override Start() and Update() and call the base methods /// </remarks> public class UltralightUIScript : SyncScript { #region (Static) internal static UltralightUIScript Instance { get; set; } // TODO - avoid the static /// <summary> /// Should be only one renderer per Game. /// </summary> protected static ImpromptuNinjas.UltralightSharp.Safe.Renderer renderer; #endregion #region Parameters [DataMemberIgnore] public Keys? ToggleKey { get; set; } = Keys.F10; public Keys? ExternalBrowserKey { get; set; } = Keys.F9; public Keys? RefreshBrowserKey { get; set; } = Keys.F5; public bool ShouldPassToBrowser(Keys key) => key switch { Keys.F5 => false, Keys.F9 => false, Keys.F10 => false, _ => true }; /// <summary> /// Full path to directory containing html files. /// </summary> [DataMemberIgnore] public string AssetDirectory { get; set; } = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "wwwroot"); /// <summary> /// File path to main html file. Should be inside the AssetDirectory folder. /// </summary> [DataMemberIgnore] //public string LoadingUrl { get; set; } = "http://google.com"; // file:///index.html public string LoadingUrl { get; set; } = "file:///loading.html"; [DataMemberIgnore] //public string StartUrl { get; set; } = "http://google.com"; public string StartUrl { get; set; } = "http://localhost:7150/"; #endregion #region Dependencies private ILogger Logger { get; set; } private IHostApplicationLifetime HostApplicationLifetime { get; } private IDispatcher Dispatcher => StrideDispatcher.Instance; //private IDispatcher Dispatcher => dispatcher ??= DependencyContext.Current?.GetService<IDispatcher>(); //private IDispatcher dispatcher ; #endregion #region Relationships /// <summary> /// View created by Ultralight. /// </summary> protected ImpromptuNinjas.UltralightSharp.Safe.View View { get; set; } protected ImpromptuNinjas.UltralightSharp.Safe.Session session; protected Texture texture; protected SpriteFromTexture sprite; #region ImageElement private UIComponent UIComponent => Entity.Get<UIComponent>(); private ImageElement ImageElement { get => imageElement; set { imageElement = value; UpdateImageVisibility(); } } private ImageElement imageElement; private void UpdateImageVisibility() { if (imageElement != null) { imageElement.Visibility = visible ? Stride.UI.Visibility.Visible : Stride.UI.Visibility.Hidden; imageElement.CanBeHitByUser = visible; } if (UIComponent?.Page?.RootElement != null) { if (UIComponent.Page.RootElement is Stride.UI.Panels.Grid grid) { grid.CanBeHitByUser = visible; } } } #endregion #endregion //Sound tReloadSound; //SoundInstance reloadSound; #region Construction and Destruction public UltralightUIScript() { Instance ??= this; Logger = DependencyContext.Current?.GetService<ILogger<UltralightUIScript>>() ?? (ILogger)Logging.Null.NullLogger.Instance; HostApplicationLifetime = DependencyContext.Current?.GetService<IHostApplicationLifetime>(); } //void InitSound() //{ // try // { // Sound tReloadSound = Content.Load<Sound>("Audio/Tiny Button Push-SoundBible.com-513260752 [notification]"); // reloadSound = tReloadSound.CreateInstance(); // reloadSound.Volume = 0.25f; // reloadSound.Play(); // } // catch (Exception ex) // { // Logger.LogError(ex, "Failed to init sound"); // } //} protected void InitUltralight() { Ultralight.SetLogger(new Logger { LogMessage = LoggerCallback }); using var cfg = new Config(); var cachePath = Path.Combine(AssetDirectory, "Cache"); cfg.SetCachePath(cachePath); var resourcePath = Path.Combine(AssetDirectory, "resources"); cfg.SetResourcePath(resourcePath); cfg.SetUseGpuRenderer(false); cfg.SetEnableImages(true); cfg.SetEnableJavaScript(true); AppCore.EnablePlatformFontLoader(); AppCore.EnablePlatformFileSystem(AssetDirectory); renderer = new Renderer(cfg); } ~UltralightUIScript() { View?.Dispose(); renderer?.Dispose(); } #endregion #region State #region Settings public bool AutoReload { get; set; } = true; #endregion protected uint width; protected uint height; private bool loadedLoadingUrl = false; private bool IsWebServerAvailable => HostApplicationLifetime.ApplicationStarted.IsCancellationRequested; private bool startedLoadingStartUrl = false; private bool javascriptTestComplete = false; #region Visible [DataMemberIgnore] public bool Visible { get => visible; set { visible = value; UpdateImageVisibility(); } } private bool visible = true; #endregion ComponentUI pendingInputEvents = new ComponentUI(); #endregion #region Event Handlers #region MediatR public bool IsWebUI(Type type) => type.FullName.Contains("Blazor") || type.BaseType == typeof(Microsoft.AspNetCore.Components.ComponentBase); #if LiveSharp internal Task OnUpdatedMethodNotification(UpdatedMethodNotification notification) { Logger.LogInformation($"OnUpdatedMethodNotification -- TEMP " + notification.UpdatedMethod.DeclaringType.BaseType.BaseType.FullName); if (AutoReload) { if (IsWebUI(notification.UpdatedMethod.DeclaringType)) { Logger.LogInformation($"AutoReloading due to method change: {notification.UpdatedMethod.DeclaringType.FullName}.{notification.UpdatedMethod.MethodIdentifier}"); return Dispatcher.BeginInvoke(() => { //try //{ // reloadSound.Play(); //} //catch (Exception ex) //{ // Logger.LogError(ex, "Error playing sound"); //} View.Reload(); }); } else { Logger.LogDebug($"Ignorning non-web UI code change in {notification.UpdatedMethod.DeclaringType}"); } } return Task.CompletedTask; } internal Task OnUpdatedResourceNotification(UpdatedResourceNotification notification) { var path = notification?.Path; if (path != null && (path.EndsWith(".css")) ) { Dispatcher.BeginInvoke(() => { View?.Reload(); }); } return Task.CompletedTask; } #endif #endregion private void OnPrivateWebServerStarted() { if (startedLoadingStartUrl) return; startedLoadingStartUrl = true; Logger.LogInformation($"Loading: {StartUrl}"); View.LoadUrl(StartUrl); } #region Event Handlers: Stride UI #region Mouse / Touch private void ImageElement_MouseOverStateChanged(object sender, Stride.UI.PropertyChangedArgs<Stride.UI.MouseOverState> e) { Logger.LogDebug($"MouseOverStateChanged {e.NewValue}"); } private void ImageElement_TouchEnter(object sender, Stride.UI.TouchEventArgs e) { Logger.LogDebug("TouchEnter " + e.ScreenPosition); } private void ImageElement_TouchDown(object sender, Stride.UI.TouchEventArgs e) { #if TRACE_Touch Logger.LogTrace($"TouchDown {e.ScreenPosition} ({(int)(e.ScreenPosition.X * width)},{(int)(e.ScreenPosition.Y * height)}) {(Input.Mouse.DownButtons.Any() ? Input.Mouse.DownButtons.Select(m => m.ToString()).Aggregate((x, y) => $"{x},{y}") : "")}"); #endif pendingInputEvents.MouseEvents.Enqueue(new MouseEvent(MouseEventType.MouseDown, (int)(e.ScreenPosition.X * width), (int)(e.ScreenPosition.Y * height), MouseButton.Left)); e.Handled = false; } private void ImageElement_TouchUp(object sender, Stride.UI.TouchEventArgs e) { #if TRACE_Touch Logger.LogTrace($"TouchUp {e.ScreenPosition} ({(int)(e.ScreenPosition.X * width)},{(int)(e.ScreenPosition.Y * height)})"); #endif pendingInputEvents.MouseEvents.Enqueue(new MouseEvent(MouseEventType.MouseUp, (int)(e.ScreenPosition.X * width), (int)(e.ScreenPosition.Y * height), MouseButton.Left)); } #endregion #region Keyboard private void OnKeysPressed() { foreach (var key in Input.PressedKeys) { if (!ShouldPassToBrowser(key)) continue; // DEPRECATE the char approach, if virtual key-code works string keyString = null; switch (key) { case Keys.D0: case Keys.D1: case Keys.D2: case Keys.D3: case Keys.D4: case Keys.D5: case Keys.D6: case Keys.D7: case Keys.D8: case Keys.D9: keyString = key.ToString()[1].ToString(); break; case Keys.A: case Keys.B: case Keys.C: case Keys.D: case Keys.E: case Keys.F: case Keys.G: case Keys.H: case Keys.I: case Keys.J: case Keys.K: case Keys.L: case Keys.M: case Keys.N: case Keys.O: case Keys.P: case Keys.Q: case Keys.R: case Keys.S: case Keys.T: case Keys.U: case Keys.V: case Keys.W: case Keys.X: case Keys.Y: case Keys.Z: keyString = key.ToString().ToLowerInvariant(); break; default: break; } if (keyString != null) { unsafe { #if TRACE_Keyboard Logger.LogTrace($"Key pressed: {key}"); #endif pendingInputEvents.KeyboardEvents.Enqueue( new KeyEvent(ImpromptuNinjas.UltralightSharp.Enums.KeyEventType.Char, 0, 0, 0, ImpromptuString.Create(keyString), ImpromptuString.Create(keyString), false, false, false)); } continue; } int nativeCode = key.ToWindowsVirtualKeyCode(); // TODO: Other platforms if (nativeCode != 0) { unsafe { #if TRACE_Keyboard Logger.LogTrace($"'{key}' Key pressed. (code: {nativeCode})"); #endif // TODO from Ultralight docs: // You'll need to generate a key identifier from the virtual key code // when synthesizing events. This function is provided in KeyEvent.h //GetKeyIdentifierFromVirtualKeyCode(evt.virtual_key_code, evt.key_identifier); //In addition to key presses / key releases, you'll need to pass in the actual text generated. (For example, pressing the A key should generate the character 'a'). //KeyEvent evt; //evt.type = KeyEvent::kType_Char; //evt.text = "a"; //evt.unmodified_text = "a"; // If not available, set to same as evt.text var empty = ImpromptuString.Create(""); pendingInputEvents.KeyboardEvents.Enqueue(new KeyEvent(ImpromptuNinjas.UltralightSharp.Enums.KeyEventType.RawKeyDown, 0, nativeCode, 0, ImpromptuString.Create(""), empty, false, false, false)); } } else { Logger.LogWarning($"Ignoring key because native key code is unknown: {key}"); } } } #endregion #endregion #endregion #region Stride Component Overrides public override void Start() { base.Start(); //InitSound(); #region UIComponent var uiComponent = UIComponent; if (uiComponent == null) { Logger.LogError($"{this.GetType().FullName} script must be installed on the same Entity as UIComponent"); return; } #endregion #region ImageElement //var gridElement = uiComponent.Page.RootElement.VisualChildren.FirstOrDefault() as Stride.UI.Panels.Grid; imageElement = uiComponent.Page.RootElement.VisualChildren.OfType<ImageElement>().FirstOrDefault() as ImageElement; if (imageElement == null) { Logger.LogError($"Failed to find image element. The first ImageElement in VisualChildren will be used."); return; } #region Events imageElement.TouchUp += ImageElement_TouchUp; imageElement.TouchDown += ImageElement_TouchDown; imageElement.TouchEnter += ImageElement_TouchEnter; imageElement.MouseOverStateChanged += ImageElement_MouseOverStateChanged; #endregion Logger.LogDebug($"Drawing to image: {imageElement.Name}"); #endregion width = (uint)uiComponent.Resolution.X; height = (uint)uiComponent.Resolution.Y; #region Ultralight setup texture = Texture.New2D(this.GraphicsDevice, (int)width, (int)height, Stride.Graphics.PixelFormat.B8G8R8A8_UNorm_SRgb, TextureFlags.ShaderResource | TextureFlags.RenderTarget); sprite = new SpriteFromTexture(); if (renderer == null) { InitUltralight(); } session = new Session(renderer, false, ""); View = new View(renderer, width, height, true, session); View.SetFinishLoadingCallback((data, caller, frameId, isMainFrame, url) => { loadedLoadingUrl = true; Logger.LogInformation($"Finished loading: {url}"); }, default); #endregion #region LoadUrl if (!IsWebServerAvailable) { Logger.LogInformation("Web server not available yet. Loading LoadingUrl."); View.LoadUrl(LoadingUrl); //Task.Run(async () => //{ // //await HostApplicationLifetime.ApplicationStarted; // while(!IsWebServerAvailable) // { // Logger.LogInformation("Waiting for web server to start... "); // await Task.Delay(250); // } // Logger.LogInformation("Waiting for web server to start...done."); // OnPrivateWebServerStarted(); //}); } else { Logger.LogInformation("Web server already available. (Skipping LoadingUrl.)"); loadedLoadingUrl = true; OnPrivateWebServerStarted(); } #endregion } public override void Update() { if (renderer == null) return; if (!loadedLoadingUrl) { renderer.Update(); renderer.Render(); if (!loadedLoadingUrl) { return; } } if (!startedLoadingStartUrl && IsWebServerAvailable) { OnPrivateWebServerStarted(); } if (!javascriptTestComplete) { DoJavascriptTest(); } FireInputs(pendingInputEvents); if (RefreshBrowserKey.HasValue && Input.PressedKeys.Contains(RefreshBrowserKey.Value)) { Logger.LogInformation("Refreshing"); View.Reload(); } if (ToggleKey.HasValue && Input.PressedKeys.Contains(ToggleKey.Value)) { Visible ^= true; } if (ExternalBrowserKey.HasValue && Input.PressedKeys.Contains(ExternalBrowserKey.Value)) { try { var psi = new ProcessStartInfo { FileName = StartUrl, UseShellExecute = true }; Process.Start(psi); } catch (System.ComponentModel.Win32Exception noBrowser) { if (noBrowser.ErrorCode == -2147467259) { Logger.LogError(noBrowser.Message); } } catch (System.Exception other) { Logger.LogError(other.Message); } } if (Input.HasPressedKeys) { OnKeysPressed(); } renderer.Update(); renderer.Render(); var surface = View.GetSurface(); var bitmap = surface.GetBitmap(); var pixels = bitmap.LockPixels(); DataPointer dataPointer = new DataPointer((IntPtr)pixels, (int)bitmap.GetHeight() * (int)bitmap.GetWidth() * (int)bitmap.GetBpp()); texture.SetData(this.Game.GraphicsContext.CommandList, dataPointer); sprite.Texture = texture; imageElement.Source = sprite; bitmap.UnlockPixels(); bitmap.Dispose(); void FireInputs(ComponentUI ui) { while (pendingInputEvents.MouseEvents.TryDequeue(out var e)) { View.FireMouseEvent(e); } while (pendingInputEvents.ScrollEvents.TryDequeue(out var e)) { View.FireScrollEvent(e); } while (pendingInputEvents.KeyboardEvents.TryDequeue(out var e)) { View.FireKeyEvent(e); } } void DoJavascriptTest() { javascriptTestComplete = true; try { var result = View.EvaluateScript($"console.log('hi ' + (2+2)); 2+2;", out string exception); Logger.LogInformation("Javascript returned: " + result); if (!string.IsNullOrEmpty(exception)) { Logger.LogError("Javascript returned exception: " + exception); } } catch (Exception ex) { Logger.LogError(ex, "Javascript threw exception"); } } } #endregion #region Classes public class ComponentUI { public ConcurrentQueue<MouseEvent> MouseEvents { get; set; } = new ConcurrentQueue<MouseEvent>(); public ConcurrentQueue<KeyEvent> KeyboardEvents { get; set; } = new ConcurrentQueue<KeyEvent>(); public ConcurrentQueue<ScrollEvent> ScrollEvents { get; set; } = new ConcurrentQueue<ScrollEvent>(); } #endregion #region Logging private LoggerLogMessageCallback LoggerCallback => new LoggerLogMessageCallback((logLevel, msg) => { var microsoftLogLevel = logLevel switch { ImpromptuNinjas.UltralightSharp.Enums.LogLevel.Error => LogLevel.Error, ImpromptuNinjas.UltralightSharp.Enums.LogLevel.Warning => LogLevel.Warning, ImpromptuNinjas.UltralightSharp.Enums.LogLevel.Info => LogLevel.Information, _ => LogLevel.Error, }; Logger.Log(microsoftLogLevel, msg); }); #endregion } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ActionGroupsOperations. /// </summary> public static partial class ActionGroupsOperationsExtensions { /// <summary> /// Create a new action group or update an existing one. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='actionGroup'> /// The action group to create or use for the update. /// </param> public static ActionGroupResource CreateOrUpdate(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup) { return operations.CreateOrUpdateAsync(resourceGroupName, actionGroupName, actionGroup).GetAwaiter().GetResult(); } /// <summary> /// Create a new action group or update an existing one. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='actionGroup'> /// The action group to create or use for the update. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ActionGroupResource> CreateOrUpdateAsync(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, ActionGroupResource actionGroup, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, actionGroupName, actionGroup, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get an action group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> public static ActionGroupResource Get(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName) { return operations.GetAsync(resourceGroupName, actionGroupName).GetAwaiter().GetResult(); } /// <summary> /// Get an action group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ActionGroupResource> GetAsync(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, actionGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete an action group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> public static void Delete(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName) { operations.DeleteAsync(resourceGroupName, actionGroupName).GetAwaiter().GetResult(); } /// <summary> /// Delete an action group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, actionGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Get a list of all action groups in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IEnumerable<ActionGroupResource> ListBySubscriptionId(this IActionGroupsOperations operations) { return operations.ListBySubscriptionIdAsync().GetAwaiter().GetResult(); } /// <summary> /// Get a list of all action groups in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<ActionGroupResource>> ListBySubscriptionIdAsync(this IActionGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionIdWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get a list of all action groups in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IEnumerable<ActionGroupResource> ListByResourceGroup(this IActionGroupsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Get a list of all action groups in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<ActionGroupResource>> ListByResourceGroupAsync(this IActionGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Enable a receiver in an action group. This changes the receiver's status /// from Disabled to Enabled. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='receiverName'> /// The name of the receiver to resubscribe. /// </param> public static void EnableReceiver(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, string receiverName) { operations.EnableReceiverAsync(resourceGroupName, actionGroupName, receiverName).GetAwaiter().GetResult(); } /// <summary> /// Enable a receiver in an action group. This changes the receiver's status /// from Disabled to Enabled. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='actionGroupName'> /// The name of the action group. /// </param> /// <param name='receiverName'> /// The name of the receiver to resubscribe. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task EnableReceiverAsync(this IActionGroupsOperations operations, string resourceGroupName, string actionGroupName, string receiverName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.EnableReceiverWithHttpMessagesAsync(resourceGroupName, actionGroupName, receiverName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
//----------------------------------------------------------------------- // <copyright file="GvrAudioSource.cs" company="Google Inc."> // Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using UnityEngine.Audio; using System.Collections; #pragma warning disable 0618 // Ignore GvrAudio* deprecation /// GVR audio source component that enhances AudioSource to provide advanced spatial audio features. #if UNITY_2017_1_OR_NEWER [System.Obsolete("Please upgrade to Resonance Audio (https://developers.google.com/resonance-audio/migrate).")] #endif // UNITY_2017_1_OR_NEWER [AddComponentMenu("GoogleVR/Audio/GvrAudioSource")] public class GvrAudioSource : MonoBehaviour { /// Denotes whether the room effects should be bypassed. public bool bypassRoomEffects = false; /// Directivity pattern shaping factor. public float directivityAlpha = 0.0f; /// Directivity pattern order. public float directivitySharpness = 1.0f; /// Listener directivity pattern shaping factor. public float listenerDirectivityAlpha = 0.0f; /// Listener directivity pattern order. public float listenerDirectivitySharpness = 1.0f; /// Input gain in decibels. public float gainDb = 0.0f; /// Occlusion effect toggle. public bool occlusionEnabled = false; /// Play source on awake. public bool playOnAwake = true; /// The default AudioClip to play. public AudioClip clip { get { return sourceClip; } set { sourceClip = value; if (audioSource != null) { audioSource.clip = sourceClip; } } } [SerializeField] private AudioClip sourceClip = null; /// Is the clip playing right now (Read Only)? public bool isPlaying { get { if (audioSource != null) { return audioSource.isPlaying; } return false; } } /// Is the audio clip looping? public bool loop { get { return sourceLoop; } set { sourceLoop = value; if (audioSource != null) { audioSource.loop = sourceLoop; } } } [SerializeField] private bool sourceLoop = false; /// Un- / Mutes the source. Mute sets the volume=0, Un-Mute restore the original volume. public bool mute { get { return sourceMute; } set { sourceMute = value; if (audioSource != null) { audioSource.mute = sourceMute; } } } [SerializeField] private bool sourceMute = false; /// The pitch of the audio source. public float pitch { get { return sourcePitch; } set { sourcePitch = value; if (audioSource != null) { audioSource.pitch = sourcePitch; } } } [SerializeField] [Range(-3.0f, 3.0f)] private float sourcePitch = 1.0f; /// Sets the priority of the audio source. public int priority { get { return sourcePriority; } set { sourcePriority = value; if (audioSource != null) { audioSource.priority = sourcePriority; } } } [SerializeField] [Range(0, 256)] private int sourcePriority = 128; /// Sets how much this source is affected by 3D spatialization calculations (attenuation, doppler). public float spatialBlend { get { return sourceSpatialBlend; } set { sourceSpatialBlend = value; if (audioSource != null) { audioSource.spatialBlend = sourceSpatialBlend; } } } [SerializeField] [Range(0.0f, 1.0f)] private float sourceSpatialBlend = 1.0f; /// Sets the Doppler scale for this audio source. public float dopplerLevel { get { return sourceDopplerLevel; } set { sourceDopplerLevel = value; if (audioSource != null) { audioSource.dopplerLevel = sourceDopplerLevel; } } } [SerializeField] [Range(0.0f, 5.0f)] private float sourceDopplerLevel = 1.0f; /// Sets the spread angle (in degrees) in 3D space. public float spread { get { return sourceSpread; } set { sourceSpread = value; if (audioSource != null) { audioSource.spread = sourceSpread; } } } [SerializeField] [Range(0.0f, 360.0f)] private float sourceSpread = 0.0f; /// Playback position in seconds. public float time { get { if (audioSource != null) { return audioSource.time; } return 0.0f; } set { if (audioSource != null) { audioSource.time = value; } } } /// Playback position in PCM samples. public int timeSamples { get { if (audioSource != null) { return audioSource.timeSamples; } return 0; } set { if (audioSource != null) { audioSource.timeSamples = value; } } } /// The volume of the audio source (0.0 to 1.0). public float volume { get { return sourceVolume; } set { sourceVolume = value; if (audioSource != null) { audioSource.volume = sourceVolume; } } } [SerializeField] [Range(0.0f, 1.0f)] private float sourceVolume = 1.0f; /// Volume rolloff model with respect to the distance. public AudioRolloffMode rolloffMode { get { return sourceRolloffMode; } set { sourceRolloffMode = value; if (audioSource != null) { audioSource.rolloffMode = sourceRolloffMode; if (rolloffMode == AudioRolloffMode.Custom) { // Custom rolloff is not supported, set the curve for no distance attenuation. audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, AnimationCurve.Linear(sourceMinDistance, 1.0f, sourceMaxDistance, 1.0f)); } } } } [SerializeField] private AudioRolloffMode sourceRolloffMode = AudioRolloffMode.Logarithmic; /// MaxDistance is the distance a sound stops attenuating at. public float maxDistance { get { return sourceMaxDistance; } set { sourceMaxDistance = Mathf.Clamp(value, sourceMinDistance + GvrAudio.distanceEpsilon, GvrAudio.maxDistanceLimit); if (audioSource != null) { audioSource.maxDistance = sourceMaxDistance; } } } [SerializeField] private float sourceMaxDistance = 500.0f; /// Within the Min distance the GvrAudioSource will cease to grow louder in volume. public float minDistance { get { return sourceMinDistance; } set { sourceMinDistance = Mathf.Clamp(value, 0.0f, GvrAudio.minDistanceLimit); if (audioSource != null) { audioSource.minDistance = sourceMinDistance; } } } [SerializeField] private float sourceMinDistance = 1.0f; /// Binaural (HRTF) rendering toggle. [SerializeField] private bool hrtfEnabled = true; // Unity audio source attached to the game object. [SerializeField] private AudioSource audioSource = null; // Unique source id. private int id = -1; // Current occlusion value; private float currentOcclusion = 0.0f; // Next occlusion update time in seconds. private float nextOcclusionUpdate = 0.0f; // Denotes whether the source is currently paused or not. private bool isPaused = false; void Awake() { #if UNITY_EDITOR && UNITY_2017_1_OR_NEWER Debug.LogWarningFormat(gameObject, "Game object '{0}' uses deprecated {1} component.\nPlease upgrade to Resonance Audio ({2}).", name, GetType().Name, "https://developers.google.com/resonance-audio/migrate"); #endif // UNITY_EDITOR && UNITY_2017_1_OR_NEWER if (audioSource == null) { // Ensure the audio source gets created once. audioSource = gameObject.AddComponent<AudioSource>(); } audioSource.enabled = false; audioSource.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave; audioSource.playOnAwake = false; audioSource.bypassReverbZones = true; #if UNITY_5_5_OR_NEWER audioSource.spatializePostEffects = true; #endif // UNITY_5_5_OR_NEWER OnValidate(); // Route the source output to |GvrAudioMixer|. AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer); if (mixer != null) { audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0]; } else { Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK " + "Unity package is imported properly."); } } void OnEnable() { audioSource.enabled = true; if (playOnAwake && !isPlaying && InitializeSource()) { Play(); } } void Start() { if (playOnAwake && !isPlaying) { Play(); } } void OnDisable() { Stop(); audioSource.enabled = false; } void OnDestroy() { Destroy(audioSource); } void OnApplicationPause(bool pauseStatus) { if (pauseStatus) { Pause(); } else { UnPause(); } } void Update() { // Update occlusion state. if (!occlusionEnabled) { currentOcclusion = 0.0f; } else if (Time.time >= nextOcclusionUpdate) { nextOcclusionUpdate = Time.time + GvrAudio.occlusionDetectionInterval; currentOcclusion = GvrAudio.ComputeOcclusion(transform); } // Update source. if (!isPlaying && !isPaused) { Stop(); } else { audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.Gain, GvrAudio.ConvertAmplitudeFromDb(gainDb)); audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.MinDistance, sourceMinDistance); GvrAudio.UpdateAudioSource(id, this, currentOcclusion); } } /// Provides a block of the currently playing source's output data. /// /// @note The array given in samples will be filled with the requested data before spatialization. public void GetOutputData(float[] samples, int channel) { if (audioSource != null) { audioSource.GetOutputData(samples, channel); } } /// Provides a block of the currently playing audio source's spectrum data. /// /// @note The array given in samples will be filled with the requested data before spatialization. public void GetSpectrumData(float[] samples, int channel, FFTWindow window) { if (audioSource != null) { audioSource.GetSpectrumData(samples, channel, window); } } /// Pauses playing the clip. public void Pause() { if (audioSource != null) { isPaused = true; audioSource.Pause(); } } /// Plays the clip. public void Play() { if (audioSource != null && InitializeSource()) { audioSource.Play(); isPaused = false; } else { Debug.LogWarning("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays the clip with a delay specified in seconds. public void PlayDelayed(float delay) { if (audioSource != null && InitializeSource()) { audioSource.PlayDelayed(delay); isPaused = false; } else { Debug.LogWarning("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays an AudioClip. public void PlayOneShot(AudioClip clip) { PlayOneShot(clip, 1.0f); } /// Plays an AudioClip, and scales its volume. public void PlayOneShot(AudioClip clip, float volume) { if (audioSource != null && InitializeSource()) { audioSource.PlayOneShot(clip, volume); isPaused = false; } else { Debug.LogWarning("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads /// from. public void PlayScheduled(double time) { if (audioSource != null && InitializeSource()) { audioSource.PlayScheduled(time); isPaused = false; } else { Debug.LogWarning("GVR Audio source not initialized. Audio playback not supported " + "until after Awake() and OnEnable(). Try calling from Start() instead."); } } /// Changes the time at which a sound that has already been scheduled to play will end. public void SetScheduledEndTime(double time) { if (audioSource != null) { audioSource.SetScheduledEndTime(time); } } /// Changes the time at which a sound that has already been scheduled to play will start. public void SetScheduledStartTime(double time) { if (audioSource != null) { audioSource.SetScheduledStartTime(time); } } /// Stops playing the clip. public void Stop() { if (audioSource != null) { audioSource.Stop(); ShutdownSource(); isPaused = true; } } /// Unpauses the paused playback. public void UnPause() { if (audioSource != null) { audioSource.UnPause(); isPaused = false; } } // Initializes the source. private bool InitializeSource() { if (id < 0) { id = GvrAudio.CreateAudioSource(hrtfEnabled); if (id >= 0) { GvrAudio.UpdateAudioSource(id, this, currentOcclusion); audioSource.spatialize = true; audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.Type, (float)GvrAudio.SpatializerType.Source); audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.Gain, GvrAudio.ConvertAmplitudeFromDb(gainDb)); audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.MinDistance, sourceMinDistance); audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.ZeroOutput, 0.0f); // Source id must be set after all the spatializer parameters, to ensure that the source is // properly initialized before processing. audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.Id, (float)id); } } return id >= 0; } // Shuts down the source. private void ShutdownSource() { if (id >= 0) { audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.Id, -1.0f); // Ensure that the output is zeroed after shutdown. audioSource.SetSpatializerFloat((int)GvrAudio.SpatializerData.ZeroOutput, 1.0f); audioSource.spatialize = false; GvrAudio.DestroyAudioSource(id); id = -1; } } void OnDidApplyAnimationProperties() { OnValidate(); } void OnValidate() { clip = sourceClip; loop = sourceLoop; mute = sourceMute; pitch = sourcePitch; priority = sourcePriority; spatialBlend = sourceSpatialBlend; volume = sourceVolume; dopplerLevel = sourceDopplerLevel; spread = sourceSpread; minDistance = sourceMinDistance; maxDistance = sourceMaxDistance; rolloffMode = sourceRolloffMode; } void OnDrawGizmosSelected() { // Draw listener directivity gizmo. // Note that this is a very suboptimal way of finding the component, to be used in Unity Editor // only, should not be used to access the component in run time. GvrAudioListener listener = FindObjectOfType<GvrAudioListener>(); if (listener != null) { Gizmos.color = GvrAudio.listenerDirectivityColor; DrawDirectivityGizmo(listener.transform, listenerDirectivityAlpha, listenerDirectivitySharpness, 180); } // Draw source directivity gizmo. Gizmos.color = GvrAudio.sourceDirectivityColor; DrawDirectivityGizmo(transform, directivityAlpha, directivitySharpness, 180); } // Draws a 3D gizmo in the Scene View that shows the selected directivity pattern. private void DrawDirectivityGizmo(Transform target, float alpha, float sharpness, int resolution) { Vector2[] points = GvrAudio.Generate2dPolarPattern(alpha, sharpness, resolution); // Compute |vertices| from the polar pattern |points|. int numVertices = resolution + 1; Vector3[] vertices = new Vector3[numVertices]; vertices[0] = Vector3.zero; for (int i = 0; i < points.Length; ++i) { vertices[i + 1] = new Vector3(points[i].x, 0.0f, points[i].y); } // Generate |triangles| from |vertices|. Two triangles per each sweep to avoid backface culling. int[] triangles = new int[6 * numVertices]; for (int i = 0; i < numVertices - 1; ++i) { int index = 6 * i; if (i < numVertices - 2) { triangles[index] = 0; triangles[index + 1] = i + 1; triangles[index + 2] = i + 2; } else { // Last vertex is connected back to the first for the last triangle. triangles[index] = 0; triangles[index + 1] = numVertices - 1; triangles[index + 2] = 1; } // The second triangle facing the opposite direction. triangles[index + 3] = triangles[index]; triangles[index + 4] = triangles[index + 2]; triangles[index + 5] = triangles[index + 1]; } // Construct a new mesh for the gizmo. Mesh directivityGizmoMesh = new Mesh(); directivityGizmoMesh.hideFlags = HideFlags.DontSaveInEditor; directivityGizmoMesh.vertices = vertices; directivityGizmoMesh.triangles = triangles; directivityGizmoMesh.RecalculateNormals(); // Draw the mesh. Vector3 scale = 2.0f * Mathf.Max(target.lossyScale.x, target.lossyScale.z) * Vector3.one; Gizmos.DrawMesh(directivityGizmoMesh, target.position, target.rotation, scale); } } #pragma warning restore 0618 // Restore warnings
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the routes /// for your subscription. /// </summary> public partial interface IRouteOperations { /// <summary> /// Set the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be added to. /// </param> /// <param name='parameters'> /// The parameters necessary to add a route table to the provided /// subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> AddRouteTableToSubnetAsync(string vnetName, string subnetName, AddRouteTableToSubnetParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be added to. /// </param> /// <param name='parameters'> /// The parameters necessary to add a route table to the provided /// subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginAddRouteTableToSubnetAsync(string vnetName, string subnetName, AddRouteTableToSubnetParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create the specified route table for this subscription. /// </summary> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginCreateRouteTableAsync(CreateRouteTableParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginDeleteRouteAsync(string routeTableName, string routeName, CancellationToken cancellationToken); /// <summary> /// Delete the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginDeleteRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Remove the route table from the provided subnet in the provided /// virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be removed from. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginRemoveRouteTableFromSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginSetRouteAsync(string routeTableName, string routeName, SetRouteParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create the specified route table for this subscription. /// </summary> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> CreateRouteTableAsync(CreateRouteTableParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DeleteRouteAsync(string routeTableName, string routeName, CancellationToken cancellationToken); /// <summary> /// Delete the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DeleteRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Get the effective route table for the provided network interface in /// this subscription. /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleinstanceName'> /// The name of the role instance. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetEffectiveRouteTableResponse> GetEffectiveRouteTableForNetworkInterfaceAsync(string serviceName, string deploymentName, string roleinstanceName, string networkInterfaceName, CancellationToken cancellationToken); /// <summary> /// Get the effective route table for the provided role instance in /// this subscription. /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='roleinstanceName'> /// The name of the role instance. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetEffectiveRouteTableResponse> GetEffectiveRouteTableForRoleInstanceAsync(string serviceName, string deploymentName, string roleinstanceName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table in this subscription to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableResponse> GetRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableForSubnetResponse> GetRouteTableForSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table in this subscription to retrieve. /// </param> /// <param name='detailLevel'> /// The amount of detail about the requested route table that will be /// returned. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableResponse> GetRouteTableWithDetailsAsync(string routeTableName, string detailLevel, CancellationToken cancellationToken); /// <summary> /// List the existing route tables for this subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<ListRouteTablesResponse> ListRouteTablesAsync(CancellationToken cancellationToken); /// <summary> /// Remove the route table from the provided subnet in the provided /// virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be removed from. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> RemoveRouteTableFromSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> SetRouteAsync(string routeTableName, string routeName, SetRouteParameters parameters, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE4.1 hardware instructions via intrinsics /// </summary> public static class Sse41 { public static bool IsSupported { get { return false; } } /// <summary> /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) /// </summary> public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8) /// </summary> public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8) /// </summary> public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw new NotImplementedException(); } /// <summary> /// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8) /// </summary> public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// </summary> public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask) /// </summary> public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask) /// </summary> public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw new NotImplementedException(); } /// <summary> /// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask) /// </summary> public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_ceil_ps (__m128 a) /// </summary> public static Vector128<float> Ceiling(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// __m128d _mm_ceil_pd (__m128d a) /// </summary> public static Vector128<double> Ceiling(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) /// </summary> public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b) /// </summary> public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi8_epi16 (__m128i a) /// </summary> public static Vector128<short> ConvertToShort(Vector128<sbyte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu8_epi16 (__m128i a) /// </summary> public static Vector128<short> ConvertToShort(Vector128<byte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi8_epi32 (__m128i a) /// </summary> public static Vector128<int> ConvertToInt(Vector128<sbyte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu8_epi32 (__m128i a) /// </summary> public static Vector128<int> ConvertToInt(Vector128<byte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi16_epi32 (__m128i a) /// </summary> public static Vector128<int> ConvertToInt(Vector128<short> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu16_epi32 (__m128i a) /// </summary> public static Vector128<int> ConvertToInt(Vector128<ushort> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi8_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<sbyte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu8_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<byte> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi16_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<short> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu16_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<ushort> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepi32_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<int> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_cvtepu32_epi64 (__m128i a) /// </summary> public static Vector128<long> ConvertToLong(Vector128<uint> value) { throw new NotImplementedException(); } /// <summary> /// int _mm_extract_epi8 (__m128i a, const int imm8) /// </summary> public static sbyte ExtractSbyte<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// int _mm_extract_epi8 (__m128i a, const int imm8) /// </summary> public static byte ExtractByte<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// int _mm_extract_epi32 (__m128i a, const int imm8) /// </summary> public static int ExtractInt<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// int _mm_extract_epi32 (__m128i a, const int imm8) /// </summary> public static uint ExtractUint<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) /// </summary> public static long ExtractLong<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __int64 _mm_extract_epi64 (__m128i a, const int imm8) /// </summary> public static ulong ExtractUlong<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// int _mm_extract_ps (__m128 a, const int imm8) /// </summary> public static float ExtractFloat<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_floor_ps (__m128 a) /// </summary> public static Vector128<float> Floor(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// __m128d _mm_floor_pd (__m128d a) /// </summary> public static Vector128<double> Floor(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) /// </summary> public static Vector128<T> InsertSbyte<T>(Vector128<T> value, sbyte data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8) /// </summary> public static Vector128<T> InsertByte<T>(Vector128<T> value, byte data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) /// </summary> public static Vector128<T> InsertInt<T>(Vector128<T> value, int data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) /// </summary> public static Vector128<T> InsertUint<T>(Vector128<T> value, uint data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) /// </summary> public static Vector128<T> InsertLong<T>(Vector128<T> value, long data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8) /// </summary> public static Vector128<T> InsertUlong<T>(Vector128<T> value, ulong data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8) /// </summary> public static Vector128<T> InsertFloat<T>(Vector128<T> value, float data, byte index) where T : struct { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_max_epi8 (__m128i a, __m128i b) /// </summary> public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_max_epu16 (__m128i a, __m128i b) /// </summary> public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_max_epi32 (__m128i a, __m128i b) /// </summary> public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_max_epu32 (__m128i a, __m128i b) /// </summary> public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_min_epi8 (__m128i a, __m128i b) /// </summary> public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_min_epu16 (__m128i a, __m128i b) /// </summary> public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_min_epi32 (__m128i a, __m128i b) /// </summary> public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_min_epu32 (__m128i a, __m128i b) /// </summary> public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_minpos_epu16 (__m128i a) /// </summary> public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8) /// </summary> public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_mul_epi32 (__m128i a, __m128i b) /// </summary> public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b) /// </summary> public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_packus_epi32 (__m128i a, __m128i b) /// </summary> public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } /// <summary> /// __m128 _mm_round_ps (__m128 a, int rounding) /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC /// </summary> public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC /// </summary> public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC /// </summary> public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC /// </summary> public static Vector128<float> RoundToZero(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_CUR_DIRECTION /// </summary> public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw new NotImplementedException(); } /// <summary> /// __m128d _mm_round_pd (__m128d a, int rounding) /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC /// </summary> public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC /// </summary> public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC /// </summary> public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC /// </summary> public static Vector128<double> RoundToZero(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// _MM_FROUND_CUR_DIRECTION /// </summary> public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<sbyte> LoadAlignedNonTemporal(sbyte* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<byte> LoadAlignedNonTemporal(byte* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<short> LoadAlignedNonTemporal(short* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<ushort> LoadAlignedNonTemporal(ushort* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<int> LoadAlignedNonTemporal(int* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<uint> LoadAlignedNonTemporal(uint* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<long> LoadAlignedNonTemporal(long* address) { throw new NotImplementedException(); } /// <summary> /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr) /// </summary> public static unsafe Vector128<ulong> LoadAlignedNonTemporal(ulong* address) { throw new NotImplementedException(); } /// <summary> /// int _mm_test_all_ones (__m128i a) /// </summary> public static bool TestAllOnes(Vector128<sbyte> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<byte> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<short> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<ushort> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<int> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<uint> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<long> value) { throw new NotImplementedException(); } public static bool TestAllOnes(Vector128<ulong> value) { throw new NotImplementedException(); } /// <summary> /// int _mm_test_all_zeros (__m128i a, __m128i mask) /// </summary> public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } /// <summary> /// int _mm_testc_si128 (__m128i a, __m128i b) /// </summary> public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } /// <summary> /// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask) /// </summary> public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } /// <summary> /// int _mm_testnzc_si128 (__m128i a, __m128i b) /// </summary> public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } /// <summary> /// int _mm_testz_si128 (__m128i a, __m128i b) /// </summary> public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); } public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using System.Security; using System.Linq; namespace System.Runtime.Serialization { #if uapaot public sealed class EnumDataContract : DataContract #else internal sealed class EnumDataContract : DataContract #endif { private EnumDataContractCriticalHelper _helper; public EnumDataContract() : base(new EnumDataContractCriticalHelper()) { _helper = base.Helper as EnumDataContractCriticalHelper; } public XmlQualifiedName BaseContractName { get; set; } internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type)) { _helper = base.Helper as EnumDataContractCriticalHelper; } public List<DataMember> Members { get { return _helper.Members; } set { _helper.Members = value; } } public List<long> Values { get { return _helper.Values; } set { _helper.Values = value; } } public bool IsFlags { get { return _helper.IsFlags; } set { _helper.IsFlags = value; } } public bool IsULong { get { return _helper.IsULong; } set { _helper.IsULong = value; } } public XmlDictionaryString[] ChildElementNames { get { return _helper.ChildElementNames; } set { _helper.ChildElementNames = value; } } internal override bool CanContainReferences { get { return false; } } private class EnumDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Dictionary<Type, XmlQualifiedName> s_typeToName; private static Dictionary<XmlQualifiedName, Type> s_nameToType; private List<DataMember> _members; private List<long> _values; private bool _isULong; private bool _isFlags; private bool _hasDataContract; private XmlDictionaryString[] _childElementNames; static EnumDataContractCriticalHelper() { s_typeToName = new Dictionary<Type, XmlQualifiedName>(); s_nameToType = new Dictionary<XmlQualifiedName, Type>(); Add(typeof(sbyte), "byte"); Add(typeof(byte), "unsignedByte"); Add(typeof(short), "short"); Add(typeof(ushort), "unsignedShort"); Add(typeof(int), "int"); Add(typeof(uint), "unsignedInt"); Add(typeof(long), "long"); Add(typeof(ulong), "unsignedLong"); } internal static void Add(Type type, string localName) { XmlQualifiedName stableName = CreateQualifiedName(localName, Globals.SchemaNamespace); s_typeToName.Add(type, stableName); s_nameToType.Add(stableName, type); } internal EnumDataContractCriticalHelper() { IsValueType = true; } internal EnumDataContractCriticalHelper(Type type) : base(type) { this.StableName = DataContract.GetStableName(type, out _hasDataContract); Type baseType = Enum.GetUnderlyingType(type); ImportBaseType(baseType); IsFlags = type.IsDefined(Globals.TypeOfFlagsAttribute, false); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); _childElementNames = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) _childElementNames[i] = dictionary.Add(Members[i].Name); DataContractAttribute dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { if (dataContractAttribute.IsReference) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.EnumTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, false), type); } } } internal List<DataMember> Members { get { return _members; } set { _members = value; } } internal List<long> Values { get { return _values; } set { _values = value; } } internal bool IsFlags { get { return _isFlags; } set { _isFlags = value; } } internal bool IsULong { get { return _isULong; } set { _isULong = value; } } internal XmlDictionaryString[] ChildElementNames { get { return _childElementNames; } set { _childElementNames = value; } } private void ImportBaseType(Type baseType) { _isULong = (baseType == Globals.TypeOfULong); } private void ImportDataMembers() { Type type = this.UnderlyingType; FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); Dictionary<string, DataMember> memberValuesTable = new Dictionary<string, DataMember>(); List<DataMember> tempMembers = new List<DataMember>(fields.Length); List<long> tempValues = new List<long>(fields.Length); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; bool enumMemberValid = false; if (_hasDataContract) { object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0]; DataMember memberContract = new DataMember(field); if (memberAttribute.IsValueSetExplicitly) { if (memberAttribute.Value == null || memberAttribute.Value.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Value; } else memberContract.Name = field.Name; ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable); enumMemberValid = true; } object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray(); if (dataMemberAttributes != null && dataMemberAttributes.Length > 0) ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); } else { if (!field.IsNotSerialized) { DataMember memberContract = new DataMember(field); memberContract.Name = field.Name; ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable); enumMemberValid = true; } } if (enumMemberValid) { object enumValue = field.GetValue(null); if (_isULong) tempValues.Add((long)Convert.ToUInt64(enumValue, null)); else tempValues.Add(Convert.ToInt64(enumValue, null)); } } Interlocked.MemoryBarrier(); _members = tempMembers; _values = tempValues; } } internal void WriteEnumValue(XmlWriterDelegator writer, object value) { long longValue = IsULong ? (long)Convert.ToUInt64(value, null) : Convert.ToInt64(value, null); for (int i = 0; i < Values.Count; i++) { if (longValue == Values[i]) { writer.WriteString(ChildElementNames[i].Value); return; } } if (IsFlags) { int zeroIndex = -1; bool noneWritten = true; for (int i = 0; i < Values.Count; i++) { long current = Values[i]; if (current == 0) { zeroIndex = i; continue; } if (longValue == 0) break; if ((current & longValue) == current) { if (noneWritten) noneWritten = false; else writer.WriteString(DictionaryGlobals.Space.Value); writer.WriteString(ChildElementNames[i].Value); longValue &= ~current; } } // enforce that enum value was completely parsed if (longValue != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); if (noneWritten && zeroIndex >= 0) writer.WriteString(ChildElementNames[zeroIndex].Value); } else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); } internal object ReadEnumValue(XmlReaderDelegator reader) { string stringValue = reader.ReadElementContentAsString(); long longValue = 0; int i = 0; if (IsFlags) { // Skip initial spaces for (; i < stringValue.Length; i++) if (stringValue[i] != ' ') break; // Read space-delimited values int startIndex = i; int count = 0; for (; i < stringValue.Length; i++) { if (stringValue[i] == ' ') { count = i - startIndex; if (count > 0) longValue |= ReadEnumValue(stringValue, startIndex, count); for (++i; i < stringValue.Length; i++) if (stringValue[i] != ' ') break; startIndex = i; if (i == stringValue.Length) break; } } count = i - startIndex; if (count > 0) longValue |= ReadEnumValue(stringValue, startIndex, count); } else { if (stringValue.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnRead, stringValue, DataContract.GetClrTypeFullName(UnderlyingType)))); longValue = ReadEnumValue(stringValue, 0, stringValue.Length); } if (IsULong) return Enum.ToObject(UnderlyingType, (object)(ulong)longValue); return Enum.ToObject(UnderlyingType, (object)longValue); } private long ReadEnumValue(string value, int index, int count) { for (int i = 0; i < Members.Count; i++) { string memberName = Members[i].Name; if (memberName.Length == count && String.CompareOrdinal(value, index, memberName, 0, count) == 0) { return Values[i]; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType)))); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { WriteEnumValue(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object obj = ReadEnumValue(xmlReader); if (context != null) context.AddNewObject(obj); return obj; } } }
//----------------------------------------------------------------------- // <copyright file="SerializationNodeDataWriter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Stratus.OdinSerializer { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; /// <summary> /// Not yet documented. /// </summary> public class SerializationNodeDataWriter : BaseDataWriter { private List<SerializationNode> nodes; private Dictionary<Type, Delegate> primitiveTypeWriters; /// <summary> /// Not yet documented. /// </summary> public List<SerializationNode> Nodes { get { if (this.nodes == null) { this.nodes = new List<SerializationNode>(); } return this.nodes; } set { if (value == null) { throw new ArgumentNullException(); } this.nodes = value; } } /// <summary> /// Not yet documented. /// </summary> public SerializationNodeDataWriter(SerializationContext context) : base(null, context) { this.primitiveTypeWriters = new Dictionary<Type, Delegate>() { { typeof(char), (Action<string, char>)this.WriteChar }, { typeof(sbyte), (Action<string, sbyte>)this.WriteSByte }, { typeof(short), (Action<string, short>)this.WriteInt16 }, { typeof(int), (Action<string, int>)this.WriteInt32 }, { typeof(long), (Action<string, long>)this.WriteInt64 }, { typeof(byte), (Action<string, byte>)this.WriteByte }, { typeof(ushort), (Action<string, ushort>)this.WriteUInt16 }, { typeof(uint), (Action<string, uint>)this.WriteUInt32 }, { typeof(ulong), (Action<string, ulong>)this.WriteUInt64 }, { typeof(decimal), (Action<string, decimal>)this.WriteDecimal }, { typeof(bool), (Action<string, bool>)this.WriteBoolean }, { typeof(float), (Action<string, float>)this.WriteSingle }, { typeof(double), (Action<string, double>)this.WriteDouble }, { typeof(Guid), (Action<string, Guid>)this.WriteGuid } }; } /// <summary> /// Not yet documented. /// </summary> public override Stream Stream { get { throw new NotSupportedException("This data writer has no stream."); } set { throw new NotSupportedException("This data writer has no stream."); } } /// <summary> /// Begins an array node of the given length. /// </summary> /// <param name="length">The length of the array to come.</param> /// <exception cref="System.NotImplementedException"></exception> public override void BeginArrayNode(long length) { this.Nodes.Add(new SerializationNode() { Name = string.Empty, Entry = EntryType.StartOfArray, Data = length.ToString(CultureInfo.InvariantCulture) }); this.PushArray(); } /// <summary> /// Not yet documented. /// </summary> public override void BeginReferenceNode(string name, Type type, int id) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.StartOfNode, Data = type != null ? (id.ToString(CultureInfo.InvariantCulture) + SerializationNodeDataReaderWriterConfig.NodeIdSeparator + this.Context.Binder.BindToName(type, this.Context.Config.DebugContext)) : id.ToString(CultureInfo.InvariantCulture) }); this.PushNode(name, id, type); } /// <summary> /// Not yet documented. /// </summary> public override void BeginStructNode(string name, Type type) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.StartOfNode, Data = type != null ? this.Context.Binder.BindToName(type, this.Context.Config.DebugContext) : "" }); this.PushNode(name, -1, type); } /// <summary> /// Not yet documented. /// </summary> public override void Dispose() { this.nodes = null; } /// <summary> /// Not yet documented. /// </summary> public override void EndArrayNode() { this.PopArray(); this.Nodes.Add(new SerializationNode() { Name = string.Empty, Entry = EntryType.EndOfArray, Data = string.Empty }); } /// <summary> /// Not yet documented. /// </summary> public override void EndNode(string name) { this.PopNode(name); this.Nodes.Add(new SerializationNode() { Name = string.Empty, Entry = EntryType.EndOfNode, Data = string.Empty }); } /// <summary> /// Not yet documented. /// </summary> public override void PrepareNewSerializationSession() { base.PrepareNewSerializationSession(); } /// <summary> /// Not yet documented. /// </summary> public override void WriteBoolean(string name, bool value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Boolean, Data = value ? "true" : "false" }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteByte(string name, byte value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteChar(string name, char value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.String, Data = value.ToString(CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteDecimal(string name, decimal value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.FloatingPoint, Data = value.ToString("G", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteSingle(string name, float value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.FloatingPoint, Data = value.ToString("R", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteDouble(string name, double value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.FloatingPoint, Data = value.ToString("R", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteExternalReference(string name, Guid guid) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.ExternalReferenceByGuid, Data = guid.ToString("N", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteExternalReference(string name, string id) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.ExternalReferenceByString, Data = id }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteExternalReference(string name, int index) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.ExternalReferenceByIndex, Data = index.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteGuid(string name, Guid value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Guid, Data = value.ToString("N", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteInt16(string name, short value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteInt32(string name, int value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteInt64(string name, long value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteInternalReference(string name, int id) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.InternalReference, Data = id.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteNull(string name) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Null, Data = string.Empty }); } /// <summary> /// Not yet documented. /// </summary> public override void WritePrimitiveArray<T>(T[] array) { if (FormatterUtilities.IsPrimitiveArrayType(typeof(T)) == false) { throw new ArgumentException("Type " + typeof(T).Name + " is not a valid primitive array type."); } if (typeof(T) == typeof(byte)) { string hex = ProperBitConverter.BytesToHexString((byte[])(object)array); this.Nodes.Add(new SerializationNode() { Name = string.Empty, Entry = EntryType.PrimitiveArray, Data = hex }); } else { this.Nodes.Add(new SerializationNode() { Name = string.Empty, Entry = EntryType.PrimitiveArray, Data = array.LongLength.ToString(CultureInfo.InvariantCulture) }); this.PushArray(); Action<string, T> writer = (Action<string, T>)this.primitiveTypeWriters[typeof(T)]; for (int i = 0; i < array.Length; i++) { writer(string.Empty, array[i]); } this.EndArrayNode(); } } /// <summary> /// Not yet documented. /// </summary> public override void WriteSByte(string name, sbyte value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteString(string name, string value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.String, Data = value }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteUInt16(string name, ushort value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteUInt32(string name, uint value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void WriteUInt64(string name, ulong value) { this.Nodes.Add(new SerializationNode() { Name = name, Entry = EntryType.Integer, Data = value.ToString("D", CultureInfo.InvariantCulture) }); } /// <summary> /// Not yet documented. /// </summary> public override void FlushToStream() { // Do nothing } public override string GetDataDump() { var sb = new System.Text.StringBuilder(); sb.Append("Nodes: \n\n"); for (int i = 0; i < this.nodes.Count; i++) { var node = this.nodes[i]; sb.AppendLine(" - Name: " + node.Name); sb.AppendLine(" Entry: " + (int)node.Entry); sb.AppendLine(" Data: " + node.Data); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace DarkMultiPlayer { public class DebugWindow { public bool display = false; private bool safeDisplay = false; private bool initialized = false; private bool isWindowLocked = false; private static DebugWindow singleton; //private parts private bool displayFast; private bool displayVectors; private bool displayNTP; private bool displayConnectionQueue; private bool displayDynamicTickStats; private bool displayRequestedRates; private bool displayProfilerStatistics; private string vectorText = ""; private string ntpText = ""; private string connectionText = ""; private string dynamicTickText = ""; private string requestedRateText = ""; private string profilerText = ""; private float lastUpdateTime; //GUI Layout private Rect windowRect; private Rect moveRect; private GUILayoutOption[] layoutOptions; private GUILayoutOption[] textAreaOptions; private GUIStyle windowStyle; private GUIStyle buttonStyle; private GUIStyle labelStyle; //const private const float WINDOW_HEIGHT = 400; private const float WINDOW_WIDTH = 350; private const float DISPLAY_UPDATE_INTERVAL = .2f; public static DebugWindow fetch { get { return singleton; } } private void InitGUI() { //Setup GUI stuff windowRect = new Rect(Screen.width - (WINDOW_WIDTH + 50), (Screen.height / 2f) - (WINDOW_HEIGHT / 2f), WINDOW_WIDTH, WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); layoutOptions = new GUILayoutOption[4]; layoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH); layoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH); layoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT); layoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT); windowStyle = new GUIStyle(GUI.skin.window); buttonStyle = new GUIStyle(GUI.skin.button); textAreaOptions = new GUILayoutOption[1]; textAreaOptions[0] = GUILayout.ExpandWidth(true); labelStyle = new GUIStyle(GUI.skin.label); } public void Draw() { if (safeDisplay) { if (!initialized) { initialized = true; InitGUI(); } windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6705 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer - Debug", windowStyle, layoutOptions)); } CheckWindowLock(); } private void DrawContent(int windowID) { GUILayout.BeginVertical(); GUI.DragWindow(moveRect); GameEvents.debugEvents = GUILayout.Toggle(GameEvents.debugEvents, "Debug GameEvents", buttonStyle); displayFast = GUILayout.Toggle(displayFast, "Fast debug update", buttonStyle); displayVectors = GUILayout.Toggle(displayVectors, "Display vessel vectors", buttonStyle); if (displayVectors) { GUILayout.Label(vectorText, labelStyle); } displayNTP = GUILayout.Toggle(displayNTP, "Display NTP/Subspace statistics", buttonStyle); if (displayNTP) { GUILayout.Label(ntpText, labelStyle); } displayConnectionQueue = GUILayout.Toggle(displayConnectionQueue, "Display connection statistics", buttonStyle); if (displayConnectionQueue) { GUILayout.Label(connectionText, labelStyle); } displayDynamicTickStats = GUILayout.Toggle(displayDynamicTickStats, "Display dynamic tick statistics", buttonStyle); if (displayDynamicTickStats) { GUILayout.Label(dynamicTickText, labelStyle); } displayRequestedRates = GUILayout.Toggle(displayRequestedRates, "Display requested rates", buttonStyle); if (displayRequestedRates) { GUILayout.Label(requestedRateText, labelStyle); } displayProfilerStatistics = GUILayout.Toggle(displayProfilerStatistics, "Display Profiler Statistics", buttonStyle); if (displayProfilerStatistics) { if (System.Diagnostics.Stopwatch.IsHighResolution) { if (GUILayout.Button("Reset Profiler history", buttonStyle)) { Profiler.updateData = new ProfilerData(); Profiler.fixedUpdateData = new ProfilerData(); Profiler.guiData = new ProfilerData(); } GUILayout.Label("Timer resolution: " + System.Diagnostics.Stopwatch.Frequency + " hz", labelStyle); GUILayout.Label(profilerText, labelStyle); } else { GUILayout.Label("Timer resolution: " + System.Diagnostics.Stopwatch.Frequency + " hz", labelStyle); GUILayout.Label("Profiling statistics unavailable without a high resolution timer"); } } GUILayout.EndVertical(); } private void Update() { safeDisplay = display; if (display) { if (((UnityEngine.Time.realtimeSinceStartup - lastUpdateTime) > DISPLAY_UPDATE_INTERVAL) || displayFast) { lastUpdateTime = UnityEngine.Time.realtimeSinceStartup; //Vector text if (HighLogic.LoadedScene == GameScenes.FLIGHT && FlightGlobals.ready && FlightGlobals.fetch.activeVessel != null) { Vessel ourVessel = FlightGlobals.fetch.activeVessel; vectorText = "Forward vector: " + ourVessel.GetFwdVector() + "\n"; vectorText += "Up vector: " + (Vector3)ourVessel.upAxis + "\n"; vectorText += "Srf Rotation: " + ourVessel.srfRelRotation + "\n"; vectorText += "Vessel Rotation: " + ourVessel.transform.rotation + "\n"; vectorText += "Vessel Local Rotation: " + ourVessel.transform.localRotation + "\n"; vectorText += "mainBody Rotation: " + (Quaternion)ourVessel.mainBody.rotation + "\n"; vectorText += "mainBody Transform Rotation: " + (Quaternion)ourVessel.mainBody.bodyTransform.rotation + "\n"; vectorText += "Surface Velocity: " + ourVessel.GetSrfVelocity() + ", |v|: " + ourVessel.GetSrfVelocity().magnitude + "\n"; vectorText += "Orbital Velocity: " + ourVessel.GetObtVelocity() + ", |v|: " + ourVessel.GetObtVelocity().magnitude + "\n"; if (ourVessel.orbitDriver != null && ourVessel.orbitDriver.orbit != null) { vectorText += "Frame Velocity: " + (Vector3)ourVessel.orbitDriver.orbit.GetFrameVel() + ", |v|: " + ourVessel.orbitDriver.orbit.GetFrameVel().magnitude + "\n"; } vectorText += "CoM offset vector: " + ourVessel.orbitDriver.CoMoffset + "\n"; vectorText += "Angular Velocity: " + ourVessel.angularVelocity + ", |v|: " + ourVessel.angularVelocity.magnitude + "\n"; vectorText += "World Pos: " + (Vector3)ourVessel.GetWorldPos3D() + ", |pos|: " + ourVessel.GetWorldPos3D().magnitude + "\n"; } else { vectorText = "You have to be in flight"; } //NTP text ntpText = "Warp rate: " + Math.Round(Time.timeScale, 3) + "x.\n"; ntpText += "Current subspace: " + TimeSyncer.fetch.currentSubspace + ".\n"; if (TimeSyncer.fetch.locked) { ntpText += "Current subspace rate: " + Math.Round(TimeSyncer.fetch.lockedSubspace.subspaceSpeed, 3) + "x.\n"; } else { ntpText += "Current subspace rate: " + Math.Round(TimeSyncer.fetch.requestedRate, 3) + "x.\n"; } ntpText += "Current Error: " + Math.Round((TimeSyncer.fetch.GetCurrentError() * 1000), 0) + " ms.\n"; ntpText += "Current universe time: " + Math.Round(Planetarium.GetUniversalTime(), 3) + " UT\n"; ntpText += "Network latency: " + Math.Round((TimeSyncer.fetch.networkLatencyAverage / 10000f), 3) + " ms\n"; ntpText += "Server clock difference: " + Math.Round((TimeSyncer.fetch.clockOffsetAverage / 10000f), 3) + " ms\n"; ntpText += "Server lag: " + Math.Round((TimeSyncer.fetch.serverLag / 10000f), 3) + " ms\n"; //Connection queue text connectionText = "Last send time: " + NetworkWorker.fetch.GetStatistics("LastSendTime") + "ms.\n"; connectionText += "Last receive time: " + NetworkWorker.fetch.GetStatistics("LastReceiveTime") + "ms.\n"; connectionText += "Queued outgoing messages (High): " + NetworkWorker.fetch.GetStatistics("HighPriorityQueueLength") + ".\n"; connectionText += "Queued outgoing messages (Split): " + NetworkWorker.fetch.GetStatistics("SplitPriorityQueueLength") + ".\n"; connectionText += "Queued outgoing messages (Low): " + NetworkWorker.fetch.GetStatistics("LowPriorityQueueLength") + ".\n"; connectionText += "Queued out bytes: " + NetworkWorker.fetch.GetStatistics("QueuedOutBytes") + ".\n"; connectionText += "Sent bytes: " + NetworkWorker.fetch.GetStatistics("SentBytes") + ".\n"; connectionText += "Received bytes: " + NetworkWorker.fetch.GetStatistics("ReceivedBytes") + ".\n"; connectionText += "Stored future updates: " + VesselWorker.fetch.GetStatistics("StoredFutureUpdates") + "\n"; connectionText += "Stored future proto updates: " + VesselWorker.fetch.GetStatistics("StoredFutureProtoUpdates") + ".\n"; //Dynamic tick text dynamicTickText = "Current tick rate: " + DynamicTickWorker.fetch.sendTickRate + "hz.\n"; dynamicTickText += "Current max secondry vessels: " + DynamicTickWorker.fetch.maxSecondryVesselsPerTick + ".\n"; //Requested rates text requestedRateText = Settings.fetch.playerName + ": " + Math.Round(TimeSyncer.fetch.requestedRate, 3) + "x.\n"; foreach (KeyValuePair<string, float> playerEntry in WarpWorker.fetch.clientSkewList) { requestedRateText += playerEntry.Key + ": " + Math.Round(playerEntry.Value, 3) + "x.\n"; } profilerText = "Update: \n" + Profiler.updateData; profilerText += "Fixed Update: \n" + Profiler.fixedUpdateData; profilerText += "GUI: \n" + Profiler.guiData; } } } private void CheckWindowLock() { if (!Client.fetch.gameRunning) { RemoveWindowLock(); return; } if (HighLogic.LoadedSceneIsFlight) { RemoveWindowLock(); return; } if (safeDisplay) { Vector2 mousePos = Input.mousePosition; mousePos.y = Screen.height - mousePos.y; bool shouldLock = windowRect.Contains(mousePos); if (shouldLock && !isWindowLocked) { InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_DebugLock"); isWindowLocked = true; } if (!shouldLock && isWindowLocked) { RemoveWindowLock(); } } if (!safeDisplay && isWindowLocked) { RemoveWindowLock(); } } private void RemoveWindowLock() { if (isWindowLocked) { isWindowLocked = false; InputLockManager.RemoveControlLock("DMP_DebugLock"); } } public static void Reset() { lock (Client.eventLock) { if (singleton != null) { singleton.display = false; singleton.RemoveWindowLock(); Client.updateEvent.Remove(singleton.Update); Client.drawEvent.Remove(singleton.Draw); } singleton = new DebugWindow(); Client.updateEvent.Add(singleton.Update); Client.drawEvent.Add(singleton.Draw); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using OLEDB.Test.ModuleCore; namespace XmlReaderTest.Common { public partial class TCLinePos : TCXMLReaderBaseGeneral { // Type is XmlReaderTest.Common.TCLinePos // Test Case public override void AddChildren() { // for function TestLinePos1 { this.AddChild(new CVariation(TestLinePos1) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Element") { Priority = 0 } }); } // for function TestLinePos2 { this.AddChild(new CVariation(TestLinePos2) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = CDATA") { Priority = 0 } }); } // for function TestLinePos4 { this.AddChild(new CVariation(TestLinePos4) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Comment") { Priority = 0 } }); } // for function TestLinePos6 { this.AddChild(new CVariation(TestLinePos6) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EndElement") { Priority = 0 } }); } // for function TestLinePos7 { this.AddChild(new CVariation(TestLinePos7) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EntityReference, not expanded") { Priority = 0 } }); } // for function TestLinePos9 { this.AddChild(new CVariation(TestLinePos9) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = ProcessingInstruction") { Priority = 0 } }); } // for function TestLinePos10 { this.AddChild(new CVariation(TestLinePos10) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = SignificantWhitespace") { Priority = 0 } }); } // for function TestLinePos11 { this.AddChild(new CVariation(TestLinePos11) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Text") { Priority = 0 } }); } // for function TestLinePos12 { this.AddChild(new CVariation(TestLinePos12) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Whitespace") { Priority = 0 } }); } // for function TestLinePos13 { this.AddChild(new CVariation(TestLinePos13) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = XmlDeclaration") { Priority = 0 } }); } // for function TestLinePos14 { this.AddChild(new CVariation(TestLinePos14) { Attribute = new Variation("LineNumber/LinePos after MoveToElement") }); } // for function TestLinePos15 { this.AddChild(new CVariation(TestLinePos15) { Attribute = new Variation("LineNumber/LinePos after MoveToFirstAttribute/MoveToNextAttribute") }); } // for function TestLinePos16 { this.AddChild(new CVariation(TestLinePos16) { Attribute = new Variation("LineNumber/LinePos after MoveToAttribute") }); } // for function TestLinePos18 { this.AddChild(new CVariation(TestLinePos18) { Attribute = new Variation("LineNumber/LinePos after Skip") }); } // for function TestLinePos19 { this.AddChild(new CVariation(TestLinePos19) { Attribute = new Variation("LineNumber/LinePos after ReadInnerXml") }); } // for function TestLinePos20 { this.AddChild(new CVariation(TestLinePos20) { Attribute = new Variation("LineNumber/LinePos after MoveToContent") }); } // for function TestLinePos21 { this.AddChild(new CVariation(TestLinePos21) { Attribute = new Variation("LineNumber/LinePos after ReadBase64 succesive calls") }); } // for function TestLinePos22 { this.AddChild(new CVariation(TestLinePos22) { Attribute = new Variation("LineNumber/LinePos after ReadBinHex succesive calls") }); } // for function TestLinePos26 { this.AddChild(new CVariation(TestLinePos26) { Attribute = new Variation("LineNumber/LinePos after ReadEndElement") }); } // for function TestLinePos27 { this.AddChild(new CVariation(TestLinePos27) { Attribute = new Variation("LineNumber/LinePos after ReadString") }); } // for function TestLinePos39 { this.AddChild(new CVariation(TestLinePos39) { Attribute = new Variation("LineNumber/LinePos after element containing entities in attribute values") }); } // for function TestLinePos40 { this.AddChild(new CVariation(TestLinePos40) { Attribute = new Variation("LineNumber/LinePos when Read = false") }); } // for function TestLinePos41 { this.AddChild(new CVariation(TestLinePos41) { Attribute = new Variation("XmlTextReader:LineNumber and LinePos don't return the right position after ReadInnerXml is called") }); } // for function TestLinePos42 { this.AddChild(new CVariation(TestLinePos42) { Attribute = new Variation("XmlTextReader: LineNum and LinePosition incorrect for EndTag token and text element") }); } // for function TestLinePos43 { this.AddChild(new CVariation(TestLinePos43) { Attribute = new Variation("Bogus LineNumber value when reading attribute over XmlTextReader") }); } // for function TestLinePos44 { this.AddChild(new CVariation(TestLinePos44) { Attribute = new Variation("LineNumber and LinePosition on attribute with columns") }); } // for function TestLinePos45 { this.AddChild(new CVariation(TestLinePos45) { Attribute = new Variation("HasLineInfo") }); } // for function TestLinePos99 { this.AddChild(new CVariation(TestLinePos99) { Attribute = new Variation("XmlException LineNumber and LinePosition") }); } // for function ReadingNonWellFormedXmlThrows { this.AddChild(new CVariation(ReadingNonWellFormedXmlThrows) { Attribute = new Variation("Check error message on a non-wellformed XML") }); } // for function XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown { this.AddChild(new CVariation(XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown) { Attribute = new Variation("When an XmlException is thrown both XmlException.LineNumber and XmlTextReader.LineNumber should be same") }); } // for function XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag { this.AddChild(new CVariation(XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag) { Attribute = new Variation("Xml(Text)Reader does not increase line number for a new line in element end tag") }); } // for function LineNumberAndLinePositionAreCorrect { this.AddChild(new CVariation(LineNumberAndLinePositionAreCorrect) { Attribute = new Variation("LineNumber and LinePosition are not correct") }); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections.Generic; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary implementation. /// </summary> internal class Binary : IBinary { /** Owning grid. */ private readonly Marshaller _marsh; /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> internal Binary(Marshaller marsh) { _marsh = marsh; } /** <inheritDoc /> */ public T ToBinary<T>(object obj) { if (obj is IBinaryObject) return (T)obj; using (var stream = new BinaryHeapStream(1024)) { // Serialize. BinaryWriter writer = _marsh.StartMarshal(stream); try { writer.Write(obj); } finally { // Save metadata. _marsh.FinishMarshal(writer); } // Deserialize. stream.Seek(0, SeekOrigin.Begin); return _marsh.Unmarshal<T>(stream, BinaryMode.ForceBinary); } } /** <inheritDoc /> */ public IBinaryObjectBuilder GetBuilder(Type type) { IgniteArgumentCheck.NotNull(type, "type"); IBinaryTypeDescriptor desc = _marsh.GetDescriptor(type); if (desc == null) throw new IgniteException("Type is not binary (add it to BinaryConfiguration): " + type.FullName); return Builder0(null, BinaryFromDescriptor(desc), desc); } /** <inheritDoc /> */ public IBinaryObjectBuilder GetBuilder(string typeName) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); IBinaryTypeDescriptor desc = _marsh.GetDescriptor(typeName); return Builder0(null, BinaryFromDescriptor(desc), desc); } /** <inheritDoc /> */ public IBinaryObjectBuilder GetBuilder(IBinaryObject obj) { IgniteArgumentCheck.NotNull(obj, "obj"); BinaryObject obj0 = obj as BinaryObject; if (obj0 == null) throw new ArgumentException("Unsupported object type: " + obj.GetType()); IBinaryTypeDescriptor desc = _marsh.GetDescriptor(true, obj0.TypeId); return Builder0(null, obj0, desc); } /** <inheritDoc /> */ public int GetTypeId(string typeName) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); return Marshaller.GetDescriptor(typeName).TypeId; } /** <inheritDoc /> */ public ICollection<IBinaryType> GetBinaryTypes() { return Marshaller.Ignite.ClusterGroup.GetBinaryTypes(); } /** <inheritDoc /> */ public IBinaryType GetBinaryType(int typeId) { return Marshaller.GetBinaryType(typeId); } /** <inheritDoc /> */ public IBinaryType GetBinaryType(string typeName) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); return GetBinaryType(GetTypeId(typeName)); } /** <inheritDoc /> */ public IBinaryType GetBinaryType(Type type) { IgniteArgumentCheck.NotNull(type, "type"); var desc = Marshaller.GetDescriptor(type); return desc == null ? null : Marshaller.GetBinaryType(desc.TypeId); } /** <inheritDoc /> */ public IBinaryObject BuildEnum(string typeName, int value) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); var desc = Marshaller.GetDescriptor(typeName); IgniteArgumentCheck.Ensure(desc.IsEnum, "typeName", "Type should be an Enum."); _marsh.PutBinaryType(desc); return new BinaryEnum(GetTypeId(typeName), value, Marshaller); } /** <inheritDoc /> */ public IBinaryObject BuildEnum(Type type, int value) { IgniteArgumentCheck.NotNull(type, "type"); IgniteArgumentCheck.Ensure(type.IsEnum, "type", "Type should be an Enum."); return BuildEnum(type.Name, value); } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Create empty binary object from descriptor. /// </summary> /// <param name="desc">Descriptor.</param> /// <returns>Empty binary object.</returns> private BinaryObject BinaryFromDescriptor(IBinaryTypeDescriptor desc) { const int len = BinaryObjectHeader.Size; var hdr = new BinaryObjectHeader(desc.TypeId, 0, len, 0, len, desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None); using (var stream = new BinaryHeapStream(len)) { BinaryObjectHeader.Write(hdr, stream, 0); return new BinaryObject(_marsh, stream.InternalArray, 0, hdr); } } /// <summary> /// Internal builder creation routine. /// </summary> /// <param name="parent">Parent builder.</param> /// <param name="obj">binary object.</param> /// <param name="desc">Type descriptor.</param> /// <returns>Builder.</returns> private BinaryObjectBuilder Builder0(BinaryObjectBuilder parent, BinaryObject obj, IBinaryTypeDescriptor desc) { return new BinaryObjectBuilder(this, parent, obj, desc); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using System.Threading; namespace Rejc2.Utils.Audio { public class WavefileWavLoader : WavefileLoader { class FourByteId { readonly byte[] m_Data = new byte[4]; private string m_TypeId; public string TypeId { get { if (m_TypeId == null) { m_TypeId = Encoding.ASCII.GetString(m_Data, 0, 4); } return m_TypeId; } } public bool Equals(FourByteId other) { return m_Data[0] == other.m_Data[0] && m_Data[1] == other.m_Data[1] && m_Data[2] == other.m_Data[2] && m_Data[3] == other.m_Data[3]; } public override bool Equals(object obj) { return Equals((FourByteId)obj); } public override int GetHashCode() { return TypeId.GetHashCode(); } public FourByteId(SafeStream stream) { stream.Read(m_Data, 0, 4); } public FourByteId(string id) { m_TypeId = id; Encoding.ASCII.GetBytes(id).CopyTo(m_Data, 0); } public override string ToString() { return TypeId; } } class ChunkHeader { private FourByteId m_TypeId; public FourByteId TypeId { get { return m_TypeId; } } private int m_Length; public int Length { get { return m_Length; } } SafeStream m_Stream; public ChunkHeader(SafeStream stream) { m_Stream = stream; m_TypeId = new FourByteId(stream); m_Length = ReadI4(m_Stream); } public bool IsType(FourByteId type) { //return memcmp(id, type, 4)==0 ; return type.Equals(m_TypeId); } public SafeStream GetSubStream() { FixedLengthSubStream subStream = new FixedLengthSubStream(m_Stream, Length); SafeStream safeStream = new SafeStream(subStream); return safeStream; } } int m_Length; bool m_DoneFormat; int fmt_Channels; int fmt_SampleRate; int fmt_BitsPerSample; //bool m_Done; static readonly FourByteId RiffId = new FourByteId("RIFF"); static readonly FourByteId WaveId = new FourByteId("WAVE"); static readonly FourByteId FormatId = new FourByteId("fmt "); static readonly FourByteId DataId = new FourByteId("data"); public override Wavefile Load(Stream fileStream) { SafeStream safeStream = new SafeStream(fileStream); try { ChunkHeader riffHeader = new ChunkHeader(safeStream); if (!riffHeader.IsType(RiffId)) throw new InvalidFileFormatException("WAV-file does not begin with `RIFF'."); SafeStream stream = riffHeader.GetSubStream(); try { FourByteId waveHeader = new FourByteId(stream); if (!waveHeader.Equals(WaveId)) throw new InvalidFileFormatException("Riff file is not a waveform."); while (true) //!m_Done) { ChunkHeader chunk = new ChunkHeader(stream); if (chunk.IsType(FormatId)) { using (SafeStream formatStream = chunk.GetSubStream()) { int formatTag = ReadI2(formatStream); if (formatTag != 1) throw new InvalidFileFormatException("Wavefile is not PCM."); fmt_Channels = ReadI2(formatStream); //if (fmt_channels != 1) throw "Wavefile must be mono." ; //^^^ Fixed 19.Mar.2001 fmt_SampleRate = ReadI4(formatStream); ReadI4(formatStream); // <-- average bytes per second (rubbish) ReadI2(formatStream); // <-- block align (who knows) fmt_BitsPerSample = ReadI2(formatStream); m_DoneFormat = true; } } else if (chunk.IsType(DataId)) { if (!m_DoneFormat) throw new InvalidFileFormatException("No format block before data!"); Wavefile wave = new Wavefile(); wave.m_SampleRate = (float)fmt_SampleRate; switch (fmt_BitsPerSample) { case 8: { if (fmt_Channels == 2) { //read_pcm_8bit_st (f, chunk.len/2, wave) ; //read_pcm = read_pcm_8bit_st ; m_Length = chunk.Length / 2; //start() ; } else { //read_pcm_8bit (f, chunk.len, wave) ; //read_pcm = read_pcm_8bit ; m_Length = chunk.Length; //start() ; } } break; case 16: { if (fmt_Channels == 2) { //read_pcm_16bit_i_st (f, chunk.len/2/2, wave) ; //read_pcm = read_pcm_16bit_i_st ; m_Length = chunk.Length / 2 / 2; //start() ; } else { //read_pcm_16bit_i (f, chunk.len/2, wave) ; //read_pcm = read_pcm_16bit_i ; m_Length = chunk.Length / 2; //start() ; } } break; default: throw new InvalidFileFormatException("Must be 8- or 16-bit."); } ThreadPool.QueueUserWorkItem(delegate { using (SafeStream dataStream = chunk.GetSubStream()) { ReadPcm(wave, dataStream, m_Length, fmt_BitsPerSample, fmt_Channels, true); } //m_Done = true; wave.FinishedLoading = true; }); safeStream = null; stream = null; return wave; } else { chunk.GetSubStream().Dispose(); Trace.WriteLine(String.Format("Warning: Unknown chunk `{0}'", chunk.TypeId)); ; } } } finally { if (stream != null) stream.Dispose(); } } finally { if (safeStream != null) safeStream.Dispose(); } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using Microsoft.Win32; namespace Gallio.Loader { /// <summary> /// The Gallio.Loader namespace contains types for loading the Gallio runtime /// into an application. /// </summary> /// <remarks> /// <para> /// The loader is not distributed as a compiled assembly. Instead it is intended /// to be included as a source file within the application itself. /// </para> /// <para> /// For documentation see: http://www.gallio.org/wiki/devel:gallio_loader /// </para> /// </remarks> [CompilerGenerated] class NamespaceDoc { } /// <summary> /// Helper utilities for implementing the Gallio loader. /// </summary> internal static class LoaderUtils { /// <summary> /// Gets the local path of an assembly. (Not its shadow copied location.) /// </summary> /// <param name="assembly">The assembly, not null.</param> /// <returns>The assembly path.</returns> public static string GetAssemblyPath(Assembly assembly) { return new Uri(assembly.CodeBase).LocalPath; } /// <summary> /// Gets the directory path of the assembly that contains the loader. /// </summary> /// <returns>The directory path of the assembly that contains the loader.</returns> public static string GetLoaderDirectoryPath() { return Path.GetDirectoryName(GetAssemblyPath(typeof(LoaderUtils).Assembly)); } } /// <summary> /// The exception that is thrown by the loader when an operation cannot be performed. /// </summary> [Serializable] internal class LoaderException : Exception { /// <summary> /// Creates an exception. /// </summary> public LoaderException() { } /// <summary> /// Creates an exception. /// </summary> /// <param name="message">The message.</param> public LoaderException(string message) : base(message) { } /// <summary> /// Creates an exception. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> public LoaderException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Creates an exception from serialization info. /// </summary> /// <param name="info">The serialization info.</param> /// <param name="context">The streaming context.</param> protected LoaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Specifies how to locate the Gallio runtime. /// </summary> internal abstract class RuntimeLocator { /// <summary> /// Gets the path of the runtime and validates it. If not found or if a /// problem occurs, throws. /// </summary> /// <returns>The validated runtime path.</returns> /// <exception cref="LoaderException">Thrown if the runtime path could not be obtained or validated.</exception> public virtual string GetValidatedRuntimePathOrThrow() { try { string runtimePath = GetRuntimePath(); if (runtimePath == null) { throw new LoaderException(string.Format( "Could not determine the Gallio runtime path.\n\n{0}", GetFailureHint())); } if (! IsRuntimePathValid(runtimePath)) { throw new LoaderException(string.Format( "The Gallio runtime path '{0}' appears to be invalid.\n\n{1}", runtimePath, GetFailureHint())); } return runtimePath; } catch (LoaderException) { throw; } catch (Exception ex) { throw new LoaderException(string.Format( "An exception occurred while attempting to determine the Gallio runtime path.\n\n{0}", GetFailureHint()), ex); } } /// <summary> /// Returns a hint to help the user figure out how to resolve an issue /// involving a bad runtime path. /// </summary> public abstract string GetFailureHint(); /// <summary> /// Gets the path of the runtime. /// </summary> /// <returns>The runtime path, or null if not found.</returns> public abstract string GetRuntimePath(); /// <summary> /// Returns true if the specified runtime path is valid. /// </summary> /// <param name="runtimePath">The runtime path, not null.</param> /// <returns>True if the path was valid.</returns> public virtual bool IsRuntimePathValid(string runtimePath) { return File.Exists(GetGallioAssemblyPath(runtimePath)); } /// <summary> /// Gets the path of the Gallio assembly. /// </summary> /// <param name="runtimePath">The runtime path, not null.</param> /// <returns>The path of the Gallio assembly.</returns> public virtual string GetGallioAssemblyPath(string runtimePath) { return Path.Combine(runtimePath, "Gallio.dll"); } } /// <summary> /// Locates the runtime path automatically using environment variables and the registry. /// </summary> internal class DefaultRuntimeLocator : RuntimeLocator { /// <inheritdoc /> public override string GetFailureHint() { return "This usually means that this program or Gallio has not been installed correctly.\n" + "As a workaround, you can set the GALLIO_RUNTIME_PATH environment variable to force " + "the program to look for Gallio in a particular directory such as 'C:\\Gallio\\bin'. " + "Alternately, you can set the GALLIO_RUNTIME_VERSION environment variable to force the " + "program to search for a particular version of Gallio in the registry, such as '3.2'."; } /// <summary> /// Gets the path of the runtime. /// </summary> /// <remarks> /// The default implementation tries <see cref="GetRuntimePathUsingEnvironment" /> /// then <see cref="GetRuntimePathUsingRegistry" /> then /// <see cref="GetRuntimePathUsingApplicationBaseDirectoryOrAncestor"/>. /// </remarks> /// <returns>The runtime path, or null if not found.</returns> public override string GetRuntimePath() { return GetRuntimePathUsingEnvironment() ?? GetRuntimePathUsingRegistry() ?? GetRuntimePathUsingApplicationBaseDirectoryOrAncestor(); } /// <summary> /// Gets the Gallio runtime path by examining the GALLIO_RUNTIME_PATH /// environment variable. /// </summary> /// <returns>The runtime path, or null if not found.</returns> protected virtual string GetRuntimePathUsingEnvironment() { return Environment.GetEnvironmentVariable("GALLIO_RUNTIME_PATH"); } /// <summary> /// Gets the Gallio runtime path by searching the registry for the /// version returned by <see cref="GetRuntimeVersion"/>. /// </summary> /// <returns>The runtime path, or null if not found.</returns> protected virtual string GetRuntimePathUsingRegistry() { string runtimeVersion = GetRuntimeVersion(); if (runtimeVersion == null) return null; foreach (string installationKey in new[] { @"HKEY_CURRENT_USER\Software\Gallio.org\Gallio\" + runtimeVersion, @"HKEY_CURRENT_USER\Software\Wow6432Node\Gallio.org\Gallio\" + runtimeVersion, @"HKEY_LOCAL_MACHINE\Software\Gallio.org\Gallio\" + runtimeVersion, @"HKEY_LOCAL_MACHINE\Software\Wow6432Node\Gallio.org\Gallio\" + runtimeVersion }) { string installationFolder = Registry.GetValue(installationKey, @"InstallationFolder", null) as string; if (installationFolder != null) return Path.Combine(installationFolder, "bin"); } return null; } /// <summary> /// Gets the Gallio runtime path by searching the application base directory /// and its ancestors for Gallio.dll. /// </summary> /// <remarks> /// This fallback option only makes sense for applications that are themselves /// installed in the Gallio runtime path. It is also useful for /// debugging since debug versions of Gallio contain extra special logic /// hardcoded in the runtime to tweak the runtime path assuming that the /// application resides in the Gallio source tree. /// </remarks> /// <returns>The runtime path, or null if not found.</returns> protected virtual string GetRuntimePathUsingApplicationBaseDirectoryOrAncestor() { string candidatePath = AppDomain.CurrentDomain.BaseDirectory; while (candidatePath != null) { if (IsRuntimePathValid(candidatePath)) return candidatePath; candidatePath = Path.GetDirectoryName(candidatePath); } return null; } /// <summary> /// Gets the version of Gallio to load. /// </summary> /// <remarks> /// The default implementation tries <see cref="GetRuntimeVersionUsingEnvironment" /> /// then <see cref="GetRuntimeVersionUsingReferencedAssemblies" />. /// </remarks> /// <returns>The runtime version, or null if not found.</returns> protected virtual string GetRuntimeVersion() { return GetRuntimeVersionUsingEnvironment() ?? GetRuntimeVersionUsingReferencedAssemblies(); } /// <summary> /// Gets the version of Gallio to load by examining the GALLIO_RUNTIME_VERSION /// environment variable. /// </summary> /// <returns>The runtime version, or null if not found.</returns> protected virtual string GetRuntimeVersionUsingEnvironment() { return Environment.GetEnvironmentVariable("GALLIO_RUNTIME_VERSION"); } /// <summary> /// Gets the version of Gallio to load by searching the referenced assemblies /// for an assembly name for which <see cref="IsGallioAssemblyName"/> returns true /// then returns the runtime version that was discovered. /// </summary> /// <returns>The runtime version, or null if not found.</returns> protected virtual string GetRuntimeVersionUsingReferencedAssemblies() { foreach (AssemblyName assemblyName in GetReferencedAssemblies()) { if (IsGallioAssemblyName(assemblyName)) return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", assemblyName.Version.Major, assemblyName.Version.Minor); } return null; } /// <summary> /// Returns true if the assembly name is a Gallio assembly. /// </summary> /// <remarks> /// The default implementation returns true for any assembly called /// "Gallio" or whose name starts with "Gallio.". /// </remarks> /// <param name="assemblyName">The assembly name to check, not null.</param> /// <returns>True if the assembly is a Gallio assembly.</returns> protected virtual bool IsGallioAssemblyName(AssemblyName assemblyName) { return assemblyName.Name == "Gallio" || assemblyName.Name.StartsWith("Gallio."); } /// <summary> /// Gets the referenced assemblies to search for a Gallio reference in order /// to automatically determine the version of Gallio to load. /// </summary> /// <remarks> /// The default implementation returns the name of the assemblies referenced by the /// currently executing assembly and the name of the executing assembly itself. /// </remarks> /// <returns>The referenced assemblies.</returns> protected virtual IEnumerable<AssemblyName> GetReferencedAssemblies() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); foreach (AssemblyName assemblyName in executingAssembly.GetReferencedAssemblies()) yield return assemblyName; yield return executingAssembly.GetName(); } } /// <summary> /// A runtime locator that uses an explicitly specified runtime path. /// </summary> internal class ExplicitRuntimeLocator : RuntimeLocator { private readonly string runtimePath; /// <summary> /// Creates the explicit runtime locator. /// </summary> /// <param name="runtimePath">The runtime path, or null if not found.</param> public ExplicitRuntimeLocator(string runtimePath) { this.runtimePath = runtimePath; } public override string GetFailureHint() { return ""; } public override string GetRuntimePath() { return runtimePath; } } /// <summary> /// The loader provides access to Gallio runtime services from an application /// that might not be installed in Gallio's runtime path. /// </summary> /// <seealso cref="LoaderManager"/> internal interface ILoader { /// <summary> /// Gets the Gallio runtime path used by the loader. /// </summary> /// <exception cref="LoaderException">Thrown if the operation could not be performed.</exception> string RuntimePath { get; } /// <summary> /// Sets up the runtime with a default runtime setup using the loader's /// runtime path and a null logger. Does nothing if the runtime has /// already been initialized. /// </summary> /// <remarks> /// <para> /// If you need more control over this behavior, call RuntimeBootstrap /// yourself. /// </para> /// </remarks> /// <exception cref="LoaderException">Thrown if the operation could not be performed.</exception> void SetupRuntime(); /// <summary> /// Adds a hint directory to the assembly resolver. /// </summary> /// <param name="path">The path of the hint directory to add.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="path"/> is null.</exception> /// <exception cref="LoaderException">Thrown if the operation could not be performed.</exception> void AddHintDirectory(string path); /// <summary> /// Resolves a runtime service. /// </summary> /// <typeparam name="T">The type of service to resolve.</typeparam> /// <returns>The resolved service.</returns> /// <exception cref="LoaderException">Thrown if the operation could not be performed.</exception> T Resolve<T>(); /// <summary> /// Resolves a runtime service. /// </summary> /// <param name="serviceType">The type of service to resolve.</param> /// <returns>The resolved service.</returns> /// <exception cref="LoaderException">Thrown if the operation could not be performed.</exception> object Resolve(Type serviceType); } /// <summary> /// The loader manager is responsible for initializing a loader within the current process. /// At most one loader can exist in a process. /// </summary> /// <remarks> /// <para> /// The Gallio loader is used in situations where applications that are not installed /// in the Gallio runtime path need to load Gallio assemblies. We can't just copy /// Gallio assemblies into the application base directory because it creates /// assembly loading ambiguities. In particular, it is possible for multiple copies /// to be loaded in the same process simultaneously in different load contexts /// (Load / LoadFrom / LoadFile). When multiple copies of the same assembly are loaded /// their types are considered distinct and they cannot reliably exchange information /// with other components (like plugins). /// </para> /// <para> /// For example, assembly load context problems were observed when two different Visual /// Studio add-ins installed in different locations were loaded at the same time. /// The Gallio loader avoids this problem by ensuring that there is only one copy of /// Gallio installed on the machine. Applications installed outside of the Gallio /// runtime path are required to use a custom assembly resolver to load Gallio assemblies. /// </para> /// <para> /// Before the loader is initialized, it might not be possible to load /// certain Gallio types unless the appropriate assemblies have been /// copied into the application base directory. (In fact, that's the /// problem that the loader is designed to solve.) /// </para> /// <para> /// Consequently it is very important that the application refrain /// from causing any Gallio types to be loaded. This bears repeating! /// Don't try to use any Gallio functions or declare any fields of /// Gallio types until the loader is initialized. Otherwise a runtime /// exception will probably be thrown. Ideally you should initialize /// the loader in your program's main entry point before doing anything /// else. /// </para> /// <para> /// When the loader is initialized, it will install a custom assembly /// resolver to ensure that assemblies in the Gallio runtime path can /// be resolved. In particular, this makes it possible to initialize /// the Gallio runtime extensibility framework. /// </para> /// </remarks> internal static class LoaderManager { private static ILoader loader; /// <summary> /// Gets the current loader, or null if it has not been initialized. /// </summary> public static ILoader Loader { get { return loader; } } /// <summary> /// If the loader has not been initialized, initializes it using the default /// runtime locator and sets up the runtime. /// </summary> public static void InitializeAndSetupRuntimeIfNeeded() { if (loader == null) { Initialize(); loader.SetupRuntime(); } } /// <summary> /// Initializes the loader using the <see cref="DefaultRuntimeLocator"/>. /// </summary> /// <exception cref="InvalidOperationException">Thrown if the loader has already been initialized.</exception> /// <exception cref="LoaderException">Thrown if the loader could not be initialized.</exception> public static void Initialize() { Initialize(new DefaultRuntimeLocator()); } /// <summary> /// Initializes the loader. /// </summary> /// <param name="locator">The runtime locator.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="locator"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if the loader has already been initialized.</exception> /// <exception cref="LoaderException">Thrown if the loader could not be initialized.</exception> public static void Initialize(RuntimeLocator locator) { if (locator == null) throw new ArgumentNullException("locator"); if (loader != null) throw new InvalidOperationException("The loader has already been initialized."); string runtimePath = locator.GetValidatedRuntimePathOrThrow(); string gallioAssemblyPath = locator.GetGallioAssemblyPath(runtimePath); LoaderImpl newLoader = new LoaderImpl(runtimePath, gallioAssemblyPath); newLoader.Initialize(); loader = newLoader; } private class LoaderImpl : ILoader { private const string BootstrapTypeFullName = "Gallio.Runtime.Loader.GallioLoaderBootstrap"; private const string BootstrapInstallAssemblyLoaderMethodName = "InstallAssemblyLoader"; private const string BootstrapSetupRuntimeMethodName = "SetupRuntime"; private const string BootstrapAddHintDirectoryMethodName = "AddHintDirectory"; private const string BootstrapResolveMethodName = "Resolve"; private readonly string runtimePath; private readonly string gallioAssemblyPath; private Assembly gallioAssembly; private Type bootstrapType; public LoaderImpl(string runtimePath, string gallioAssemblyPath) { this.runtimePath = runtimePath; this.gallioAssemblyPath = gallioAssemblyPath; } public string RuntimePath { get { return runtimePath; } } public void Initialize() { LoadGallioAssembly(); LoadBootstrapType(); InstallAssemblyLoader(); } public void SetupRuntime() { try { MethodInfo method = GetBootstrapMethod(BootstrapSetupRuntimeMethodName); method.Invoke(null, new object[] { runtimePath }); } catch (TargetInvocationException ex) { throw new LoaderException("Failed to setup the runtime.", ex.InnerException); } catch (Exception ex) { throw new LoaderException("Failed to setup the runtime.", ex); } } public void AddHintDirectory(string path) { if (path == null) throw new ArgumentNullException("path"); try { MethodInfo method = GetBootstrapMethod(BootstrapAddHintDirectoryMethodName); method.Invoke(null, new object[] { path }); } catch (TargetInvocationException ex) { throw new LoaderException("Failed to add hint directory.", ex.InnerException); } catch (Exception ex) { throw new LoaderException("Failed to add hint directory.", ex); } } public T Resolve<T>() { return (T)Resolve(typeof(T)); } public object Resolve(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); try { MethodInfo method = GetBootstrapMethod(BootstrapResolveMethodName); return method.Invoke(null, new object[] { serviceType }); } catch (TargetInvocationException ex) { throw new LoaderException("Failed to resolve service.", ex.InnerException); } catch (Exception ex) { throw new LoaderException("Failed to resolve service.", ex); } } private void LoadGallioAssembly() { try { try { // Try to resolve the Gallio assembly if we already know where it is. // But we need to sanity check that it is the right version otherwise we will // encounter conflicts. gallioAssembly = Assembly.Load("Gallio"); if (gallioAssembly.Location == null || Path.GetFullPath(gallioAssembly.Location) != Path.GetFullPath(gallioAssemblyPath)) { AssemblyName expectedAssemblyName = AssemblyName.GetAssemblyName(gallioAssemblyPath); if (gallioAssembly.FullName != expectedAssemblyName.FullName) throw new LoaderException(string.Format( "Failed to load the expected version of the Gallio assembly. Actually loaded '{0}' but expected '{1}'.", gallioAssembly.FullName, expectedAssemblyName.FullName)); } } catch (FileNotFoundException) { gallioAssembly = Assembly.LoadFrom(gallioAssemblyPath); } } catch (LoaderException) { throw; } catch (Exception ex) { throw new LoaderException(string.Format( "Failed to load the Gallio assembly from '{0}'.", gallioAssemblyPath), ex); } } private void LoadBootstrapType() { try { bootstrapType = gallioAssembly.GetType(BootstrapTypeFullName, true); } catch (Exception ex) { throw new LoaderException("Failed to load the bootstrap type.", ex); } } private void InstallAssemblyLoader() { try { MethodInfo method = GetBootstrapMethod(BootstrapInstallAssemblyLoaderMethodName); method.Invoke(null, new object[] { runtimePath }); } catch (TargetInvocationException ex) { throw new LoaderException("Failed to install the assembly loader.", ex.InnerException); } catch (Exception ex) { throw new LoaderException("Failed to install the assembly resolver.", ex); } } private MethodInfo GetBootstrapMethod(string methodName) { MethodInfo method = bootstrapType.GetMethod(methodName); if (method == null) throw new LoaderException(String.Format("Could not resolve method '{0}' on bootstrap type.", methodName)); return method; } } } }
namespace StockSharp.Algo.Candles.Compression { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.Localization; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// Candle builder adapter. /// </summary> public class CandleBuilderMessageAdapter : MessageAdapterWrapper { private enum SeriesStates { None, Regular, SmallTimeFrame, Compress, } private class SeriesInfo : ICandleBuilderSubscription { public SeriesInfo(MarketDataMessage original, MarketDataMessage current) { Original = original ?? throw new ArgumentNullException(nameof(original)); Current = current; } public long Id => Original.TransactionId; MarketDataMessage ICandleBuilderSubscription.Message => Original; public MarketDataMessage Original { get; } public Dictionary<SecurityId, SeriesInfo> Child { get; } = new Dictionary<SecurityId, SeriesInfo>(); private MarketDataMessage _current; public MarketDataMessage Current { get => _current; set => _current = value ?? throw new ArgumentNullException(nameof(value)); } public SeriesStates State { get; set; } = SeriesStates.None; public BiggerTimeFrameCandleCompressor BigTimeFrameCompressor { get; set; } public ICandleBuilderValueTransform Transform { get; set; } public DateTimeOffset? LastTime { get; set; } public long? Count { get; set; } public CandleMessage CurrentCandle { get; set; } public CandleMessage NonFinishedCandle { get; set; } public VolumeProfileBuilder VolumeProfile { get; set; } public bool Stopped; } private readonly SyncObject _syncObject = new(); private readonly Dictionary<long, SeriesInfo> _series = new(); private readonly Dictionary<long, long> _replaceId = new(); private readonly CandleBuilderProvider _candleBuilderProvider; private readonly Dictionary<long, SeriesInfo> _allChilds = new(); private readonly Dictionary<long, RefPair<long, SubscriptionStates>> _pendingLoopbacks = new(); /// <summary> /// Initializes a new instance of the <see cref="CandleBuilderMessageAdapter"/>. /// </summary> /// <param name="innerAdapter">Inner message adapter.</param> /// <param name="candleBuilderProvider">Candle builders provider.</param> public CandleBuilderMessageAdapter(IMessageAdapter innerAdapter, CandleBuilderProvider candleBuilderProvider) : base(innerAdapter) { _candleBuilderProvider = candleBuilderProvider ?? throw new ArgumentNullException(nameof(candleBuilderProvider)); } /// <summary> /// Send out finished candles when they received. /// </summary> public bool SendFinishedCandlesImmediatelly { get; set; } /// <inheritdoc /> protected override bool OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { lock (_syncObject) { _series.Clear(); _replaceId.Clear(); _allChilds.Clear(); _pendingLoopbacks.Clear(); } break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (!_candleBuilderProvider.IsRegistered(mdMsg.DataType2.MessageType)) break; var transactionId = mdMsg.TransactionId; if (mdMsg.IsSubscribe) { lock (_syncObject) { if (_replaceId.ContainsKey(transactionId)) break; if (_pendingLoopbacks.TryGetAndRemove(transactionId, out var tuple)) { if (tuple.Second != SubscriptionStates.Stopped) { if (tuple.Second == SubscriptionStates.Finished) { RaiseNewOutMessage(new SubscriptionFinishedMessage { OriginalTransactionId = transactionId, }); } else { RaiseNewOutMessage(new SubscriptionResponseMessage { OriginalTransactionId = transactionId, Error = new InvalidOperationException(LocalizedStrings.SubscriptionInvalidState.Put(transactionId, tuple.Second)), }); } return true; } tuple.Second = SubscriptionStates.Active; this.AddDebugLog("New ALL candle-map (active): {0}/{1} TrId={2}", mdMsg.SecurityId, tuple.Second, mdMsg.TransactionId); RaiseNewOutMessage(mdMsg.CreateResponse()); return true; } } var isLoadOnly = mdMsg.BuildMode == MarketDataBuildModes.Load; if (mdMsg.IsCalcVolumeProfile) { if (!IsSupportCandlesPriceLevels) { if (isLoadOnly) { RaiseNewOutMessage(transactionId.CreateNotSupported()); } else { if (!TrySubscribeBuild(mdMsg)) RaiseNewOutMessage(transactionId.CreateNotSupported()); } return true; } } if (mdMsg.BuildMode == MarketDataBuildModes.Build) { if (!TrySubscribeBuild(mdMsg)) RaiseNewOutMessage(transactionId.CreateNotSupported()); return true; } if (mdMsg.DataType2.MessageType == typeof(TimeFrameCandleMessage)) { var originalTf = mdMsg.GetTimeFrame(); var timeFrames = InnerAdapter.GetTimeFrames(mdMsg.SecurityId, mdMsg.From, mdMsg.To).ToArray(); if (timeFrames.Contains(originalTf) || InnerAdapter.CheckTimeFrameByRequest) { this.AddInfoLog("Origin tf: {0}", originalTf); var original = mdMsg.TypedClone(); if (mdMsg.To == null && mdMsg.BuildMode == MarketDataBuildModes.LoadAndBuild && !mdMsg.IsFinishedOnly && !InnerAdapter.IsSupportCandlesUpdates && InnerAdapter.TryGetCandlesBuildFrom(original, _candleBuilderProvider) != null) { mdMsg.To = DateTimeOffset.Now; } lock (_syncObject) { _series.Add(transactionId, new SeriesInfo(original, original) { State = SeriesStates.Regular, LastTime = original.From, Count = original.Count, }); } break; } if (isLoadOnly) { RaiseNewOutMessage(transactionId.CreateNotSupported()); return true; } if (mdMsg.AllowBuildFromSmallerTimeFrame) { var smaller = timeFrames .FilterSmallerTimeFrames(originalTf) .OrderByDescending() .FirstOr(); if (smaller != null) { this.AddInfoLog("Smaller tf: {0}->{1}", originalTf, smaller); var original = mdMsg.TypedClone(); var current = original.TypedClone(); current.SetArg(smaller); lock (_syncObject) { _series.Add(transactionId, new SeriesInfo(original, current) { State = SeriesStates.SmallTimeFrame, BigTimeFrameCompressor = new BiggerTimeFrameCandleCompressor(original, _candleBuilderProvider.Get(typeof(TimeFrameCandleMessage))), LastTime = original.From, Count = original.Count, }); } return base.OnSendInMessage(current); } } if (!TrySubscribeBuild(mdMsg)) { RaiseNewOutMessage(transactionId.CreateNotSupported()); } } else { if (InnerAdapter.IsCandlesSupported(mdMsg)) { this.AddInfoLog("Origin arg: {0}", mdMsg.GetArg()); var original = mdMsg.TypedClone(); lock (_syncObject) { _series.Add(transactionId, new SeriesInfo(original, original) { State = SeriesStates.Regular, LastTime = original.From, Count = original.Count, }); } break; } else { if (isLoadOnly || !TrySubscribeBuild(mdMsg)) { RaiseNewOutMessage(transactionId.CreateNotSupported()); } } } return true; } else { var series = TryRemoveSeries(mdMsg.OriginalTransactionId); if (series == null) { var sentResponse = false; lock (_syncObject) { if (_allChilds.TryGetAndRemove(mdMsg.OriginalTransactionId, out var child)) { child.Stopped = true; sentResponse = true; } } if (sentResponse) { RaiseNewOutMessage(mdMsg.CreateResponse()); return true; } break; } else { // TODO sub childs } var unsubscribe = series.Current.TypedClone(); unsubscribe.OriginalTransactionId = unsubscribe.TransactionId; unsubscribe.TransactionId = transactionId; unsubscribe.IsSubscribe = false; message = unsubscribe; break; } } } return base.OnSendInMessage(message); } private SeriesInfo TryGetSeries(long id, out long originalId) { lock (_syncObject) { if (_replaceId.TryGetValue(id, out originalId)) id = originalId; else originalId = id; return _series.TryGetValue(id); } } private SeriesInfo TryRemoveSeries(long id) { this.AddInfoLog("Series removing {0}.", id); lock (_syncObject) { if (!_series.TryGetAndRemove(id, out var series)) return null; _replaceId.RemoveWhere(p => p.Value == id); return series; } } private MarketDataMessage TryCreateBuildSubscription(MarketDataMessage original, DateTimeOffset? lastTime, long? count, bool needCalcCount) { if (original == null) throw new ArgumentNullException(nameof(original)); var buildFrom = InnerAdapter.TryGetCandlesBuildFrom(original, _candleBuilderProvider); if (buildFrom == null) return null; if (needCalcCount && count is null) count = GetMaxCount(buildFrom); var current = new MarketDataMessage { DataType2 = buildFrom, From = lastTime, To = original.To, Count = count, MaxDepth = original.MaxDepth, BuildField = original.BuildField, IsSubscribe = true, }; original.CopyTo(current, false); this.AddInfoLog("Build tf: {0}->{1}", buildFrom, original.GetArg()); return current; } private bool TrySubscribeBuild(MarketDataMessage original) { var current = TryCreateBuildSubscription(original, original.From, original.Count, false); if (current == null) return false; current.TransactionId = original.TransactionId; var series = new SeriesInfo(original.TypedClone(), current) { LastTime = current.From, Count = current.Count, Transform = CreateTransform(current), State = SeriesStates.Compress, }; lock (_syncObject) _series.Add(original.TransactionId, series); base.OnSendInMessage(current); return true; } private static ICandleBuilderValueTransform CreateTransform(MarketDataMessage current) { return CreateTransform(current.DataType2, current.BuildField); } private static ICandleBuilderValueTransform CreateTransform(DataType dataType, Level1Fields? field) { if (dataType == DataType.Ticks) { return new TickCandleBuilderValueTransform(); } else if (dataType == DataType.MarketDepth) { var t = new QuoteCandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } else if (dataType == DataType.Level1) { var t = new Level1CandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } else if (dataType == DataType.OrderLog) { var t = new OrderLogCandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } else throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1219); } /// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.SubscriptionResponse: { var response = (SubscriptionResponseMessage)message; var requestId = response.OriginalTransactionId; var series = TryGetSeries(requestId, out _); if (series == null) break; if (response.IsOk()) { if (series.Id == requestId) RaiseNewOutMessage(message); } else UpgradeSubscription(series, response, null); return; } case MessageTypes.SubscriptionFinished: { var finishMsg = (SubscriptionFinishedMessage)message; var subscriptionId = finishMsg.OriginalTransactionId; var series = TryGetSeries(subscriptionId, out _); if (series == null) break; UpgradeSubscription(series, null, finishMsg); return; } case MessageTypes.SubscriptionOnline: { var onlineMsg = (SubscriptionOnlineMessage)message; var subscriptionId = onlineMsg.OriginalTransactionId; lock (_syncObject) { if (_series.ContainsKey(subscriptionId)) this.AddInfoLog("Series online {0}.", subscriptionId); if (_replaceId.TryGetValue(subscriptionId, out var originalId)) onlineMsg.OriginalTransactionId = originalId; } break; } case MessageTypes.Execution: case MessageTypes.QuoteChange: case MessageTypes.Level1Change: { if (message.Type == MessageTypes.QuoteChange && ((QuoteChangeMessage)message).State != null) break; if (message.Type == MessageTypes.Execution && !((ExecutionMessage)message).IsMarketData()) break; var subscrMsg = (ISubscriptionIdMessage)message; if (ProcessValue(subscrMsg)) return; break; } default: { if (message is CandleMessage candleMsg) { if (candleMsg.Type == MessageTypes.CandleTimeFrame) { var subscriptionIds = candleMsg.GetSubscriptionIds(); HashSet<long> newSubscriptionIds = null; foreach (var subscriptionId in subscriptionIds) { var series = TryGetSeries(subscriptionId, out _); if (series == null) continue; if (newSubscriptionIds == null) newSubscriptionIds = new HashSet<long>(subscriptionIds); newSubscriptionIds.Remove(subscriptionId); switch (series.State) { case SeriesStates.Regular: ProcessCandle(series, candleMsg); break; case SeriesStates.SmallTimeFrame: if (series.Count <= 0) break; var candles = series.BigTimeFrameCompressor.Process(candleMsg); foreach (var bigCandle in candles) { var isFinished = bigCandle.State == CandleStates.Finished; if (series.Current.IsFinishedOnly && !isFinished) continue; bigCandle.SetSubscriptionIds(subscriptionId: series.Id); bigCandle.Adapter = candleMsg.Adapter; if (isFinished) { series.LastTime = bigCandle.CloseTime; if (series.Count != null) { if (series.Count <= 0) break; series.Count--; } } base.OnInnerAdapterNewOutMessage(bigCandle.TypedClone()); } break; // TODO default } } if (newSubscriptionIds != null) { if (newSubscriptionIds.Count == 0) return; candleMsg.SetSubscriptionIds(newSubscriptionIds.ToArray()); } } else { var subscriptionIds = candleMsg.GetSubscriptionIds(); HashSet<long> newSubscriptionIds = null; foreach (var subscriptionId in subscriptionIds) { var series = TryGetSeries(subscriptionId, out _); if (series == null) continue; if (newSubscriptionIds == null) newSubscriptionIds = new HashSet<long>(subscriptionIds); newSubscriptionIds.Remove(subscriptionId); ProcessCandle(series, candleMsg); } if (newSubscriptionIds != null) { if (newSubscriptionIds.Count == 0) return; candleMsg.SetSubscriptionIds(newSubscriptionIds.ToArray()); } } } break; } } base.OnInnerAdapterNewOutMessage(message); } private void UpgradeSubscription(SeriesInfo series, SubscriptionResponseMessage response, SubscriptionFinishedMessage finish) { if (series == null) throw new ArgumentNullException(nameof(series)); var original = series.Original; void Finish() { TryRemoveSeries(series.Id); if (response != null && !response.IsOk()) { response = response.TypedClone(); response.OriginalTransactionId = original.TransactionId; RaiseNewOutMessage(response); } else RaiseNewOutMessage(new SubscriptionFinishedMessage { OriginalTransactionId = original.TransactionId }); } if (finish?.NextFrom != null) series.LastTime = finish.NextFrom; if (original.To != null && series.LastTime != null && original.To <= series.LastTime) { Finish(); return; } if (original.Count != null && series.Count <= 0) { Finish(); return; } switch (series.State) { case SeriesStates.Regular: { var isLoadOnly = series.Original.BuildMode == MarketDataBuildModes.Load; // upgrade to smaller tf only in case failed subscription if (response != null && original.DataType2.MessageType == typeof(TimeFrameCandleMessage) && original.AllowBuildFromSmallerTimeFrame) { if (isLoadOnly) { Finish(); return; } var smaller = InnerAdapter .GetTimeFrames(original.SecurityId, series.LastTime, original.To) .FilterSmallerTimeFrames(original.GetTimeFrame()) .OrderByDescending() .FirstOr(); if (smaller != null) { var newTransId = TransactionIdGenerator.GetNextId(); series.Current = original.TypedClone(); series.Current.SetArg(smaller); series.Current.TransactionId = newTransId; series.BigTimeFrameCompressor = new BiggerTimeFrameCandleCompressor(original, _candleBuilderProvider.Get(typeof(TimeFrameCandleMessage))); series.State = SeriesStates.SmallTimeFrame; series.NonFinishedCandle = null; lock (_syncObject) _replaceId.Add(series.Current.TransactionId, series.Id); this.AddInfoLog("Series smaller tf: ids {0}->{1}", original.TransactionId, newTransId); // loopback series.Current.LoopBack(this); RaiseNewOutMessage(series.Current); return; } } if (response == null && isLoadOnly) { Finish(); return; } series.State = SeriesStates.Compress; break; } case SeriesStates.SmallTimeFrame: { series.BigTimeFrameCompressor = null; series.State = SeriesStates.Compress; break; } case SeriesStates.Compress: { Finish(); return; } //case SeriesStates.None: default: throw new ArgumentOutOfRangeException(nameof(series), series.State, LocalizedStrings.Str1219); } if (series.State != SeriesStates.Compress) throw new InvalidOperationException(series.State.ToString()); series.NonFinishedCandle = null; var current = TryCreateBuildSubscription(original, series.LastTime, null, series.Count != null); if (current == null) { Finish(); return; } current.TransactionId = TransactionIdGenerator.GetNextId(); lock (_syncObject) _replaceId.Add(current.TransactionId, series.Id); this.AddInfoLog("Series compress: ids {0}->{1}", original.TransactionId, current.TransactionId); series.Transform = CreateTransform(current); series.Current = current; // loopback current.LoopBack(this); RaiseNewOutMessage(current); } private void ProcessCandle(SeriesInfo info, CandleMessage candleMsg) { if (info.LastTime != null && info.LastTime > candleMsg.OpenTime) return; if (info.Count <= 0) return; info.LastTime = candleMsg.OpenTime; var nonFinished = info.NonFinishedCandle; if (nonFinished != null && nonFinished.OpenTime < candleMsg.OpenTime) { nonFinished.State = CandleStates.Finished; nonFinished.LocalTime = candleMsg.LocalTime; RaiseNewOutCandle(info, nonFinished); info.NonFinishedCandle = null; } candleMsg = candleMsg.TypedClone(); if (candleMsg.Type == MessageTypes.CandleTimeFrame && !SendFinishedCandlesImmediatelly) { // make all incoming candles as Active until next come candleMsg.State = CandleStates.Active; } SendCandle(info, candleMsg); if (candleMsg.State != CandleStates.Finished) info.NonFinishedCandle = candleMsg.TypedClone(); } private bool ProcessValue(ISubscriptionIdMessage message) { var subsciptionIds = message.GetSubscriptionIds(); HashSet<long> newSubscriptionIds = null; foreach (var id in subsciptionIds) { var series = TryGetSeries(id, out var subscriptionId); if (series == null) continue; if (newSubscriptionIds == null) newSubscriptionIds = new HashSet<long>(subsciptionIds); newSubscriptionIds.Remove(id); var isAll = series.Original.SecurityId == default; if (isAll) { SubscriptionSecurityAllMessage allMsg = null; lock (_syncObject) { series = series.Child.SafeAdd(((ISecurityIdMessage)message).SecurityId, key => { allMsg = new SubscriptionSecurityAllMessage(); series.Original.CopyTo(allMsg); allMsg.ParentTransactionId = series.Original.TransactionId; allMsg.TransactionId = TransactionIdGenerator.GetNextId(); allMsg.SecurityId = key; allMsg.LoopBack(this, MessageBackModes.Chain); _pendingLoopbacks.Add(allMsg.TransactionId, RefTuple.Create(allMsg.ParentTransactionId, SubscriptionStates.Stopped)); this.AddDebugLog("New ALL candle-map: {0}/{1} TrId={2}-{3}", key, series.Original.DataType2, allMsg.ParentTransactionId, allMsg.TransactionId); return new SeriesInfo(allMsg, allMsg) { LastTime = allMsg.From, Count = allMsg.Count, Transform = CreateTransform(series.Current), State = SeriesStates.Compress, }; }); if (series.Stopped) continue; } if (allMsg != null) RaiseNewOutMessage(allMsg); } var transform = series.Transform; if (transform?.Process((Message)message) != true) continue; var time = transform.Time; var origin = series.Original; if (origin.To != null && origin.To.Value < time) { TryRemoveSeries(subscriptionId); RaiseNewOutMessage(new SubscriptionFinishedMessage { OriginalTransactionId = origin.TransactionId }); continue; } if (series.LastTime != null && series.LastTime.Value > time) continue; if (series.Count <= 0) continue; series.LastTime = time; var builder = _candleBuilderProvider.Get(origin.DataType2.MessageType); var result = builder.Process(series, transform); foreach (var candleMessage in result) { if (series.Original.IsFinishedOnly && candleMessage.State != CandleStates.Finished) continue; SendCandle(series, candleMessage.TypedClone()); } } if (newSubscriptionIds != null) { if (newSubscriptionIds.Count == 0) return true; message.SetSubscriptionIds(newSubscriptionIds.ToArray()); } return false; } private void SendCandle(SeriesInfo info, CandleMessage candleMsg) { candleMsg.Adapter = candleMsg.Adapter; candleMsg.OriginalTransactionId = info.Id; candleMsg.SetSubscriptionIds(subscriptionId: info.Id); RaiseNewOutCandle(info, candleMsg); } private void RaiseNewOutCandle(SeriesInfo info, CandleMessage candleMsg) { if (candleMsg.State == CandleStates.Finished) { if (info.Count != null) info.Count--; } RaiseNewOutMessage(candleMsg); } /// <summary> /// Create a copy of <see cref="CandleBuilderMessageAdapter"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() { return new CandleBuilderMessageAdapter(InnerAdapter.TypedClone(), _candleBuilderProvider) { SendFinishedCandlesImmediatelly = SendFinishedCandlesImmediatelly }; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CarMarketPlace.Areas.HelpPage.ModelDescriptions; using CarMarketPlace.Areas.HelpPage.Models; namespace CarMarketPlace.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Globalization; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test.Text { [TestFixture, Category("Formatting"), Category("Parse")] public class ValueCursorTest : TextCursorTestBase { internal override TextCursor MakeCursor(string value) { return new ValueCursor(value); } [Test] public void Match_Char() { var value = new ValueCursor("abc"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.True(value.Match('a'), "First character"); Assert.True(value.Match('b'), "Second character"); Assert.True(value.Match('c'), "Third character"); Assert.False(value.MoveNext(), "GetNext() end"); } [Test] public void Match_String() { var value = new ValueCursor("abc"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.True(value.Match("abc")); Assert.False(value.MoveNext(), "GetNext() end"); } [Test] public void Match_StringNotMatched() { var value = new ValueCursor("xabcdef"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.False(value.Match("abc")); ValidateCurrentCharacter(value, 0, 'x'); } [Test] public void Match_StringOverLongStringToMatch() { var value = new ValueCursor("x"); Assert.True(value.MoveNext()); Assert.False(value.Match("long string")); ValidateCurrentCharacter(value, 0, 'x'); } [Test] public void MatchCaseInsensitive_MatchAndMove() { var value = new ValueCursor("abcd"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.True(value.MatchCaseInsensitive("AbC", CultureInfo.InvariantCulture.CompareInfo, true)); ValidateCurrentCharacter(value, 3, 'd'); } [Test] public void MatchCaseInsensitive_MatchWithoutMoving() { var value = new ValueCursor("abcd"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.True(value.MatchCaseInsensitive("AbC", CultureInfo.InvariantCulture.CompareInfo, false)); // We're still looking at the start ValidateCurrentCharacter(value, 0, 'a'); } [Test] public void MatchCaseInsensitive_StringNotMatched() { var value = new ValueCursor("xabcdef"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.False(value.MatchCaseInsensitive("abc", CultureInfo.InvariantCulture.CompareInfo, true)); ValidateCurrentCharacter(value, 0, 'x'); } [Test] public void MatchCaseInsensitive_StringOverLongStringToMatch() { var value = new ValueCursor("x"); Assert.True(value.MoveNext()); Assert.False(value.MatchCaseInsensitive("long string", CultureInfo.InvariantCulture.CompareInfo, true)); ValidateCurrentCharacter(value, 0, 'x'); } [Test] public void Match_StringPartial() { var value = new ValueCursor("abcdef"); Assert.True(value.MoveNext(), "GetNext() 1"); Assert.True(value.Match("abc")); ValidateCurrentCharacter(value, 3, 'd'); } [Test] public void ParseDigits_TooFewDigits() { var value = new ValueCursor("a12b"); Assert.True(value.MoveNext()); ValidateCurrentCharacter(value, 0, 'a'); Assert.True(value.MoveNext()); int actual; Assert.False(value.ParseDigits(3, 3, out actual)); ValidateCurrentCharacter(value, 1, '1'); } [Test] public void ParseDigits_NoNumber() { var value = new ValueCursor("abc"); Assert.True(value.MoveNext()); int actual; Assert.False(value.ParseDigits(1, 2, out actual)); ValidateCurrentCharacter(value, 0, 'a'); } [Test] public void ParseDigits_Maximum() { var value = new ValueCursor("12"); Assert.True(value.MoveNext()); int actual; Assert.True(value.ParseDigits(1, 2, out actual)); Assert.AreEqual(12, actual); } [Test] public void ParseDigits_MaximumMoreDigits() { var value = new ValueCursor("1234"); Assert.True(value.MoveNext()); int actual; Assert.True(value.ParseDigits(1, 2, out actual)); Assert.AreEqual(12, actual); ValidateCurrentCharacter(value, 2, '3'); } [Test] public void ParseDigits_Minimum() { var value = new ValueCursor("1"); value.MoveNext(); int actual; Assert.True(value.ParseDigits(1, 2, out actual)); Assert.AreEqual(1, actual); ValidateEndOfString(value); } [Test] public void ParseDigits_MinimumNonDigits() { var value = new ValueCursor("1abc"); Assert.True(value.MoveNext()); int actual; Assert.True(value.ParseDigits(1, 2, out actual)); Assert.AreEqual(1, actual); ValidateCurrentCharacter(value, 1, 'a'); } [Test] public void ParseDigits_NonAscii_NeverMatches() { // Arabic-Indic digits 0 and 1. See // http://www.unicode.org/charts/PDF/U0600.pdf var value = new ValueCursor("\u0660\u0661"); Assert.True(value.MoveNext()); int actual; Assert.False(value.ParseDigits(1, 2, out actual)); } [Test] public void ParseInt64Digits_TooFewDigits() { var value = new ValueCursor("a12b"); Assert.True(value.MoveNext()); ValidateCurrentCharacter(value, 0, 'a'); Assert.True(value.MoveNext()); long actual; Assert.False(value.ParseInt64Digits(3, 3, out actual)); ValidateCurrentCharacter(value, 1, '1'); } [Test] public void ParseInt64Digits_NoNumber() { var value = new ValueCursor("abc"); Assert.True(value.MoveNext()); long actual; Assert.False(value.ParseInt64Digits(1, 2, out actual)); ValidateCurrentCharacter(value, 0, 'a'); } [Test] public void ParseInt64Digits_Maximum() { var value = new ValueCursor("12"); Assert.True(value.MoveNext()); long actual; Assert.True(value.ParseInt64Digits(1, 2, out actual)); Assert.AreEqual(12, actual); } [Test] public void ParseInt64Digits_MaximumMoreDigits() { var value = new ValueCursor("1234"); Assert.True(value.MoveNext()); long actual; Assert.True(value.ParseInt64Digits(1, 2, out actual)); Assert.AreEqual(12, actual); ValidateCurrentCharacter(value, 2, '3'); } [Test] public void ParseInt64Digits_Minimum() { var value = new ValueCursor("1"); value.MoveNext(); long actual; Assert.True(value.ParseInt64Digits(1, 2, out actual)); Assert.AreEqual(1, actual); ValidateEndOfString(value); } [Test] public void ParseInt64Digits_MinimumNonDigits() { var value = new ValueCursor("1abc"); Assert.True(value.MoveNext()); long actual; Assert.True(value.ParseInt64Digits(1, 2, out actual)); Assert.AreEqual(1, actual); ValidateCurrentCharacter(value, 1, 'a'); } [Test] public void ParseInt64Digits_NonAscii_NeverMatches() { // Arabic-Indic digits 0 and 1. See // http://www.unicode.org/charts/PDF/U0600.pdf var value = new ValueCursor("\u0660\u0661"); Assert.True(value.MoveNext()); long actual; Assert.False(value.ParseInt64Digits(1, 2, out actual)); } [Test] public void ParseInt64Digits_LargeNumber() { var value = new ValueCursor("9999999999999"); Assert.True(value.MoveNext()); long actual; Assert.True(value.ParseInt64Digits(1, 13, out actual)); Assert.AreEqual(actual, 9999999999999L); Assert.Greater(9999999999999L, int.MaxValue); } [Test] public void ParseFraction_NonAscii_NeverMatches() { // Arabic-Indic digits 0 and 1. See // http://www.unicode.org/charts/PDF/U0600.pdf var value = new ValueCursor("\u0660\u0661"); Assert.True(value.MoveNext()); int actual; Assert.False(value.ParseFraction(2, 2, out actual, 2)); } [Test] public void ParseInt64_Simple() { var value = new ValueCursor("56x"); Assert.True(value.MoveNext()); long result; Assert.IsNull(value.ParseInt64<string>(out result)); Assert.AreEqual(56L, result); // Cursor ends up post-number Assert.AreEqual(2, value.Index); } [Test] public void ParseInt64_Negative() { var value = new ValueCursor("-56x"); Assert.True(value.MoveNext()); long result; Assert.IsNull(value.ParseInt64<string>(out result)); Assert.AreEqual(-56L, result); } [Test] public void ParseInt64_NonNumber() { var value = new ValueCursor("xyz"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_DoubleNegativeSign() { var value = new ValueCursor("--10xyz"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_NegativeThenNonDigit() { var value = new ValueCursor("-x"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_NumberOutOfRange_LowLeadingDigits() { var value = new ValueCursor("1000000000000000000000000"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_NumberOutOfRange_HighLeadingDigits() { var value = new ValueCursor("999999999999999999999999"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_NumberOutOfRange_MaxValueLeadingDigits() { var value = new ValueCursor("9223372036854775808"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_NumberOutOfRange_MinValueLeadingDigits() { var value = new ValueCursor("-9223372036854775809"); Assert.True(value.MoveNext()); long result; Assert.IsNotNull(value.ParseInt64<string>(out result)); // Cursor has not moved Assert.AreEqual(0, value.Index); } [Test] public void ParseInt64_MaxValue() { var value = new ValueCursor("9223372036854775807"); Assert.True(value.MoveNext()); long result; Assert.IsNull(value.ParseInt64<string>(out result)); Assert.AreEqual(long.MaxValue, result); } [Test] public void ParseInt64_MinValue() { var value = new ValueCursor("-9223372036854775808"); Assert.True(value.MoveNext()); long result; Assert.IsNull(value.ParseInt64<string>(out result)); Assert.AreEqual(long.MinValue, result); } [Test] public void CompareOrdinal_ExactMatchToEndOfValue() { var value = new ValueCursor("xabc"); value.Move(1); Assert.AreEqual(0, value.CompareOrdinal("abc")); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_ExactMatchValueContinues() { var value = new ValueCursor("xabc"); value.Move(1); Assert.AreEqual(0, value.CompareOrdinal("ab")); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_ValueIsEarlier() { var value = new ValueCursor("xabc"); value.Move(1); Assert.Less(value.CompareOrdinal("mm"), 0); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_ValueIsLater() { var value = new ValueCursor("xabc"); value.Move(1); Assert.Greater(value.CompareOrdinal("aa"), 0); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_LongMatch_EqualToEnd() { var value = new ValueCursor("xabc"); value.Move(1); Assert.Less(value.CompareOrdinal("abcd"), 0); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_LongMatch_ValueIsEarlier() { var value = new ValueCursor("xabc"); value.Move(1); Assert.Less(value.CompareOrdinal("cccc"), 0); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } [Test] public void CompareOrdinal_LongMatch_ValueIsLater() { var value = new ValueCursor("xabc"); value.Move(1); Assert.Greater(value.CompareOrdinal("aaaa"), 0); Assert.AreEqual(1, value.Index); // Cursor hasn't moved } } }
#region License // // Copyright (c) 2007-2018, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Runner; using FluentMigrator.Runner.Exceptions; using FluentMigrator.Runner.Infrastructure; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Tests.Integration.Migrations; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit { [TestFixture] [Obsolete] public class ObsoleteMigrationRunnerTests { private MigrationRunner _runner; private Mock<IAnnouncer> _announcer; private Mock<IStopWatch> _stopWatch; private Mock<IMigrationProcessor> _processorMock; private Mock<IMigrationInformationLoader> _migrationLoaderMock; private Mock<IProfileLoader> _profileLoaderMock; private Mock<IRunnerContext> _runnerContextMock; private SortedList<long, IMigrationInfo> _migrationList; private TestVersionLoader _fakeVersionLoader; private int _applicationContext; [SetUp] public void SetUp() { _applicationContext = new Random().Next(); _migrationList = new SortedList<long, IMigrationInfo>(); _runnerContextMock = new Mock<IRunnerContext>(MockBehavior.Loose); _processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose); _migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose); _profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose); _profileLoaderMock.SetupGet(l => l.SupportsParameterlessApplyProfile).Returns(true); _announcer = new Mock<IAnnouncer>(); _stopWatch = new Mock<IStopWatch>(); _stopWatch.Setup(x => x.Time(It.IsAny<Action>())).Returns(new TimeSpan(1)).Callback((Action a) => a.Invoke()); var options = new ProcessorOptions { PreviewOnly = false }; _processorMock.SetupGet(x => x.Options).Returns(options); _processorMock.SetupGet(x => x.ConnectionString).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString); _runnerContextMock.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations"); _runnerContextMock.SetupGet(x => x.Announcer).Returns(_announcer.Object); _runnerContextMock.SetupGet(x => x.StopWatch).Returns(_stopWatch.Object); _runnerContextMock.SetupGet(x => x.Targets).Returns(new[] { Assembly.GetExecutingAssembly().ToString()}); _runnerContextMock.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString); _runnerContextMock.SetupGet(x => x.Database).Returns("sqlserver"); _runnerContextMock.SetupGet(x => x.ApplicationContext).Returns(_applicationContext); _migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList); _runner = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationRunnerTests)), _runnerContextMock.Object, _processorMock.Object) { MigrationLoader = _migrationLoaderMock.Object, ProfileLoader = _profileLoaderMock.Object, }; _fakeVersionLoader = new TestVersionLoader(_runner, _runner.VersionLoader.VersionTableMetaData); _runner.VersionLoader = _fakeVersionLoader; _processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName))) .Returns(true); _processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName), It.Is<string>(t => t == _runner.VersionLoader.VersionTableMetaData.TableName))) .Returns(true); } private void LoadVersionData(params long[] fakeVersions) { _fakeVersionLoader.Versions.Clear(); _migrationList.Clear(); foreach (var version in fakeVersions) { _fakeVersionLoader.Versions.Add(version); _migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration())); } _fakeVersionLoader.LoadVersionInfo(); } [Test] public void ProfilesAreAppliedWhenMigrateUpIsCalledWithNoVersion() { _runner.MigrateUp(); _profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once()); } [Test] public void ProfilesAreAppliedWhenMigrateUpIsCalledWithVersionParameter() { _runner.MigrateUp(2009010101); _profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once()); } [Test] public void ProfilesAreAppliedWhenMigrateDownIsCalled() { _runner.MigrateDown(2009010101); _profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once()); } /// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary> [Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")] public void CanPassApplicationContext() { IMigration migration = new TestEmptyMigration(); _runner.Up(migration); Assert.AreEqual(_applicationContext, _runnerContextMock.Object.ApplicationContext, "The runner context does not have the expected application context."); Assert.AreEqual(_applicationContext, _runner.RunnerContext?.ApplicationContext, "The MigrationRunner does not have the expected application context."); Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context."); _announcer.VerifyAll(); } [Test] public void CanPassConnectionString() { IMigration migration = new TestEmptyMigration(); _runner.Up(migration); Assert.AreEqual(IntegrationTestOptions.SqlServer2008.ConnectionString, migration.ConnectionString, "The migration does not have the expected connection string."); _announcer.VerifyAll(); } [Test] public void CanAnnounceUp() { _announcer.Setup(x => x.Heading(It.IsRegex(ContainsAll("Test", "migrating")))); _runner.Up(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanAnnounceUpFinish() { _announcer.Setup(x => x.Say(It.IsRegex(ContainsAll("Test", "migrated")))); _runner.Up(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanAnnounceDown() { _announcer.Setup(x => x.Heading(It.IsRegex(ContainsAll("Test", "reverting")))); _runner.Down(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanAnnounceDownFinish() { _announcer.Setup(x => x.Say(It.IsRegex(ContainsAll("Test", "reverted")))); _runner.Down(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanAnnounceUpElapsedTime() { var ts = new TimeSpan(0, 0, 0, 1, 3); _announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts))); _stopWatch.Setup(x => x.ElapsedTime()).Returns(ts); _runner.Up(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanAnnounceDownElapsedTime() { var ts = new TimeSpan(0, 0, 0, 1, 3); _announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts))); _stopWatch.Setup(x => x.ElapsedTime()).Returns(ts); _runner.Down(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanReportExceptions() { _processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops")); var exception = Assert.Throws<Exception>(() => _runner.Up(new TestMigration())); Assert.That(exception.Message, Does.Contain("Oops")); } [Test] public void CanSayExpression() { _announcer.Setup(x => x.Say(It.IsRegex(ContainsAll("CreateTable")))); _stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3)); _runner.Up(new TestMigration()); _announcer.VerifyAll(); } [Test] public void CanTimeExpression() { var ts = new TimeSpan(0, 0, 0, 1, 3); _announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts))); _stopWatch.Setup(x => x.ElapsedTime()).Returns(ts); _runner.Up(new TestMigration()); _announcer.VerifyAll(); } private static string ContainsAll(params string[] words) { return ".*?" + string.Join(".*?", words) + ".*?"; } [Test] public void LoadsCorrectCallingAssembly() { if (_runner.MigrationAssemblies == null) { throw new InvalidOperationException("MigrationAssemblies aren't set"); } var asm = _runner.MigrationAssemblies.Assemblies.Single(); asm.ShouldBe(Assembly.GetAssembly(typeof(MigrationRunnerTests))); } [Test] public void HasMigrationsToApplyUpWhenThereAreMigrations() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _fakeVersionLoader.Versions.Remove(fakeMigrationVersion2); _fakeVersionLoader.LoadVersionInfo(); _runner.HasMigrationsToApplyUp().ShouldBeTrue(); } [Test] public void HasMigrationsToApplyUpWhenThereAreNoNewMigrations() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _runner.HasMigrationsToApplyUp().ShouldBeFalse(); } [Test] public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasNotBeenApplied() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _fakeVersionLoader.Versions.Remove(fakeMigrationVersion2); _fakeVersionLoader.LoadVersionInfo(); _runner.HasMigrationsToApplyUp(fakeMigrationVersion2).ShouldBeTrue(); } [Test] public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasBeenApplied() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _fakeVersionLoader.Versions.Remove(fakeMigrationVersion2); _fakeVersionLoader.LoadVersionInfo(); _runner.HasMigrationsToApplyUp(fakeMigrationVersion1).ShouldBeFalse(); } [Test] public void HasMigrationsToApplyRollbackWithOneMigrationApplied() { const long fakeMigrationVersion1 = 2009010101; LoadVersionData(fakeMigrationVersion1); _runner.HasMigrationsToApplyRollback().ShouldBeTrue(); } [Test] public void HasMigrationsToApplyRollbackWithNoMigrationsApplied() { LoadVersionData(); _runner.HasMigrationsToApplyRollback().ShouldBeFalse(); } [Test] public void HasMigrationsToApplyDownWhenTheVersionHasNotBeenApplied() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _fakeVersionLoader.Versions.Remove(fakeMigrationVersion2); _fakeVersionLoader.LoadVersionInfo(); _runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeFalse(); } [Test] public void HasMigrationsToApplyDownWhenTheVersionHasBeenApplied() { const long fakeMigrationVersion1 = 2009010101; const long fakeMigrationVersion2 = 2009010102; LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2); _runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeTrue(); } [Test] public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable() { const long fakeMigrationVersion = 2009010101; const long fakeMigrationVersion2 = 2009010102; Assert.NotNull(_runner.VersionLoader.VersionTableMetaData.TableName); LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2); _runner.VersionLoader.LoadVersionInfo(); _runner.Rollback(1); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); } [Test] public void RollbackLastVersionShouldDeleteVersionInfoTable() { const long fakeMigrationVersion = 2009010101; LoadVersionData(fakeMigrationVersion); Assert.NotNull(_runner.VersionLoader.VersionTableMetaData.TableName); _runner.Rollback(1); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue(); } [Test] public void RollbackToVersionZeroShouldDeleteVersionInfoTable() { Assert.NotNull(_runner.VersionLoader.VersionTableMetaData.TableName); _runner.RollbackToVersion(0); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue(); } [Test] public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval() { var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName; _runner.RollbackToVersion(0); //Should only be called once in setup _processorMock.Verify( pm => pm.Process(It.Is<CreateTableExpression>( dte => dte.TableName == versionInfoTableName) ), Times.Once() ); } [Test] public void RollbackToVersionShouldShouldLimitMigrationsToNamespace() { const long fakeMigration1 = 2011010101; const long fakeMigration2 = 2011010102; const long fakeMigration3 = 2011010103; LoadVersionData(fakeMigration1,fakeMigration3); _fakeVersionLoader.Versions.Add(fakeMigration2); _fakeVersionLoader.LoadVersionInfo(); _runner.RollbackToVersion(2011010101); _fakeVersionLoader.Versions.ShouldContain(fakeMigration1); _fakeVersionLoader.Versions.ShouldContain(fakeMigration2); _fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3); } [Test] public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace() { const long fakeMigration1 = 2011010101; const long fakeMigration2 = 2011010102; const long fakeMigration3 = 2011010103; LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3); _migrationList.Remove(fakeMigration1); _migrationList.Remove(fakeMigration2); _fakeVersionLoader.LoadVersionInfo(); _runner.RollbackToVersion(0); _fakeVersionLoader.Versions.ShouldContain(fakeMigration1); _fakeVersionLoader.Versions.ShouldContain(fakeMigration2); _fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3); } [Test] public void RollbackShouldLimitMigrationsToNamespace() { const long fakeMigration1 = 2011010101; const long fakeMigration2 = 2011010102; const long fakeMigration3 = 2011010103; LoadVersionData(fakeMigration1, fakeMigration3); _fakeVersionLoader.Versions.Add(fakeMigration2); _fakeVersionLoader.LoadVersionInfo(); _runner.Rollback(2); _fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1); _fakeVersionLoader.Versions.ShouldContain(fakeMigration2); _fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); } [Test] public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero() { var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName; _runner.RollbackToVersion(1); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); //Once in setup _processorMock.Verify( pm => pm.Process(It.Is<CreateTableExpression>( dte => dte.TableName == versionInfoTableName) ), Times.Exactly(1) ); //After setup is done, fake version loader owns the proccess _fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true); } [Test] public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations() { const long version1 = 2011010101; const long version2 = 2011010102; var mockMigration1 = new Mock<IMigration>(); var mockMigration2 = new Mock<IMigration>(); LoadVersionData(version1, version2); _migrationList.Clear(); _migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object)); _migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object)); Assert.DoesNotThrow(() => _runner.ValidateVersionOrder()); _announcer.Verify(a => a.Say("Version ordering valid.")); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); } [Test] public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration() { const long version1 = 2011010101; const long version2 = 2011010102; var mockMigration1 = new Mock<IMigration>(); var mockMigration2 = new Mock<IMigration>(); LoadVersionData(version1); _migrationList.Clear(); _migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object)); _migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object)); Assert.DoesNotThrow(() => _runner.ValidateVersionOrder()); _announcer.Verify(a => a.Say("Version ordering valid.")); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); } [Test] public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion() { const long version1 = 2011010101; const long version2 = 2011010102; const long version3 = 2011010103; const long version4 = 2011010104; var mockMigration1 = new Mock<IMigration>(); var mockMigration2 = new Mock<IMigration>(); var mockMigration3 = new Mock<IMigration>(); var mockMigration4 = new Mock<IMigration>(); LoadVersionData(version1, version4); _migrationList.Clear(); _migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object)); _migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object)); _migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object)); _migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object)); var exception = Assert.Throws<VersionOrderInvalidException>(() => _runner.ValidateVersionOrder()); var invalidMigrations = exception.InvalidMigrations.ToList(); invalidMigrations.Count.ShouldBe(2); invalidMigrations.Select(x => x.Key).ShouldContain(version2); invalidMigrations.Select(x => x.Key).ShouldContain(version3); _fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse(); } [Test] public void CanListVersions() { const long version1 = 2011010101; const long version2 = 2011010102; const long version3 = 2011010103; const long version4 = 2011010104; var mockMigration1 = new Mock<IMigration>(); var mockMigration2 = new Mock<IMigration>(); var mockMigration3 = new Mock<IMigration>(); var mockMigration4 = new Mock<IMigration>(); LoadVersionData(version1, version3); _migrationList.Clear(); _migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object)); _migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object)); _migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object)); _migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, true, mockMigration4.Object)); _runner.ListMigrations(); _announcer.Verify(a => a.Say("2011010101: IMigrationProxy")); _announcer.Verify(a => a.Say("2011010102: IMigrationProxy (not applied)")); _announcer.Verify(a => a.Emphasize("2011010103: IMigrationProxy (current)")); _announcer.Verify(a => a.Emphasize("2011010104: IMigrationProxy (not applied, BREAKING)")); } [Test] public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError() { var invalidMigration = new Mock<IMigration>(); var invalidExpression = new UpdateDataExpression {TableName = "Test"}; invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression)); Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object)); var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows; _announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains($"UpdateDataExpression: {expectedErrorMessage}")))); } [Test] public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError() { var invalidMigration = new Mock<IMigration>(); var invalidExpression = new UpdateDataExpression { TableName = "Test" }; invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression)); Assert.Throws<InvalidMigrationException>(() => _runner.Down(invalidMigration.Object)); var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows; _announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains($"UpdateDataExpression: {expectedErrorMessage}")))); } [Test] public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors() { var invalidMigration = new Mock<IMigration>(); var invalidExpression = new UpdateDataExpression { TableName = "Test" }; var secondInvalidExpression = new CreateColumnExpression(); invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())) .Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); }); Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object)); _announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains($"UpdateDataExpression: {ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows}")))); _announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains($"CreateColumnExpression: {ErrorMessages.TableNameCannotBeNullOrEmpty}")))); } [Test] public void CanLoadCustomMigrationConventions() { Assert.That(_runner.Conventions, Is.TypeOf<MigrationRunnerTests.CustomMigrationConventions>()); } [Test] public void CanLoadDefaultMigrationConventionsIfNoCustomConventionsAreSpecified() { var processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose); var options = new ProcessorOptions { PreviewOnly = false }; processorMock.SetupGet(x => x.Options).Returns(options); var asm = "s".GetType().Assembly; var runner = new MigrationRunner(asm, _runnerContextMock.Object, processorMock.Object); Assert.That(runner.Conventions, Is.TypeOf<DefaultMigrationRunnerConventions>()); } [Test] public void CanBlockBreakingChangesByDefault() { InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => _runner.ApplyMigrationUp( new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true)); Assert.NotNull(ex); Assert.AreEqual( "The migration 7: TestBreakingMigration is identified as a breaking change, and will not be executed unless the necessary flag (allow-breaking-changes|abc) is passed to the runner.", ex.Message); } [Test] public void CanRunBreakingChangesIfSpecified() { _runnerContextMock.SetupGet(rcm => rcm.AllowBreakingChange).Returns(true); Assert.DoesNotThrow(() => _runner.ApplyMigrationUp( new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true)); } [Test] public void CanRunBreakingChangesInPreview() { _runnerContextMock.SetupGet(rcm => rcm.PreviewOnly).Returns(true); _runnerContextMock.SetupGet(rcm => rcm.AllowBreakingChange).Returns(true); Assert.DoesNotThrow(() => _runner.ApplyMigrationUp( new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.IO; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== XmlResolver ===================== public class TCXmlResolver : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; private ExceptionVerifier _exVerifier; public TCXmlResolver(ITestOutputHelper output): base(output) { _output = output; _exVerifier = new ExceptionVerifier("System.Xml", _output); } //BUG #304124 [Fact] public void DefaultValueForXmlResolver_XmlUrlResolver() { XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("t", "uri:tempuri"); XmlSchemaValidator val = new XmlSchemaValidator(new NameTable(), CreateSchemaSetFromXml("<root />"), manager, AllFlags); XmlSchemaInfo info = new XmlSchemaInfo(); val.XmlResolver = new XmlUrlResolver(); //Adding this as the default resolver is null and not XmlUrlResolver anymore val.Initialize(); val.ValidateElement("foo", "", null, "t:type1", null, "uri:tempuri " + Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE), null); val.ValidateEndOfAttributes(null); val.ValidateElement("bar", "", null); val.ValidateEndOfAttributes(null); val.ValidateEndElement(null); val.ValidateEndElement(info); Assert.Equal(XmlSchemaContentType.ElementOnly, info.ContentType); Assert.True(info.SchemaType != null); return; } [Theory] [InlineData(true)] [InlineData(false)] public void UsingCustomXmlResolverWith_SchemaLocation_NoNamespaceSchemaLocation(bool schemaLocation) { CXmlTestResolver res = new CXmlTestResolver(); CResolverHolder holder = new CResolverHolder(); res.CalledResolveUri += new XmlTestResolverEventHandler(holder.CallBackResolveUri); res.CalledGetEntity += new XmlTestResolverEventHandler(holder.CallBackGetEntity); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); XmlSchemaValidator val = new XmlSchemaValidator(new NameTable(), new XmlSchemaSet(), manager, AllFlags); val.XmlResolver = res; val.Initialize(); if (schemaLocation) { manager.AddNamespace("t", "uri:tempuri"); val.ValidateElement("foo", "", null, "t:type1", null, "uri:tempuri " + Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE), null); } else { val.ValidateElement("foo", "", null, "type1", null, null, XSDFILE_NO_TARGET_NAMESPACE); } Assert.True(holder.IsCalledResolveUri); Assert.True(holder.IsCalledGetEntity); return; } [Fact] public void InternalSchemaSetShouldUseSeparateXmlResolver() { CXmlTestResolver res = new CXmlTestResolver(); CResolverHolder holder = new CResolverHolder(); res.CalledResolveUri += new XmlTestResolverEventHandler(holder.CallBackResolveUri); res.CalledGetEntity += new XmlTestResolverEventHandler(holder.CallBackGetEntity); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); XmlSchemaValidator val = new XmlSchemaValidator(new NameTable(), new XmlSchemaSet(){ XmlResolver = new XmlUrlResolver()}, manager, AllFlags); val.XmlResolver = res; val.Initialize(); val.AddSchema(XmlSchema.Read(XmlReader.Create(Path.Combine(TestData, XSDFILE_VALIDATE_ATTRIBUTE)), null)); // this schema has xs:import val.ValidateElement("NoAttributesElement", "", null); Assert.True(!holder.IsCalledResolveUri); Assert.True(!holder.IsCalledGetEntity); return; } [Fact] public void SetResolverToCustomValidateSomethignChangeResolverThenVerify() { CXmlTestResolver res = new CXmlTestResolver(); CResolverHolder holder = new CResolverHolder(); res.CalledResolveUri += new XmlTestResolverEventHandler(holder.CallBackResolveUri); res.CalledGetEntity += new XmlTestResolverEventHandler(holder.CallBackGetEntity); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = new XmlSchemaValidator(new NameTable(), new XmlSchemaSet(), manager, AllFlags); val.XmlResolver = res; val.Initialize(); val.ValidateElement("foo", "", null, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE)); val.SkipToEndElement(null); Assert.True(holder.IsCalledResolveUri); Assert.True(holder.IsCalledGetEntity); val.XmlResolver = new XmlUrlResolver(); holder.IsCalledGetEntity = false; holder.IsCalledResolveUri = false; val.ValidateElement("foo", "", null, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE)); Assert.True(!holder.IsCalledResolveUri); Assert.True(!holder.IsCalledGetEntity); return; } [Fact] public void SetResolverToCustomValidateSomethingSetResolverToNullThenVerify() { CXmlTestResolver res = new CXmlTestResolver(); CResolverHolder holder = new CResolverHolder(); res.CalledResolveUri += new XmlTestResolverEventHandler(holder.CallBackResolveUri); res.CalledGetEntity += new XmlTestResolverEventHandler(holder.CallBackGetEntity); XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = new XmlSchemaValidator(new NameTable(), new XmlSchemaSet(), manager, AllFlags); val.XmlResolver = res; val.Initialize(); val.ValidateElement("foo", "", null, "type1", null, null, Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE)); val.SkipToEndElement(null); Assert.True(holder.IsCalledResolveUri); Assert.True(holder.IsCalledGetEntity); manager.AddNamespace("t", "uri:tempuri"); val.XmlResolver = null; try { val.ValidateElement("bar", "", null, "t:type1", null, "uri:tempuri " + Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE), null); Assert.True(false); } catch (XmlSchemaValidationException e) { _exVerifier.IsExceptionOk(e, "Sch_XsiTypeNotFound", new string[] { "uri:tempuri:type1" }); return; } Assert.True(false); } } // ===================== LineInfoProvider ===================== public class TCLineInfoProvider : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCLineInfoProvider(ITestOutputHelper output): base(output) { _output = output; } [Theory] [InlineData("default")] [InlineData("custom")] public void Default_Custom_ValueForLineInfoProvider(string param) { string xmlSrc = "<root><foo>FooText</foo><bar>BarText</bar></root>"; XmlSchemaInfo info = new XmlSchemaInfo(); int lineNum = -1; int linePos = -1; XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml(xmlSrc)); switch (param) { case "default": lineNum = 0; linePos = 0; break; case "custom": lineNum = 1111; linePos = 2222; val.LineInfoProvider = new CDummyLineInfo(lineNum, linePos); break; default: Assert.True(false); break; } val.Initialize(); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("foo", "", info); Assert.Equal(val.LineInfoProvider.LineNumber, lineNum); Assert.Equal(val.LineInfoProvider.LinePosition, linePos); val.SkipToEndElement(info); try { val.ValidateElement("bar2", "", info); Assert.True(false); } catch (XmlSchemaValidationException e) { Assert.Equal(e.LineNumber, lineNum); Assert.Equal(e.LinePosition, linePos); } return; } // BUG 304165 [Fact] public void LineInfoProviderChangesDuringValidation() { string xmlSrc = "<root><foo>FooText</foo></root>"; XmlSchemaInfo info = new XmlSchemaInfo(); CValidationEventHolder holder = new CValidationEventHolder(); int lineNum = -1; int linePos = -1; XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml(xmlSrc)); val.ValidationEventHandler += holder.CallbackA; val.Initialize(); foreach (int i in new int[] { 1111, 1333, 0 }) { lineNum = i; linePos = i * 2; if (i == 0) val.LineInfoProvider = null; else val.LineInfoProvider = new CDummyLineInfo(lineNum, linePos); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); Assert.Equal(holder.lastException.LineNumber, lineNum); Assert.Equal(holder.lastException.LinePosition, linePos); val.SkipToEndElement(info); val.SkipToEndElement(info); holder.IsCalledA = false; } return; } [Fact] public void XmlReaderAsALineInfoProvider() { string xmlSrc = "<root>\n" + " <foo>\n" + " FooText\n" + " </foo>\n" + "</root>"; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml(xmlSrc)); XmlReader r = XmlReader.Create(new StringReader(xmlSrc)); val.LineInfoProvider = (r as IXmlLineInfo); val.Initialize(); r.ReadStartElement("root"); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); try { r.ReadStartElement("foo"); val.ValidateElement("bar", "", info); Assert.True(false); } catch (XmlSchemaValidationException e) { Assert.Equal(2, e.LineNumber); Assert.Equal(8, e.LinePosition); } return; } } // ===================== SourceUri ===================== public class TCSourceUri : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCSourceUri(ITestOutputHelper output): base(output) { _output = output; } [Theory] [InlineData("default")] [InlineData("")] [InlineData("urn:tempuri")] [InlineData("\\\\wddata\\some\\path")] [InlineData("http://tempuri.com/schemas")] [InlineData("file://tempuri.com/schemas")] public void Default_Empty_RelativeUri_NetworkFolder_HTTP_FILE_ForSourceURI(string sourceUri) { string xmlSrc = "<root>foo</root>"; Uri tempUri; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml(xmlSrc)); if (sourceUri != "default" && sourceUri != string.Empty && sourceUri != null) { tempUri = new Uri(sourceUri); val.SourceUri = tempUri; } else tempUri = null; Assert.Equal(tempUri, val.SourceUri); val.Initialize(); try { val.ValidateElement("bar", "", info); Assert.True(false, "Validation Error - XmlSchemaValidationException wasn't thrown!"); } catch (XmlSchemaValidationException e) { Assert.True((tempUri == null && e.SourceUri == null) || (tempUri.ToString() == e.SourceUri)); } return; } [Fact] public void SourceUriChangesDuringValidation() { string xmlSrc = "<root><foo><bar/></foo></root>"; Uri tempUri; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml(xmlSrc)); tempUri = new Uri("file://tempuri.com/schemas"); val.SourceUri = tempUri; val.Initialize(); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("foo", "", info); tempUri = new Uri("urn:relativepath"); val.SourceUri = tempUri; Assert.Equal(tempUri, val.SourceUri); val.ValidateEndOfAttributes(null); try { val.ValidateElement("bar2", "", info); Assert.True(false); } catch (XmlSchemaValidationException e) { Assert.Equal(tempUri.ToString(), e.SourceUri); } return; } } // ===================== ValidationEvent handling ===================== public class TCValidationEventHandling : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCValidationEventHandling(ITestOutputHelper output): base(output) { _output = output; } [Theory] [InlineData("default")] [InlineData("null")] [InlineData("arbitrary")] [InlineData("reader")] [InlineData("document")] [InlineData("navigator")] public void Default_Null_ArbitraryObject_XmlReader_XmlDocument_XPathNavigator_ProvidedAsValidationEventSender(string param) { XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root>foo</root>")); CValidationEventHolder holder = new CValidationEventHolder(); object sender = null; val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA); switch (param) { case "default": sender = val; break; case "null": sender = null; break; case "arbitrary": sender = new ArrayList(); break; case "reader": sender = XmlReader.Create(new StringReader("<root/>")); break; case "document": sender = new XmlDocument(); break; case "navigator": XmlDocument d = new XmlDocument(); sender = d.CreateNavigator(); break; default: Assert.True(false); break; } if (param != "default") val.ValidationEventSender = sender; val.Initialize(); val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); Assert.Equal(sender, holder.lastObjectSent); return; } [Fact] public void ErrorHandlingAfterValidationError() { XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root><foo/></root>")); CValidationEventHolder holder = new CValidationEventHolder(); val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA); val.Initialize(); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); val.SkipToEndElement(info); val.SkipToEndElement(info); holder.IsCalledA = false; val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); return; } [Fact] public void SanityTestsForValidationEventHandler() { XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root>foo</root>")); CValidationEventHolder holder = new CValidationEventHolder(); val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA); val.Initialize(); val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); return; } [Fact] public void MultipleEventHandlersAttachedToValidator() { XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root>foo</root>")); CValidationEventHolder holder = new CValidationEventHolder(); val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackA); val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackB); val.Initialize(); val.ValidateElement("bar", "", info); Assert.True(holder.IsCalledA); Assert.True(holder.IsCalledB); return; } [Fact] public void ValidationCallProducesValidationErrorInsideValidationEventHandler__Nesting() { XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaValidator val = CreateValidator(CreateSchemaSetFromXml("<root>foo</root>")); CValidationEventHolder holder = new CValidationEventHolder(); val.ValidationEventHandler += new ValidationEventHandler(holder.CallbackNested); val.Initialize(); val.ValidateElement("bar", "", info); Assert.Equal(3, holder.NestingDepth); return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Tests { public class UTF8EncodingDecode { public static IEnumerable<object[]> Decode_TestData() { // All ASCII chars for (char c = char.MinValue; c <= 0x7F; c++) { yield return new object[] { new byte[] { (byte)c }, 0, 1, c.ToString() }; yield return new object[] { new byte[] { 97, (byte)c, 98 }, 1, 1, c.ToString() }; yield return new object[] { new byte[] { 97, (byte)c, 98 }, 0, 3, "a" + c.ToString() + "b" }; } // Mixture of ASCII and Unicode yield return new object[] { new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, 0, 8, "FooBA\u0400R" }; yield return new object[] { new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, 0, 9, "\u00C0nima\u0300l" }; yield return new object[] { new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, 0, 12, "Test\uD803\uDD75Test" }; yield return new object[] { new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, 0, 15, "\0Te\nst\0\t\0T\u000Fest\0" }; yield return new object[] { new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, 0, 12, "\uD803\uDD75\uD803\uDD75\uD803\uDD75" }; yield return new object[] { new byte[] { 196, 176 }, 0, 2, "\u0130" }; yield return new object[] { new byte[] { 0x61, 0xCC, 0x8A }, 0, 3, "\u0061\u030A" }; yield return new object[] { new byte[] { 0xC2, 0xA4, 0xC3, 0x90, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xC2, 0xA3, 0xC2, 0xA4 }, 0, 16, "\u00A4\u00D0aR|{AnGe\u00A3\u00A4" }; yield return new object[] { new byte[] { 0x00, 0x7F }, 0, 2, "\u0000\u007F" }; yield return new object[] { new byte[] { 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F }, 0, 14, "\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F" }; yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF }, 0, 4, "\u0080\u07FF" }; yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF }, 0, 16, "\u0080\u07FF\u0080\u07FF\u0080\u07FF\u0080\u07FF" }; yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 6, "\u0800\u0FFF" }; yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 18, "\u0800\u0FFF\u0800\u0FFF\u0800\u0FFF" }; yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 6, "\u1000\uCFFF" }; yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 18, "\u1000\uCFFF\u1000\uCFFF\u1000\uCFFF" }; yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 6, "\uD000\uD7FF" }; yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 18, "\uD000\uD7FF\uD000\uD7FF\uD000\uD7FF" }; yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD800\uDC00\uD8BF\uDFFF" }; yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD800\uDC00\uD8BF\uDFFF\uD800\uDC00\uD8BF\uDFFF" }; yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD8C0\uDC00\uDBBF\uDFFF" }; yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF, 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD8C0\uDC00\uDBBF\uDFFF\uD8C0\uDC00\uDBBF\uDFFF" }; yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 8, "\uDBC0\uDC00\uDBFF\uDFFF" }; yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF, 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 16, "\uDBC0\uDC00\uDBFF\uDFFF\uDBC0\uDC00\uDBFF\uDFFF" }; // Long ASCII strings yield return new object[] { new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, 0, 10, "TestString" }; yield return new object[] { new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, 0, 8, "TestTest" }; // Control codes yield return new object[] { new byte[] { 0x1F, 0x10, 0x00, 0x09 }, 0, 4, "\u001F\u0010\u0000\u0009" }; yield return new object[] { new byte[] { 0x1F, 0x00, 0x10, 0x09 }, 0, 4, "\u001F\u0000\u0010\u0009" }; yield return new object[] { new byte[] { 0x00, 0x1F, 0x10, 0x09 }, 0, 4, "\u0000\u001F\u0010\u0009" }; // BOM yield return new object[] { new byte[] { 0xEF, 0xBB, 0xBF, 0x41 }, 0, 4, "\uFEFF\u0041" }; // U+FDD0 - U+FDEF yield return new object[] { new byte[] { 0xEF, 0xB7, 0x90, 0xEF, 0xB7, 0xAF }, 0, 6, "\uFDD0\uFDEF" }; // 2 byte encoding yield return new object[] { new byte[] { 0xC3, 0xA1 }, 0, 2, "\u00E1" }; yield return new object[] { new byte[] { 0xC3, 0x85 }, 0, 2, "\u00C5" }; // 3 byte encoding yield return new object[] { new byte[] { 0xE8, 0x80, 0x80 }, 0, 3, "\u8000" }; yield return new object[] { new byte[] { 0xE2, 0x84, 0xAB }, 0, 3, "\u212B" }; // Surrogate pairs yield return new object[] { new byte[] { 240, 144, 128, 128 }, 0, 4, "\uD800\uDC00" }; yield return new object[] { new byte[] { 97, 240, 144, 128, 128, 98 }, 0, 6, "a\uD800\uDC00b" }; yield return new object[] { new byte[] { 0xF0, 0x90, 0x8F, 0xBF }, 0, 4, "\uD800\uDFFF" }; yield return new object[] { new byte[] { 0xF4, 0x8F, 0xB0, 0x80 }, 0, 4, "\uDBFF\uDC00" }; yield return new object[] { new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, 0, 4, "\uDBFF\uDFFF" }; yield return new object[] { new byte[] { 0xF3, 0xB0, 0x80, 0x80 }, 0, 4, "\uDB80\uDC00" }; // Empty strings yield return new object[] { new byte[0], 0, 0, string.Empty }; yield return new object[] { new byte[10], 10, 0, string.Empty }; yield return new object[] { new byte[10], 0, 0, string.Empty }; } [Theory] [MemberData(nameof(Decode_TestData))] public void Decode(byte[] bytes, int index, int count, string expected) { EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected); EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected); EncodingHelpers.Decode(new UTF8Encoding(false, true), bytes, index, count, expected); EncodingHelpers.Decode(new UTF8Encoding(true, true), bytes, index, count, expected); } public static IEnumerable<object[]> Decode_InvalidBytes_TestData() { yield return new object[] { new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, 0, 15, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD" }; yield return new object[] { new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, 0, 12, "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD" }; } [Theory] [MemberData(nameof(Decode_InvalidBytes_TestData))] public static void Decode_InvalidBytes(byte[] bytes, int index, int count, string expected) { EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected); EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected); NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(false, true), bytes, index, count); NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(true, true), bytes, index, count); } [Fact] public void Decode_InvalidBytes() { // TODO: add into Decode_TestData or Decode_InvalidBytes_TestData once #7166 is fixed // High BMP non-chars Decode(new byte[] { 239, 191, 189 }, 0, 3, "\uFFFD"); Decode(new byte[] { 239, 191, 190 }, 0, 3, "\uFFFE"); Decode(new byte[] { 239, 191, 191 }, 0, 3, "\uFFFF"); Decode(new byte[] { 0xEF, 0xBF, 0xAE }, 0, 3, "\uFFEE"); Decode(new byte[] { 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF }, 0, 18, "\uE000\uFFFF\uE000\uFFFF\uE000\uFFFF"); // Invalid surrogate bytes byte[] validSurrogateBytes = new byte[] { 240, 144, 128, 128 }; Decode_InvalidBytes(validSurrogateBytes, 0, 3, "\uFFFD"); Decode_InvalidBytes(validSurrogateBytes, 1, 3, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(validSurrogateBytes, 0, 2, "\uFFFD"); Decode_InvalidBytes(validSurrogateBytes, 1, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(validSurrogateBytes, 2, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(validSurrogateBytes, 2, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xA0, 0x80 }, 0, 3, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xAF, 0xBF }, 0, 3, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xB0, 0x80 }, 0, 3, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xBF, 0xBF }, 0, 3, "\uFFFD\uFFFD"); // Invalid surrogate pair (low/low, high/high, low/high) Decode_InvalidBytes(new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xAF, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xB0, 0x80, 0xED, 0xB0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xA0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD"); // Too high scalar value in surrogates Decode_InvalidBytes(new byte[] { 0xED, 0xA0, 0x80, 0xEE, 0x80, 0x80 }, 0, 6, "\uFFFD\uFFFD\uE000"); Decode_InvalidBytes(new byte[] { 0xF4, 0x90, 0x80, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD"); // These are examples of overlong sequences. This can cause security // vulnerabilities (e.g. MS00-078) so it is important we parse these as invalid. Decode_InvalidBytes(new byte[] { 0xC0 }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xC0, 0xAF }, 0, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE0, 0x80, 0xBF }, 0, 3, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0x80, 0x80, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF8, 0x80, 0x80, 0x80, 0xBF }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xFC, 0x80, 0x80, 0x80, 0x80, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xC0, 0xBF }, 0, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE0, 0x9C, 0x90 }, 0, 3, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0x8F, 0xA4, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xEF, 0x41 }, 0, 2, "\uFFFD\u0041"); Decode_InvalidBytes(new byte[] { 0xEF, 0xBF, 0xAE }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xEF, 0xBF, 0x41 }, 0, 3, "\uFFFD\u0041"); Decode_InvalidBytes(new byte[] { 0xEF, 0xBF, 0x61 }, 0, 3, "\uFFFD\u0061"); Decode_InvalidBytes(new byte[] { 0xEF, 0xBF, 0xEF, 0xBF, 0xAE }, 0, 5, "\uFFFD\uFFEE"); Decode_InvalidBytes(new byte[] { 0xEF, 0xBF, 0xC0, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0xC4, 0x80 }, 0, 3, "\uFFFD\u0100"); Decode_InvalidBytes(new byte[] { 176 }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 196 }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA4, 0xD0, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xA3, 0xA4 }, 0, 12, "\uFFFD\uFFFD\u0061\u0052\u007C\u007B\u0041\u006E\u0047\u0065\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA3 }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA3, 0xA4 }, 0, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x65, 0xA3, 0xA4 }, 0, 3, "\u0065\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x47, 0x65, 0xA3, 0xA4 }, 0, 4, "\u0047\u0065\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA4, 0xD0, 0x61, 0xA3, 0xA4 }, 0, 5, "\uFFFD\uFFFD\u0061\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA4, 0xD0, 0x61, 0xA3 }, 0, 4, "\uFFFD\uFFFD\u0061\uFFFD"); Decode_InvalidBytes(new byte[] { 0xD0, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD"); Decode_InvalidBytes(new byte[] { 0xA4, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD"); Decode_InvalidBytes(new byte[] { 0xD0, 0x61, 0x52, 0xA3 }, 0, 4, "\uFFFD\u0061\u0052\uFFFD"); Decode_InvalidBytes(new byte[] { 0xAA }, 0, 1, "\uFFFD"); Decode_InvalidBytes(new byte[] { 0xAA, 0x41 }, 0, 2, "\uFFFD\u0041"); Decode_InvalidBytes(new byte[] { 0xEF, 0xFF, 0xEE }, 0, 3, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xEF, 0xFF, 0xAE }, 0, 3, "\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 15, "\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }, 0, 15, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F"); Decode_InvalidBytes(new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 8, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xC2, 0xDF }, 0, 2, "\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0x80, 0x80, 0xC1, 0x80, 0xC1, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0x7F, 0x7F, 0x7F, 0x7F, 0xC3, 0xA1, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 14, "\uFFFD\u007F\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u00E1\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0xE0, 0xBF, 0x7F, 0xE0, 0xBF, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE0, 0x9F, 0x80, 0xE0, 0xC0, 0x80, 0xE0, 0x9F, 0xBF, 0xE0, 0xC0, 0xBF }, 0, 12, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0x7F, 0xE0, 0xBF, 0x7F, 0xC3, 0xA1, 0xE0, 0xBF, 0xC0 }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\u007F\uFFFD\u007F\u00E1\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE1, 0x80, 0x7F, 0xE1, 0x80, 0xC0, 0xE1, 0xBF, 0x7F, 0xE1, 0xBF, 0xC0, 0xEC, 0x80, 0x7F, 0xEC, 0x80, 0xC0, 0xEC, 0xBF, 0x7F, 0xEC, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xE1, 0x7F, 0x80, 0xE1, 0xC0, 0x80, 0xE1, 0x7F, 0xBF, 0xE1, 0xC0, 0xBF, 0xEC, 0x7F, 0x80, 0xEC, 0xC0, 0x80, 0xEC, 0x7F, 0xBF, 0xEC, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0x80, 0x7F, 0xED, 0x80, 0xC0, 0xED, 0x9F, 0x7F, 0xED, 0x9F, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xE8, 0x80, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u8000\uFFFD\u007F\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xEE, 0x80, 0x7F, 0xEE, 0x80, 0xC0, 0xEE, 0xBF, 0x7F, 0xEE, 0xBF, 0xC0, 0xEF, 0x80, 0x7F, 0xEF, 0x80, 0xC0, 0xEF, 0xBF, 0x7F, 0xEF, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xEE, 0x7F, 0x80, 0xEE, 0xC0, 0x80, 0xEE, 0x7F, 0xBF, 0xEE, 0xC0, 0xBF, 0xEF, 0x7F, 0x80, 0xEF, 0xC0, 0x80, 0xEF, 0x7F, 0xBF, 0xEF, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0x90, 0x80, 0x7F, 0xF0, 0x90, 0x80, 0xC0, 0xF0, 0xBF, 0xBF, 0x7F, 0xF0, 0xBF, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0x90, 0x7F, 0x80, 0xF0, 0x90, 0xC0, 0x80, 0xF0, 0x90, 0x7F, 0xBF, 0xF0, 0x90, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF0, 0x8F, 0x80, 0x80, 0xF0, 0xC0, 0x80, 0x80, 0xF0, 0x8F, 0xBF, 0xBF, 0xF0, 0xC0, 0xBF, 0xBF }, 0, 16, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF1, 0x80, 0x80, 0x7F, 0xF1, 0x80, 0x80, 0xC0, 0xF1, 0xBF, 0xBF, 0x7F, 0xF1, 0xBF, 0xBF, 0xC0, 0xF3, 0x80, 0x80, 0x7F, 0xF3, 0x80, 0x80, 0xC0, 0xF3, 0xBF, 0xBF, 0x7F, 0xF3, 0xBF, 0xBF, 0xC0 }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF1, 0x80, 0x7F, 0x80, 0xF1, 0x80, 0xC0, 0x80, 0xF1, 0x80, 0x7F, 0xBF, 0xF1, 0x80, 0xC0, 0xBF, 0xF3, 0x80, 0x7F, 0x80, 0xF3, 0x80, 0xC0, 0x80, 0xF3, 0x80, 0x7F, 0xBF, 0xF3, 0x80, 0xC0, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF1, 0x7F, 0x80, 0x80, 0xF1, 0xC0, 0x80, 0x80, 0xF1, 0x7F, 0xBF, 0xBF, 0xF1, 0xC0, 0xBF, 0xBF, 0xF3, 0x7F, 0x80, 0x80, 0xF3, 0xC0, 0x80, 0x80, 0xF3, 0x7F, 0xBF, 0xBF, 0xF3, 0xC0, 0xBF, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF4, 0x80, 0x80, 0x7F, 0xF4, 0x80, 0x80, 0xC0, 0xF4, 0x8F, 0xBF, 0x7F, 0xF4, 0x8F, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF4, 0x80, 0x7F, 0x80, 0xF4, 0x80, 0xC0, 0x80, 0xF4, 0x80, 0x7F, 0xBF, 0xF4, 0x80, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD"); Decode_InvalidBytes(new byte[] { 0xF4, 0x7F, 0x80, 0x80, 0xF4, 0x90, 0x80, 0x80, 0xF4, 0x7F, 0xBF, 0xBF, 0xF4, 0x90, 0xBF, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"); } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Tracing; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// /// </summary> internal enum DataPriorityType : int { /// <summary> /// This indicate that the data will be sent without priority consideration. /// Large data objects will be fragmented so that each fragmented piece can /// fit into one message. /// </summary> Default = 0, /// <summary> /// PromptResponse may be sent with or without priority considerations. /// Large data objects will be fragmented so that each fragmented piece can /// fit into one message. /// </summary> PromptResponse = 1, } #region Sending Data /// <summary> /// DataStructure used by different remoting protocol / /// DataStructures to pass data to transport manager. /// This class holds the responsibility of fragmenting. /// This allows to fragment an object only once and /// send the fragments to various machines thus saving /// fragmentation time. /// </summary> internal class PrioritySendDataCollection { #region Private Data // actual data store(s) to store priority based data and its // corresponding sync objects to provide thread safety. private SerializedDataStream[] _dataToBeSent; // fragmentor used to serialize & fragment objects added to this collection. private Fragmentor _fragmentor; private object[] _syncObjects; // callbacks used if no data is available at any time. // these callbacks are used to notify when data becomes available under // suc circumstances. private OnDataAvailableCallback _onDataAvailableCallback; private SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable; private bool _isHandlingCallback; private object _readSyncObject = new object(); /// <summary> /// Callback that is called once a fragmented data is available to send. /// </summary> /// <param name="data"> /// Fragmented object that can be sent to the remote end. /// </param> /// <param name="priorityType"> /// Priority stream to which <paramref name="data"/> belongs to. /// </param> internal delegate void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType); #endregion #region Constructor /// <summary> /// Constructs a PrioritySendDataCollection object. /// </summary> internal PrioritySendDataCollection() { _onSendCollectionDataAvailable = new SerializedDataStream.OnDataAvailableCallback(OnDataAvailable); } #endregion #region Internal Methods / Properties internal Fragmentor Fragmentor { get { return _fragmentor; } set { Dbg.Assert(null != value, "Fragmentor cannot be null."); _fragmentor = value; // create serialized streams using fragment size. string[] names = Enum.GetNames(typeof(DataPriorityType)); _dataToBeSent = new SerializedDataStream[names.Length]; _syncObjects = new object[names.Length]; for (int i = 0; i < names.Length; i++) { _dataToBeSent[i] = new SerializedDataStream(_fragmentor.FragmentSize); _syncObjects[i] = new object(); } } } /// <summary> /// Adds data to this collection. The data is fragmented in this method /// before being stored into the collection. So the calling thread /// will get affected, if it tries to add a huge object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"> /// data to be added to the collection. Caller should make sure this is not /// null. /// </param> /// <param name="priority"> /// Priority of the data. /// </param> internal void Add<T>(RemoteDataObject<T> data, DataPriorityType priority) { Dbg.Assert(null != data, "Cannot send null data object"); Dbg.Assert(null != _fragmentor, "Fragmentor cannot be null while adding objects"); Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized"); // make sure the only one object is fragmented and added to the collection // at any give time. This way the order of fragment is maintained // in the SendDataCollection(s). lock (_syncObjects[(int)priority]) { _fragmentor.Fragment<T>(data, _dataToBeSent[(int)priority]); } } /// <summary> /// Adds data to this collection. The data is fragmented in this method /// before being stored into the collection. So the calling thread /// will get affected, if it tries to add a huge object. /// /// The data is added with Default priority. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"> /// data to be added to the collection. Caller should make sure this is not /// null. /// </param> internal void Add<T>(RemoteDataObject<T> data) { Add<T>(data, DataPriorityType.Default); } /// <summary> /// Clears fragmented objects stored so far in this collection. /// </summary> internal void Clear() { Dbg.Assert(null != _dataToBeSent, "Serialized streams are not initialized"); lock (_syncObjects[(int)DataPriorityType.PromptResponse]) { _dataToBeSent[(int)DataPriorityType.PromptResponse].Dispose(); } lock (_syncObjects[(int)DataPriorityType.Default]) { _dataToBeSent[(int)DataPriorityType.Default].Dispose(); } } /// <summary> /// Gets the fragment or if no fragment is available registers the callback which /// gets called once a fragment is available. These 2 steps are performed in a /// synchronized way. /// /// While getting a fragment the following algorithm is used: /// 1. If this is the first time or if the last fragment read is an EndFragment, /// then a new set of fragments is chosen based on the implicit priority. /// PromptResponse is higher in priority order than default. /// 2. If last fragment read is not an EndFragment, then next fragment is chosen from /// the priority collection as the last fragment. This will ensure fragments /// are sent in order. /// </summary> /// <param name="callback"> /// Callback to call once data is available. (This will be used if no data is currently /// available). /// </param> /// <param name="priorityType"> /// Priority stream to which the returned object belongs to, if any. /// If the call does not return any data, the value of this "out" parameter /// is undefined. /// </param> /// <returns> /// A FragmentRemoteObject if available, otherwise null. /// </returns> internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback, out DataPriorityType priorityType) { lock (_readSyncObject) { priorityType = DataPriorityType.Default; // send data from which ever stream that has data directly. byte[] result = null; result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.PromptResponse; if (null == result) { result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.Default; } // no data to return..so register the callback. if (null == result) { // register callback. _onDataAvailableCallback = callback; } return result; } } private void OnDataAvailable(byte[] data, bool isEndFragment) { lock (_readSyncObject) { // PromptResponse and Default priority collection can both raise at the // same time. This will take care of the situation. if (_isHandlingCallback) { return; } _isHandlingCallback = true; } if (null != _onDataAvailableCallback) { DataPriorityType prType; // now get the fragment and call the callback.. byte[] result = ReadOrRegisterCallback(_onDataAvailableCallback, out prType); if (null != result) { // reset the onDataAvailableCallback so that we dont notify // multiple times. we are resetting before actually calling // the callback to make sure the caller calls ReadOrRegisterCallback // at a later point and we dont loose the callback handle. OnDataAvailableCallback realCallback = _onDataAvailableCallback; _onDataAvailableCallback = null; realCallback(result, prType); } } _isHandlingCallback = false; } #endregion } #endregion #region Receiving Data /// <summary> /// DataStructure used by remoting transport layer to store /// data being received from the wire for a particular priority /// stream. /// </summary> internal class ReceiveDataCollection : IDisposable { #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] private static PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion #region Private Data // fragmentor used to defragment objects added to this collection. private Fragmentor _defragmentor; // this stream holds incoming data..this stream doesn't know anything // about fragment boundaries. private MemoryStream _pendingDataStream; // the idea is to maintain 1 whole object. // 1 whole object may contain any number of fragments. blob from // each fragment is written to this stream. private MemoryStream _dataToProcessStream; private long _currentObjectId; private long _currentFrgId; // max deserialized object size in bytes private Nullable<int> _maxReceivedObjectSize; private int _totalReceivedObjectSizeSoFar; private bool _isCreateByClientTM; // this indicates if any off sync fragments can be ignored // this gets reset (to false) upon receiving the next "start" fragment along the stream private bool _canIgnoreOffSyncFragments = false; // objects need to cleanly release resources without // locking entire processing logic. private object _syncObject; private bool _isDisposed; // holds the number of threads that are currently in // ProcessRawData method. This might happen only for // ServerCommandTransportManager case where the command // is run in the same thread that runs ProcessRawData (to avoid // thread context switch). private int _numberOfThreadsProcessing; // limits the numberOfThreadsProcessing variable. private int _maxNumberOfThreadsToAllowForProcessing = 1; #endregion #region Delegates /// <summary> /// Callback that is called once a deserialized object is available. /// </summary> /// <param name="data"> /// Deserialized object that can be processed. /// </param> internal delegate void OnDataAvailableCallback(RemoteDataObject<PSObject> data); #endregion #region Constructor /// <summary> /// /// </summary> /// <param name="defragmentor"> /// Defragmentor used to deserialize an object. /// </param> /// <param name="createdByClientTM"> /// True if a client transport manager created this collection. /// This is used to generate custom messages for server and client. /// </param> internal ReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { Dbg.Assert(null != defragmentor, "ReceiveDataCollection needs a defragmentor to work with"); // Memory streams created with an unsigned byte array provide a non-resizable stream view // of the data, and can only be written to. When using a byte array, you can neither append // to nor shrink the stream, although you might be able to modify the existing contents // depending on the parameters passed into the constructor. Empty memory streams are // resizable, and can be written to and read from. _pendingDataStream = new MemoryStream(); _syncObject = new object(); _defragmentor = defragmentor; _isCreateByClientTM = createdByClientTM; } #endregion #region Internal Methods / Properties /// <summary> /// Limits the deserialized object size received from a remote machine. /// </summary> internal Nullable<int> MaximumReceivedObjectSize { set { _maxReceivedObjectSize = value; } } /// <summary> /// This might be needed only for ServerCommandTransportManager case /// where the command is run in the same thread that runs ProcessRawData /// (to avoid thread context switch). By default this class supports /// only one thread in ProcessRawData. /// </summary> internal void AllowTwoThreadsToProcessRawData() { _maxNumberOfThreadsToAllowForProcessing = 2; } /// <summary> /// Prepares the collection for a stream connect /// When reconnecting from same client, its possible that fragment stream get interrupted if server is dropping data /// When connecting from a new client, its possible to get trailing fragments of a previously partially transmitted object /// Logic based on this flag, ensures such offsync/trailing fragments get ignored until the next full object starts flowing /// </summary> internal void PrepareForStreamConnect() { _canIgnoreOffSyncFragments = true; } /// <summary> /// Process data coming from the transport. This method analyses the data /// and if an object can be created, it creates one and calls the /// <paramref name="callback"/> with the deserialized object. This method /// does not assume all fragments to be available. So if not enough fragments are /// available it will simply return.. /// </summary> /// <param name="data"> /// Data to process. /// </param> /// <param name="callback"> /// Callback to call once a complete deserialized object is available. /// </param> /// <returns> /// Defragmented Object if any, otherwise null. /// </returns> /// <exception cref="PSRemotingTransportException"> /// 1. Fragment Ids not in sequence /// 2. Object Ids does not match /// 3. The current deserialized object size of the received data exceeded /// allowed maximum object size. The current deserialized object size is {0}. /// Allowed maximum object size is {1}. /// </exception> /// <remarks> /// Might throw other exceptions as the deserialized object is handled here. /// </remarks> internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) { Dbg.Assert(null != data, "Cannot process null data"); Dbg.Assert(null != callback, "Callback cannot be null"); lock (_syncObject) { if (_isDisposed) { return; } _numberOfThreadsProcessing++; if (_numberOfThreadsProcessing > _maxNumberOfThreadsToAllowForProcessing) { Dbg.Assert(false, "Multiple threads are not allowed in ProcessRawData."); } } try { _pendingDataStream.Write(data, 0, data.Length); // this do loop will process one deserialized object. // using a loop allows to process multiple objects within // the same packet do { if (_pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength) { // there is not enough data to be processed. s_baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.", _pendingDataStream.Length, FragmentedRemoteObject.HeaderLength); return; } byte[] dataRead = _pendingDataStream.ToArray(); // there is enough data to process here. get the fragment header long objectId = FragmentedRemoteObject.GetObjectId(dataRead, 0); if (objectId <= 0) { throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero); } long fragmentId = FragmentedRemoteObject.GetFragmentId(dataRead, 0); bool sFlag = FragmentedRemoteObject.GetIsStartFragment(dataRead, 0); bool eFlag = FragmentedRemoteObject.GetIsEndFragment(dataRead, 0); int blobLength = FragmentedRemoteObject.GetBlobLength(dataRead, 0); if ((s_baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { s_baseTracer.WriteLine("Object Id: {0}", objectId); s_baseTracer.WriteLine("Fragment Id: {0}", fragmentId); s_baseTracer.WriteLine("Start Flag: {0}", sFlag); s_baseTracer.WriteLine("End Flag: {0}", eFlag); s_baseTracer.WriteLine("Blob Length: {0}", blobLength); } int totalLengthOfFragment = 0; try { totalLengthOfFragment = checked(FragmentedRemoteObject.HeaderLength + blobLength); } catch (System.OverflowException) { s_baseTracer.WriteLine("Fragement too big."); ResetReceiveData(); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig); throw e; } if (_pendingDataStream.Length < totalLengthOfFragment) { s_baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.", _pendingDataStream.Length, totalLengthOfFragment); return; } // ensure object size limit is not reached if (_maxReceivedObjectSize.HasValue) { _totalReceivedObjectSizeSoFar = unchecked(_totalReceivedObjectSizeSoFar + totalLengthOfFragment); if ((_totalReceivedObjectSizeSoFar < 0) || (_totalReceivedObjectSizeSoFar > _maxReceivedObjectSize.Value)) { s_baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}", _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); PSRemotingTransportException e = null; if (_isCreateByClientTM) { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient, _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); } else { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer, _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize); } ResetReceiveData(); throw e; } } // appears like stream doesn't have individual position marker for read and write // since we are going to read from now... _pendingDataStream.Seek(0, SeekOrigin.Begin); // we have enough data to process..so read the data from the stream and process. byte[] oneFragment = new byte[totalLengthOfFragment]; // this will change position back to totalLengthOfFragment int dataCount = _pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment); Dbg.Assert(dataCount == totalLengthOfFragment, "Unable to read enough data from the stream. Read failed"); PSEtwLog.LogAnalyticVerbose( PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, (Int64)objectId, (Int64)fragmentId, sFlag ? 1 : 0, eFlag ? 1 : 0, (UInt32)blobLength, new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength)); byte[] extraData = null; if (totalLengthOfFragment < _pendingDataStream.Length) { // there is more data in the stream than fragment size..so save that data extraData = new byte[_pendingDataStream.Length - totalLengthOfFragment]; _pendingDataStream.Read(extraData, 0, (int)(_pendingDataStream.Length - totalLengthOfFragment)); } // reset incoming stream. _pendingDataStream.Dispose(); _pendingDataStream = new MemoryStream(); if (null != extraData) { _pendingDataStream.Write(extraData, 0, extraData.Length); } if (sFlag) { _canIgnoreOffSyncFragments = false; //reset this upon receiving a start fragment of a fresh object _currentObjectId = objectId; // Memory streams created with an unsigned byte array provide a non-resizable stream view // of the data, and can only be written to. When using a byte array, you can neither append // to nor shrink the stream, although you might be able to modify the existing contents // depending on the parameters passed into the constructor. Empty memory streams are // resizable, and can be written to and read from. _dataToProcessStream = new MemoryStream(); } else { // check if the data belongs to the same object as the start fragment if (objectId != _currentObjectId) { s_baseTracer.WriteLine("ObjectId != CurrentObjectId"); //TODO - drop an ETW event ResetReceiveData(); if (!_canIgnoreOffSyncFragments) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching); throw e; } else { s_baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId"); continue; } } if (fragmentId != (_currentFrgId + 1)) { s_baseTracer.WriteLine("Fragment Id is not in sequence."); //TODO - drop an ETW event ResetReceiveData(); if (!_canIgnoreOffSyncFragments) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.FragmetIdsNotInSequence); throw e; } else { s_baseTracer.WriteLine("Ignoring Fragment Id is not in sequence."); continue; } } } // make fragment id from this packet as the current fragment id _currentFrgId = fragmentId; // store the blob in a separate stream _dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength); if (eFlag) { try { // appears like stream doesn't individual position marker for read and write // since we are going to read from now..i am resetting position to 0. _dataToProcessStream.Seek(0, SeekOrigin.Begin); RemoteDataObject<PSObject> remoteObject = RemoteDataObject<PSObject>.CreateFrom(_dataToProcessStream, _defragmentor); s_baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId); s_baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId); // notify the caller that a deserialized object is available. callback(remoteObject); } finally { // Reset the receive data buffers and start the process again. ResetReceiveData(); } if (_isDisposed) { break; } } } while (true); } finally { lock (_syncObject) { if (_isDisposed && (_numberOfThreadsProcessing == 1)) { ReleaseResources(); } _numberOfThreadsProcessing--; } } } /// <summary> /// Resets the store(s) holding received data. /// </summary> private void ResetReceiveData() { // reset resources used to store incoming data (for a single object) if (null != _dataToProcessStream) { _dataToProcessStream.Dispose(); } _currentObjectId = 0; _currentFrgId = 0; _totalReceivedObjectSizeSoFar = 0; } private void ReleaseResources() { if (null != _pendingDataStream) { _pendingDataStream.Dispose(); _pendingDataStream = null; } if (null != _dataToProcessStream) { _dataToProcessStream.Dispose(); _dataToProcessStream = null; } } #endregion #region IDisposable implementation /// <summary> /// Dispose and release resources. /// </summary> public void Dispose() { Dispose(true); // if already disposing..no need to let finalizer thread // put resources to clean this object. System.GC.SuppressFinalize(this); } internal virtual void Dispose(bool isDisposing) { lock (_syncObject) { _isDisposed = true; if (_numberOfThreadsProcessing == 0) { ReleaseResources(); } } } #endregion } /// <summary> /// DataStructure used by different remoting protocol / /// DataStructures to receive data from transport manager. /// This class holds the responsibility of defragmenting and /// deserializing. /// </summary> internal class PriorityReceiveDataCollection : IDisposable { #region Private Data private Fragmentor _defragmentor; private ReceiveDataCollection[] _recvdData; private bool _isCreateByClientTM; #endregion #region Constructor /// <summary> /// Construct a priority receive data collection /// </summary> /// <param name="defragmentor">Defragmentor used to deserialize an object.</param> /// <param name="createdByClientTM"> /// True if a client transport manager created this collection. /// This is used to generate custom messages for server and client. /// </param> internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { _defragmentor = defragmentor; string[] names = Enum.GetNames(typeof(DataPriorityType)); _recvdData = new ReceiveDataCollection[names.Length]; for (int index = 0; index < names.Length; index++) { _recvdData[index] = new ReceiveDataCollection(defragmentor, createdByClientTM); } _isCreateByClientTM = createdByClientTM; } #endregion #region Internal Methods / Properties /// <summary> /// Limits the total data received from a remote machine. /// </summary> internal Nullable<int> MaximumReceivedDataSize { set { _defragmentor.DeserializationContext.MaximumAllowedMemory = value; } } /// <summary> /// Limits the deserialized object size received from a remote machine. /// </summary> internal Nullable<int> MaximumReceivedObjectSize { set { foreach (ReceiveDataCollection recvdDataBuffer in _recvdData) { recvdDataBuffer.MaximumReceivedObjectSize = value; } } } /// <summary> /// Prepares receive data streams for a reconnection /// </summary> internal void PrepareForStreamConnect() { for (int index = 0; index < _recvdData.Length; index++) { _recvdData[index].PrepareForStreamConnect(); } } /// <summary> /// This might be needed only for ServerCommandTransportManager case /// where the command is run in the same thread that runs ProcessRawData /// (to avoid thread context switch). By default this class supports /// only one thread in ProcessRawData. /// </summary> internal void AllowTwoThreadsToProcessRawData() { for (int index = 0; index < _recvdData.Length; index++) { _recvdData[index].AllowTwoThreadsToProcessRawData(); } } /// <summary> /// Process data coming from the transport. This method analyses the data /// and if an object can be created, it creates one and calls the /// <paramref name="callback"/> with the deserialized object. This method /// does not assume all fragments to be available. So if not enough fragments are /// available it will simply return.. /// </summary> /// <param name="data"> /// Data to process. /// </param> /// <param name="priorityType"> /// Priority stream this data belongs to. /// </param> /// <param name="callback"> /// Callback to call once a complete deserialized object is available. /// </param> /// <returns> /// Defragmented Object if any, otherwise null. /// </returns> /// <exception cref="PSRemotingTransportException"> /// 1. Fragment Ids not in sequence /// 2. Object Ids does not match /// 3. The current deserialized object size of the received data exceeded /// allowed maximum object size. The current deserialized object size is {0}. /// Allowed maximum object size is {1}. /// 4.The total data received from the remote machine exceeded allowed maximum. /// The total data received from remote machine is {0}. Allowed maximum is {1}. /// </exception> /// <remarks> /// Might throw other exceptions as the deserialized object is handled here. /// </remarks> internal void ProcessRawData(byte[] data, DataPriorityType priorityType, ReceiveDataCollection.OnDataAvailableCallback callback) { Dbg.Assert(null != data, "Cannot process null data"); try { _defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length); } catch (System.Xml.XmlException) { PSRemotingTransportException e = null; if (_isCreateByClientTM) { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient, _defragmentor.DeserializationContext.MaximumAllowedMemory.Value); } else { e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer, _defragmentor.DeserializationContext.MaximumAllowedMemory.Value); } throw e; } _recvdData[(int)priorityType].ProcessRawData(data, callback); } #endregion #region IDisposable implementation /// <summary> /// Dispose and release resources. /// </summary> public void Dispose() { Dispose(true); // if already disposing..no need to let finalizer thread // put resources to clean this object. System.GC.SuppressFinalize(this); } internal virtual void Dispose(bool isDisposing) { if (null != _recvdData) { for (int index = 0; index < _recvdData.Length; index++) { _recvdData[index].Dispose(); } } } #endregion } #endregion }
using System; using System.Linq.Expressions; using System.Reflection; using StructureMap.Building; using StructureMap.Building.Interception; namespace StructureMap.Pipeline { public class SmartInstance<T> : SmartInstance<T, T> { public SmartInstance(Expression<Func<T>> constructorSelection = null) : base(constructorSelection) { } } /// <summary> /// Instance that builds objects with by calling constructor functions and using setter properties /// </summary> /// <typeparam name="T">The concrete type constructed by SmartInstance</typeparam> /// <typeparam name="TPluginType">The "PluginType" that this instance satisfies</typeparam> public class SmartInstance<T, TPluginType> : ExpressedInstance<SmartInstance<T, TPluginType>, T, TPluginType>, IConfiguredInstance where T : TPluginType { private readonly ConstructorInstance _inner = new ConstructorInstance(typeof (T)); public SmartInstance(Expression<Func<T>> constructorSelection = null) { if (constructorSelection != null) { SelectConstructor(constructorSelection); } } public SmartInstance<T, TPluginType> SelectConstructor(Expression<Func<T>> constructor) { var finder = new ConstructorFinderVisitor(); finder.Visit(constructor); _inner.Constructor = finder.Constructor; return this; } protected override SmartInstance<T, TPluginType> thisInstance { get { return this; } } public override string Name { get { return _inner.Name; } set { _inner.Name = value; } } /// <summary> /// Set simple setter properties /// </summary> /// <param name="action"></param> /// <returns></returns> public SmartInstance<T, TPluginType> SetProperty(Action<T> action) { AddInterceptor(InterceptorFactory.ForAction("Setting property", action)); return this; } /// <summary> /// Inline definition of a setter dependency. The property name is specified with an Expression /// </summary> /// <typeparam name="TSettertype"></typeparam> /// <param name="expression"></param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSettertype> Setter<TSettertype>( Expression<Func<T, TSettertype>> expression) { var propertyName = ReflectionHelper.GetProperty(expression).Name; return new DependencyExpression<SmartInstance<T, TPluginType>, TSettertype>(this, propertyName); } public override IDependencySource ToDependencySource(Type pluginType) { return _inner.ToDependencySource(pluginType); } public override IDependencySource ToBuilder(Type pluginType, Policies policies) { return _inner.ToBuilder(pluginType, policies); } public override string Description { get { return _inner.Description; } } public override Type ReturnedType { get { return typeof(T); } } Type IConfiguredInstance.PluggedType { get { return typeof (T); } } DependencyCollection IConfiguredInstance.Dependencies { get { return _inner.Dependencies; } } ConstructorInstance IConfiguredInstance.Override(ExplicitArguments arguments) { return _inner.Override(arguments); } ConstructorInfo IConfiguredInstance.Constructor { get { return _inner.Constructor; } set { _inner.Constructor = value; } } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type. Do not /// use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="TCtorType"></typeparam> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TCtorType> Ctor<TCtorType>() { return Ctor<TCtorType>(null); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. /// Use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="TCtorType"></typeparam> /// <param name="constructorArg"></param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TCtorType> Ctor<TCtorType>(string constructorArg) { return new DependencyExpression<SmartInstance<T, TPluginType>, TCtorType>(this, constructorArg); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the TSetterType /// </summary> /// <typeparam name="TSetterType"></typeparam> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSetterType> Setter<TSetterType>() { return Ctor<TSetterType>(); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the TSetterType /// </summary> /// <typeparam name="TSetterType"></typeparam> /// <param name="setterName">The name of the property</param> /// <returns></returns> public DependencyExpression<SmartInstance<T, TPluginType>, TSetterType> Setter<TSetterType>(string setterName) { return Ctor<TSetterType>(setterName); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="TElement"></typeparam> /// <returns></returns> public ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement> EnumerableOf<TElement>() { if (typeof(TElement).IsArray) { throw new ArgumentException("Please specify the element type in the call to TheArrayOf"); } return new ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement>(this, null); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="TElement"></typeparam> /// <param name="ctorOrPropertyName"></param> /// <returns></returns> public ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement> EnumerableOf<TElement>(string ctorOrPropertyName) { return new ArrayDefinitionExpression<SmartInstance<T, TPluginType>, TElement>(this, ctorOrPropertyName); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace NamaBeer.WebAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace CallbackReceiver.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> m_annotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { var range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { var maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { var minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { var strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { var dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { var regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> m_defaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private readonly Lazy<IModelDocumentationProvider> m_documentationProvider; /// <summary /> /// <param name="config"></param> public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } m_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } /// <summary /> public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return m_documentationProvider.Value; } } /// <summary /> public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (m_defaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { var jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { var dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { var jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); var xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); var ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); var nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); var apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (m_defaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { var annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (m_annotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { var complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { var propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { var enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { var simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Text; using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace ReactNative.Views.TextInput { /// <summary> /// View manager for <see cref="ReactTextBox"/>. /// </summary> class ReactTextInputManager : BaseViewManager<ReactTextBox, ReactTextInputShadowNode> { internal const int FocusTextInput = 1; internal const int BlurTextInput = 2; internal static readonly Color DefaultTextBoxBorder = Color.FromArgb(255, 122, 122, 122); internal static readonly Color DefaultPlaceholderTextColor = Color.FromArgb(255, 0, 0, 0); /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "RCTTextBox"; } } /// <summary> /// The exported custom bubbling event types. /// </summary> public override IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get { return new Dictionary<string, object>() { { "topSubmitEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onSubmitEditing" }, { "captured" , "onSubmitEditingCapture" } } } } }, { "topEndEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onEndEditing" }, { "captured" , "onEndEditingCapture" } } } } }, { "topFocus", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onFocus" }, { "captured" , "onFocusCapture" } } } } }, { "topBlur", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onBlur" }, { "captured" , "onBlurCapture" } } } } }, }; } } /// <summary> /// The commands map for the <see cref="ReactTextInputManager"/>. /// </summary> public override IReadOnlyDictionary<string, object> CommandsMap { get { return new Dictionary<string, object>() { { "focusTextInput", FocusTextInput }, { "blurTextInput", BlurTextInput }, }; } } /// <summary> /// Sets the font size on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(ReactTextBox view, double fontSize) { view.FontSize = fontSize; } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(ReactTextBox view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="familyName">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(ReactTextBox view, string familyName) { view.FontFamily = familyName != null ? new FontFamily(familyName) : new FontFamily(); } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontWeightString">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(ReactTextBox view, string fontWeightString) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString); view.FontWeight = fontWeight ?? FontWeights.Normal; } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontStyleString">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(ReactTextBox view, string fontStyleString) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString); view.FontStyle = fontStyle ?? new FontStyle(); } /// <summary> /// Sets whether to track selection changes on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="onSelectionChange">The indicator.</param> [ReactProp("onSelectionChange", DefaultBoolean = false)] public void SetOnSelectionChange(ReactTextBox view, bool onSelectionChange) { view.OnSelectionChange = onSelectionChange; } /// <summary> /// Sets the default text placeholder property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="placeholder">The placeholder text.</param> [ReactProp("placeholder")] public void SetPlaceholder(ReactTextBox view, string placeholder) { PlaceholderAdorner.SetText(view, placeholder); } /// <summary> /// Sets the placeholderTextColor property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The placeholder text color.</param> [ReactProp("placeholderTextColor", CustomType = "Color")] public void SetPlaceholderTextColor(ReactTextBox view, uint? color) { var brush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultPlaceholderTextColor); PlaceholderAdorner.SetTextColor(view, brush); } /// <summary> /// Sets the border color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance</param> /// <param name="color">The masked color value.</param> [ReactProp("borderColor", CustomType = "Color")] public void SetBorderColor(ReactTextBox view, uint? color) { view.BorderBrush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultTextBoxBorder); } /// <summary> /// Sets the background color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(ReactTextBox view, uint? color) { view.Background = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(Colors.White); } /// <summary> /// Sets the selection color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp("selectionColor", CustomType = "Color")] public void SetSelectionColor(ReactTextBox view, uint color) { view.SelectionBrush = new SolidColorBrush(ColorHelpers.Parse(color)); view.CaretBrush = new SolidColorBrush(ColorHelpers.Parse(color)); } /// <summary> /// Sets the text alignment property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlign)] public void SetTextAlign(ReactTextBox view, string alignment) { view.TextAlignment = EnumHelpers.Parse<TextAlignment>(alignment); } /// <summary> /// Sets the text alignment property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlignVertical)] public void SetTextVerticalAlign(ReactTextBox view, string alignment) { view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment); } /// <summary> /// Sets the editablity property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="editable">The editable flag.</param> [ReactProp("editable")] public void SetEditable(ReactTextBox view, bool editable) { view.IsEnabled = editable; } /// <summary> /// Sets the max character length property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="maxCharLength">The max length.</param> [ReactProp("maxLength")] public void SetMaxLength(ReactTextBox view, int maxCharLength) { view.MaxLength = maxCharLength; } /// <summary> /// Sets whether to enable autocorrect on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="autoCorrect">The autocorrect flag.</param> [ReactProp("autoCorrect")] public void SetAutoCorrect(ReactTextBox view, bool autoCorrect) { var checker = view.SpellCheck; checker.IsEnabled = autoCorrect; } /// <summary> /// Sets whether to enable multiline input on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="multiline">The multiline flag.</param> [ReactProp("multiline", DefaultBoolean = false)] public void SetMultiline(ReactTextBox view, bool multiline) { view.AcceptsReturn = multiline; view.TextWrapping = multiline ? TextWrapping.Wrap : TextWrapping.NoWrap; } /// <summary> /// Sets the keyboard type on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="keyboardType">The keyboard type.</param> [ReactProp("keyboardType")] public void SetKeyboardType(ReactTextBox view, string keyboardType) { view.InputScope = null; if (keyboardType != null) { var inputScope = new InputScope(); inputScope.Names.Add( new InputScopeName( InputScopeHelpers.FromString(keyboardType))); view.InputScope = inputScope; } } /// <summary> /// Sets the border width for a <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="width">The border width.</param> [ReactProp(ViewProps.BorderWidth)] public void SetBorderWidth(ReactTextBox view, int width) { view.BorderThickness = new Thickness(width); } /// <summary> /// Sets whether the text should be cleared on focus. /// </summary> /// <param name="view">The view instance.</param> /// <param name="clearTextOnFocus">The indicator.</param> [ReactProp("clearTextOnFocus")] public void SetClearTextOnFocus(ReactTextBox view, bool clearTextOnFocus) { view.ClearTextOnFocus = clearTextOnFocus; } /// <summary> /// Sets whether the text should be selected on focus. /// </summary> /// <param name="view">The view instance.</param> /// <param name="selectTextOnFocus">The indicator.</param> [ReactProp("selectTextOnFocus")] public void SetSelectTextOnFocus(ReactTextBox view, bool selectTextOnFocus) { view.SelectTextOnFocus = selectTextOnFocus; } /// <summary> /// Create the shadow node instance. /// </summary> /// <returns>The shadow node instance.</returns> public override ReactTextInputShadowNode CreateShadowNodeInstance() { return new ReactTextInputShadowNode(); } /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public override void ReceiveCommand(ReactTextBox view, int commandId, JArray args) { if (commandId == FocusTextInput) { view.Focus(); } else if (commandId == BlurTextInput) { Keyboard.ClearFocus(); } } /// <summary> /// Update the view with extra data. /// </summary> /// <param name="view">The view instance.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(ReactTextBox view, object extraData) { var paddings = extraData as float[]; var textUpdate = default(Tuple<int, string>); if (paddings != null) { view.Padding = new Thickness( paddings[0], paddings[1], paddings[2], paddings[3]); } else if ((textUpdate = extraData as Tuple<int, string>) != null) { var javaScriptCount = textUpdate.Item1; if (javaScriptCount < view.CurrentEventCount) { return; } view.TextChanged -= OnTextChanged; var removeOnSelectionChange = view.OnSelectionChange; if (removeOnSelectionChange) { view.OnSelectionChange = false; } var text = textUpdate.Item2; var selectionStart = view.SelectionStart; var selectionLength = view.SelectionLength; var textLength = text?.Length ?? 0; var maxLength = textLength - selectionLength; view.Text = text ?? ""; view.SelectionStart = Math.Min(selectionStart, textLength); view.SelectionLength = Math.Min(selectionLength, maxLength < 0 ? 0 : maxLength); if (removeOnSelectionChange) { view.OnSelectionChange = true; } view.TextChanged += OnTextChanged; } } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactTextInputManager"/>. /// subclass. Unregister all event handlers for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="ReactTextBox"/>.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, ReactTextBox view) { base.OnDropViewInstance(reactContext, view); view.KeyDown -= OnKeyDown; view.LostFocus -= OnLostFocus; view.GotFocus -= OnGotFocus; view.TextChanged -= OnTextChanged; } public override void SetDimensions(ReactTextBox view, Dimensions dimensions) { base.SetDimensions(view, dimensions); view.MinWidth = dimensions.Width; view.MinHeight = dimensions.Height; } /// <summary> /// Returns the view instance for <see cref="ReactTextBox"/>. /// </summary> /// <param name="reactContext"></param> /// <returns></returns> protected override ReactTextBox CreateViewInstance(ThemedReactContext reactContext) { return new ReactTextBox { AcceptsReturn = false, }; } /// <summary> /// Installing the textchanged event emitter on the <see cref="TextInput"/> Control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="ReactTextBox"/> view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, ReactTextBox view) { base.AddEventEmitters(reactContext, view); view.TextChanged += OnTextChanged; view.GotFocus += OnGotFocus; view.LostFocus += OnLostFocus; view.KeyDown += OnKeyDown; } private void OnTextChanged(object sender, TextChangedEventArgs e) { var textBox = (ReactTextBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( textBox.GetTag(), textBox.Text, textBox.CurrentEventCount)); } private void OnGotFocus(object sender, RoutedEventArgs e) { var textBox = (ReactTextBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputFocusEvent(textBox.GetTag())); } private void OnLostFocus(object sender, RoutedEventArgs e) { var textBox = (ReactTextBox)sender; var eventDispatcher = textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher; eventDispatcher.DispatchEvent( new ReactTextInputBlurEvent(textBox.GetTag())); eventDispatcher.DispatchEvent( new ReactTextInputEndEditingEvent( textBox.GetTag(), textBox.Text)); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var textBox = (ReactTextBox)sender; if (!textBox.AcceptsReturn) { e.Handled = true; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputSubmitEditingEvent( textBox.GetTag(), textBox.Text)); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Collections.Generic; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// This class implements a Finite State Machine (FSM) to control the remote connection on the server side. /// There is a similar but not identical FSM on the client side for this connection. /// /// The FSM's states and events are defined to be the same for both the client FSM and the server FSM. /// This design allows the client and server FSM's to /// be as similar as possible, so that the complexity of maintaining them is minimized. /// /// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace /// pipeline themselves. /// /// This FSM defines an event handling matrix, which is filled by the event handlers. /// The state transitions can only be performed by these event handlers, which are private /// to this class. The event handling is done by a single thread, which makes this /// implementation solid and thread safe. /// /// This implementation of the FSM does not allow the remote session to be reused for a connection /// after it is been closed. This design decision is made to simplify the implementation. /// However, the design can be easily modified to allow the reuse of the remote session /// to reconnect after the connection is closed. /// </summary> internal class ServerRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); private ServerRemoteSession _session; private object _syncObject; private Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue = new Queue<RemoteSessionStateMachineEventArgs>(); // whether some thread is actively processing events // in a loop. If this is set then other threads // should simply add to the queue and not attempt // at processing the events in the queue. This will // guarantee that events will always be serialized // and processed private bool _eventsInProcess = false; private EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle; private RemoteSessionState _state; /// <summary> /// Timer used for key exchange. /// </summary> private Timer _keyExchangeTimer; #region Constructors /// <summary> /// This constructor instantiates a FSM object for the server side to control the remote connection. /// It initializes the event handling matrix with event handlers. /// It sets the initial state of the FSM to be Idle. /// </summary> /// <param name="session"> /// This is the remote session object. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { if (session == null) { throw PSTraceSource.NewArgumentNullException("session"); } _session = session; _syncObject = new object(); _stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { _stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatalError; _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += DoCloseFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += DoCloseCompleted; _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += DoNegotiationTimeout; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += DoSendFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += DoReceiveFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect; } _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[(int)RemoteSessionState.NegotiationPending, (int)RemoteSessionEvent.NegotiationReceived] += DoNegotiationReceived; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += DoNegotiationCompleted; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationCompleted] += DoEstablished; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationPending] += DoNegotiationPending; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.MessageReceived] += DoMessageReceived; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += DoNegotiationFailed; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += DoConnectFailed; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySendFailed] += DoKeyExchange; _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; // with connect, a new client can negotiate a key change to a server that has already negotiated key exchange with a previous client _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } } } // Initially, set state to Idle SetState(RemoteSessionState.Idle, null); } #endregion Constructors /// <summary> /// This is a readonly property available to all other classes. It gives the FSM state. /// Other classes can query for this state. Only the FSM itself can change the state. /// </summary> internal RemoteSessionState State { get { return _state; } } /// <summary> /// Helper method used by dependents to figure out if the RaiseEvent /// method can be short-circuited. This will be useful in cases where /// the dependent code wants to take action immediately instead of /// going through state machine. /// </summary> /// <param name="arg"></param> internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg) { if (arg.StateEvent == RemoteSessionEvent.MessageReceived) { if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeySent || // server session will never be in this state.. TODO- remove this _state == RemoteSessionState.EstablishedAndKeyReceived || _state == RemoteSessionState.EstablishedAndKeyExchanged) { return true; } } return false; } /// <summary> /// This method is used by all classes to raise a FSM event. /// The method will queue the event. The event queue will be handled in /// a thread safe manner by a single dedicated thread. /// </summary> /// <param name="fsmEventArg"> /// This parameter contains the event to be raised. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal void RaiseEvent(RemoteSessionStateMachineEventArgs fsmEventArg) { // make sure only one thread is processing events. lock (_syncObject) { s_trace.WriteLine("Event received : {0}", fsmEventArg.StateEvent); _processPendingEventsQueue.Enqueue(fsmEventArg); if (_eventsInProcess) { return; } _eventsInProcess = true; } ProcessEvents(); // currently server state machine doesn't raise events // this will allow server state machine to raise events. // RaiseStateMachineEvents(); } /// <summary> /// Processes events in the queue. If there are no /// more events to process, then sets eventsInProcess /// variable to false. This will ensure that another /// thread which raises an event can then take control /// of processing the events. /// </summary> private void ProcessEvents() { RemoteSessionStateMachineEventArgs eventArgs = null; do { lock (_syncObject) { if (_processPendingEventsQueue.Count == 0) { _eventsInProcess = false; break; } eventArgs = _processPendingEventsQueue.Dequeue(); } RaiseEventPrivate(eventArgs); } while (_eventsInProcess); } /// <summary> /// This is the private version of raising a FSM event. /// It can only be called by the dedicated thread that processes the event queue. /// It calls the event handler /// in the right position of the event handling matrix. /// </summary> /// <param name="fsmEventArg"> /// The parameter contains the actual FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent]; if (handler != null) { s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); handler(this, fsmEventArg); s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); } } #region Event Handlers /// <summary> /// This is the handler for Start event of the FSM. This is the beginning of everything /// else. From this moment on, the FSM will proceeds step by step to eventually reach /// Established state or Closed state. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CreateSession, "StateEvent must be CreateSession"); Dbg.Assert(_state == RemoteSessionState.Idle, "DoCreateSession cannot only be called in Idle state"); DoNegotiationPending(sender, fsmEventArg); } } /// <summary> /// This is the handler for NegotiationPending event. /// NegotiationPending state can be in reached in the following cases /// 1. From Idle to NegotiationPending (during startup) /// 2. From Negotiation(Response)Sent to NegotiationPending. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert((_state == RemoteSessionState.Idle) || (_state == RemoteSessionState.NegotiationSent), "DoNegotiationPending can only occur when the state is Idle or NegotiationSent."); SetState(RemoteSessionState.NegotiationPending, null); } } /// <summary> /// This is the handler for the NegotiationReceived event. /// It sets the new state to be NegotiationReceived. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="fsmEventArg"/> is not NegotiationReceived event or it does not hold the /// client negotiation packet. /// </exception> private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived"); Dbg.Assert(fsmEventArg.RemoteSessionCapability != null, "RemoteSessioncapability must be non-null"); Dbg.Assert(_state == RemoteSessionState.NegotiationPending, "state must be in NegotiationPending state"); if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } if (fsmEventArg.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } SetState(RemoteSessionState.NegotiationReceived, null); } } /// <summary> /// This is the handler for NegotiationSending event. /// It sets the new state to be NegotiationSending, and sends the server side /// negotiation packet by queuing it on the output queue. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSending, "Event must be NegotiationSending"); Dbg.Assert(_state == RemoteSessionState.NegotiationReceived, "State must be NegotiationReceived"); SetState(RemoteSessionState.NegotiationSending, null); _session.SessionDataStructureHandler.SendNegotiationAsync(); } /// <summary> /// This is the handler for NegotiationSendCompleted event. /// It sets the new state to be NegotiationSent. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(_state == RemoteSessionState.NegotiationSending, "State must be NegotiationSending"); Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSendCompleted, "StateEvent must be NegotiationSendCompleted"); SetState(RemoteSessionState.NegotiationSent, null); } } /// <summary> /// This is the handler for the NegotiationCompleted event. /// It sets the new state to be Established. It turns off the negotiation timeout timer. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(_state == RemoteSessionState.NegotiationSent, "State must be NegotiationReceived"); Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationCompleted, "StateEvent must be NegotiationCompleted"); if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationCompleted) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } if (_state != RemoteSessionState.NegotiationSent) { throw PSTraceSource.NewInvalidOperationException(); } SetState(RemoteSessionState.Established, null); } } /// <summary> /// This is the handler for MessageReceived event. It dispatches the data to various components /// that uses the data. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="fsmEventArg"/> does not contain remote data. /// </exception> internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } if (fsmEventArg.RemoteData == null) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } Dbg.Assert(_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyExchanged || _state == RemoteSessionState.EstablishedAndKeyReceived || _state == RemoteSessionState.EstablishedAndKeySent, // server session will never be in this state.. TODO- remove this "State must be Established or EstablishedAndKeySent or EstablishedAndKeyReceived or EstablishedAndKeyExchanged"); RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface; RemotingDataType dataType = fsmEventArg.RemoteData.DataType; Guid clientRunspacePoolId; ServerRunspacePoolDriver runspacePoolDriver; // string errorMessage = null; RemoteDataEventArgs remoteDataForSessionArg = null; switch (targetInterface) { case RemotingTargetInterface.Session: { switch (dataType) { // GETBACK case RemotingDataType.CreateRunspacePool: remoteDataForSessionArg = new RemoteDataEventArgs(fsmEventArg.RemoteData); _session.SessionDataStructureHandler.RaiseDataReceivedEvent(remoteDataForSessionArg); break; default: Dbg.Assert(false, "Should never reach here"); break; } } break; case RemotingTargetInterface.RunspacePool: // GETBACK clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId); if (runspacePoolDriver != null) { runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData); } else { s_trace.WriteLine(@"Server received data for Runspace (id: {0}), but the Runspace cannot be found", clientRunspacePoolId); PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound, clientRunspacePoolId); RemoteSessionStateMachineEventArgs runspaceNotFoundArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure); RaiseEvent(runspaceNotFoundArg); } break; case RemotingTargetInterface.PowerShell: clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId); runspacePoolDriver.DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData); break; default: s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface); PSRemotingDataStructureException reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface); RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2); RaiseEvent(unknownTargetArg); break; } } } /// <summary> /// This is the handler for ConnectFailed event. In this implementation, this should never /// happen. This is because the IO channel is stdin/stdout/stderr redirection. /// Therefore, the connection is a dummy operation. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="fsmEventArg"/> does not contain ConnectFailed event. /// </exception> private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ConnectFailed, "StateEvent must be ConnectFailed"); if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } Dbg.Assert(_state == RemoteSessionState.Connecting, "session State must be Connecting"); // This method should not be called in this implementation. throw PSTraceSource.NewInvalidOperationException(); } } /// <summary> /// This is the handler for FatalError event. It directly calls the DoClose, which /// is the Close event handler. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> does not contains FatalError event. /// </exception> private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.FatalError, "StateEvent must be FatalError"); if (fsmEventArg.StateEvent != RemoteSessionEvent.FatalError) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } DoClose(this, fsmEventArg); } } /// <summary> /// Handle connect event - this is raised when a new client tries to connect to an existing session /// No changes to state. Calls into the session to handle any post connect operations. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"></param> private void DoConnect(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { Dbg.Assert(_state != RemoteSessionState.Idle, "session should not be in idle state when SessionConnect event is queued"); if ((_state != RemoteSessionState.Closed) && (_state != RemoteSessionState.ClosingConnection)) { _session.HandlePostConnect(); } } /// <summary> /// This is the handler for Close event. It closes the connection. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } RemoteSessionState oldState = _state; switch (oldState) { case RemoteSessionState.ClosingConnection: case RemoteSessionState.Closed: // do nothing break; case RemoteSessionState.Connecting: case RemoteSessionState.Connected: case RemoteSessionState.Established: case RemoteSessionState.EstablishedAndKeySent: // server session will never be in this state.. TODO- remove this case RemoteSessionState.EstablishedAndKeyReceived: case RemoteSessionState.EstablishedAndKeyExchanged: case RemoteSessionState.NegotiationReceived: case RemoteSessionState.NegotiationSent: case RemoteSessionState.NegotiationSending: SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason); _session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason); break; case RemoteSessionState.Idle: case RemoteSessionState.UndefinedState: default: Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed); SetState(RemoteSessionState.Closed, forcedCloseException); break; } CleanAll(); } } /// <summary> /// This is the handler for CloseFailed event. /// It simply force the new state to be Closed. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseFailed, "StateEvent must be CloseFailed"); RemoteSessionState stateBeforeTransition = _state; SetState(RemoteSessionState.Closed, fsmEventArg.Reason); // ignore CleanAll(); } } /// <summary> /// This is the handler for CloseCompleted event. It sets the new state to be Closed. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseCompleted, "StateEvent must be CloseCompleted"); SetState(RemoteSessionState.Closed, fsmEventArg.Reason); // Close the session only after changing the state..this way // state machine will not process anything. _session.Close(fsmEventArg); CleanAll(); } } /// <summary> /// This is the handler for NegotiationFailed event. /// It raises a Close event to trigger the connection to be shutdown. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationFailed, "StateEvent must be NegotiationFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); RaiseEventPrivate(closeArg); } } /// <summary> /// This is the handler for NegotiationTimeout event. /// If the connection is already Established, it ignores this event. /// Otherwise, it raises a Close event to trigger a close of the connection. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationTimeout, "StateEvent must be NegotiationTimeout"); if (_state == RemoteSessionState.Established) { // ignore return; } RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); RaiseEventPrivate(closeArg); } } /// <summary> /// This is the handler for SendFailed event. /// This is an indication that the wire layer IO is no longer connected. So it raises /// a Close event to trigger a connection shutdown. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.SendFailed, "StateEvent must be SendFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); RaiseEventPrivate(closeArg); } } /// <summary> /// This is the handler for ReceivedFailed event. /// This is an indication that the wire layer IO is no longer connected. So it raises /// a Close event to trigger a connection shutdown. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ReceiveFailed, "StateEvent must be ReceivedFailed"); RemoteSessionStateMachineEventArgs closeArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close); RaiseEventPrivate(closeArg); } } /// <summary> /// This method contains all the logic for handling the state machine /// for key exchange. All the different scenarios are covered in this. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Event args.</param> private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eventArgs) { // There are corner cases with disconnect that can result in client receiving outdated key exchange packets // ***TODO*** Deal with this on the client side. Key exchange packets should have additional information // that identify the context of negotiation. Just like callId in SetMax and SetMinRunspaces messages Dbg.Assert(_state >= RemoteSessionState.Established, "Key Receiving can only be raised after reaching the Established state"); switch (eventArgs.StateEvent) { case RemoteSessionEvent.KeyReceived: { // does the server ever start key exchange process??? This may not be required if (_state == RemoteSessionState.EstablishedAndKeyRequested) { // reset the timer Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } } // the key import would have been done // set state accordingly SetState(RemoteSessionState.EstablishedAndKeyReceived, eventArgs.Reason); // you need to send an encrypted session key to the client _session.SendEncryptedSessionKey(); } break; case RemoteSessionEvent.KeySent: { if (_state == RemoteSessionState.EstablishedAndKeyReceived) { // key exchange is now complete SetState(RemoteSessionState.EstablishedAndKeyExchanged, eventArgs.Reason); } } break; case RemoteSessionEvent.KeyRequested: { if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged)) { // the key has been sent set state accordingly SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason); // start the timer _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ServerDefaultKeepAliveTimeoutMs, Timeout.Infinite); } } break; case RemoteSessionEvent.KeyReceiveFailed: { if ((_state == RemoteSessionState.Established) || (_state == RemoteSessionState.EstablishedAndKeyExchanged)) { return; } DoClose(this, eventArgs); } break; case RemoteSessionEvent.KeySendFailed: { DoClose(this, eventArgs); } break; } } /// <summary> /// Handles the timeout for key exchange. /// </summary> /// <param name="sender">Sender of this event.</param> private void HandleKeyExchangeTimeout(object sender) { Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeyRequested, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } PSRemotingDataStructureException exception = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerKeyExchangeFailed); RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception)); } #endregion Event Handlers /// <summary> /// This method is designed to be a cleanup routine after the connection is closed. /// It can also be used for graceful shutdown of the server process, which is not currently /// implemented. /// </summary> private void CleanAll() { } /// <summary> /// Set the FSM state to a new state. /// </summary> /// <param name="newState"> /// The new state. /// </param> /// <param name="reason"> /// Optional parameter that can provide additional information. This is currently not used. /// </param> private void SetState(RemoteSessionState newState, Exception reason) { RemoteSessionState oldState = _state; if (newState != oldState) { _state = newState; s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); } // TODO: else should we close the session here? } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF.Record { using System; using System.IO; using System.Text; using NUnit.Framework; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.Util; using TestCases.HSSF.Record; using NPOI.HSSF.Record; /** * Tests that serialization and deserialization of the TextObjectRecord . * Test data taken directly from a real Excel file. * * @author Yegor Kozlov */ [TestFixture] public class TestTextObjectRecord { private static byte[] simpleData = HexRead.ReadFromString( "B6 01 12 00 " + "12 02 00 00 00 00 00 00" + "00 00 0D 00 08 00 00 00" + "00 00 " + "3C 00 0E 00 " + "00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " + "3C 00 08 " + "00 0D 00 00 00 00 00 00 00" ); [Test] public void TestRead() { RecordInputStream is1 = TestcaseRecordInputStream.Create(simpleData); TextObjectRecord record = new TextObjectRecord(is1); Assert.AreEqual(TextObjectRecord.sid, record.Sid); Assert.AreEqual(HorizontalTextAlignment.Left, record.HorizontalTextAlignment); Assert.AreEqual(VerticalTextAlignment.Top, record.VerticalTextAlignment); Assert.IsTrue(record.IsTextLocked); Assert.AreEqual(TextOrientation.None, record.TextOrientation); Assert.AreEqual("Hello, World!", record.Str.String); } [Test] public void TestWrite() { HSSFRichTextString str = new HSSFRichTextString("Hello, World!"); TextObjectRecord record = new TextObjectRecord(); record.Str = (/*setter*/str); record.HorizontalTextAlignment = (/*setter*/ HorizontalTextAlignment.Left); record.VerticalTextAlignment = (/*setter*/ VerticalTextAlignment.Top); record.IsTextLocked = (/*setter*/ true); record.TextOrientation = (/*setter*/ TextOrientation.None); byte[] ser = record.Serialize(); Assert.AreEqual(ser.Length, simpleData.Length); Assert.IsTrue(Arrays.Equals(simpleData, ser)); //read again RecordInputStream is1 = TestcaseRecordInputStream.Create(simpleData); record = new TextObjectRecord(is1); } /** * Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty */ [Test] public void TestWriteEmpty() { HSSFRichTextString str = new HSSFRichTextString(""); TextObjectRecord record = new TextObjectRecord(); record.Str = (/*setter*/str); byte[] ser = record.Serialize(); int formatDataLen = LittleEndian.GetUShort(ser, 16); Assert.AreEqual(0, formatDataLen, "formatDataLength"); Assert.AreEqual(22, ser.Length); // just the TXO record //read again RecordInputStream is1 = TestcaseRecordInputStream.Create(ser); record = new TextObjectRecord(is1); Assert.AreEqual(0, record.Str.Length); } /** * Test that TextObjectRecord Serializes logs records properly. */ [Test] public void TestLongRecords() { int[] length = { 1024, 2048, 4096, 8192, 16384 }; //test against strings of different length for (int i = 0; i < length.Length; i++) { StringBuilder buff = new StringBuilder(length[i]); for (int j = 0; j < length[i]; j++) { buff.Append("x"); } IRichTextString str = new HSSFRichTextString(buff.ToString()); TextObjectRecord obj = new TextObjectRecord(); obj.Str = (/*setter*/str); byte[] data = obj.Serialize(); RecordInputStream is1 = new RecordInputStream(new MemoryStream(data)); is1.NextRecord(); TextObjectRecord record = new TextObjectRecord(is1); str = record.Str; Assert.AreEqual(buff.Length, str.Length); Assert.AreEqual(buff.ToString(), str.String); } } /** * Test cloning */ [Test] public void TestClone() { String text = "Hello, World"; HSSFRichTextString str = new HSSFRichTextString(text); TextObjectRecord obj = new TextObjectRecord(); obj.Str = (/*setter*/ str); TextObjectRecord Cloned = (TextObjectRecord)obj.Clone(); Assert.AreEqual(obj.RecordSize, Cloned.RecordSize); Assert.AreEqual(obj.HorizontalTextAlignment, Cloned.HorizontalTextAlignment); Assert.AreEqual(obj.Str.String, Cloned.Str.String); //finally check that the Serialized data is the same byte[] src = obj.Serialize(); byte[] cln = Cloned.Serialize(); Assert.IsTrue(Arrays.Equals(src, cln)); } /** similar to {@link #simpleData} but with link formula at end of TXO rec*/ private static byte[] linkData = HexRead.ReadFromString( "B6 01 " + // TextObjectRecord.sid "1E 00 " + // size 18 "44 02 02 00 00 00 00 00" + "00 00 " + "02 00 " + // strLen 2 "10 00 " + // 16 bytes for 2 format Runs "00 00 00 00 " + "05 00 " + // formula size "D4 F0 8A 03 " + // unknownInt "24 01 00 13 C0 " + //tRef(T2) "13 " + // ?? "3C 00 " + // ContinueRecord.sid "03 00 " + // size 3 "00 " + // unicode compressed "41 42 " + // 'AB' "3C 00 " + // ContinueRecord.sid "10 00 " + // size 16 "00 00 18 00 00 00 00 00 " + "02 00 00 00 00 00 00 00 " ); [Test] public void TestLinkFormula() { RecordInputStream is1 = new RecordInputStream(new MemoryStream(linkData)); is1.NextRecord(); TextObjectRecord rec = new TextObjectRecord(is1); Ptg ptg = rec.LinkRefPtg; Assert.IsNotNull(ptg); Assert.AreEqual(typeof(RefPtg), ptg.GetType()); RefPtg rptg = (RefPtg)ptg; Assert.AreEqual("T2", rptg.ToFormulaString()); byte[] data2 = rec.Serialize(); Assert.AreEqual(linkData.Length, data2.Length); Assert.IsTrue(Arrays.Equals(linkData, data2)); } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Linq; using FluentMigrator.Builders.Alter.Column; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; using FluentMigrator.Runner.Extensions; using Moq; using NUnit.Framework; using NUnit.Should; using FluentMigrator.Builders; namespace FluentMigrator.Tests.Unit.Builders.Alter { [TestFixture] public class AlterColumnExpressionBuilderTests { private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<AlterColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>()); callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(columnExpression); } private void VerifyColumnDbType(DbType expected, Action<AlterColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Type = expected); } private void VerifyColumnSize(int expected, Action<AlterColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Size = expected); } private void VerifyColumnPrecision(int expected, Action<AlterColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Precision = expected); } private void VerifyColumnCollation(string expected, Action<AlterColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new AlterColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.CollationName = expected); } [Test] public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString()); } [Test] public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(42)); } [Test] public void CallingAsAnsiStringWithSizeSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(42, b => b.AsAnsiString(42)); } [Test] public void CallingAsBinarySetsColumnDbTypeToBinary() { VerifyColumnDbType(DbType.Binary, b => b.AsBinary()); } [Test] public void CallingAsBinaryWithSizeSetsColumnDbTypeToBinary() { VerifyColumnDbType(DbType.Binary, b => b.AsBinary(42)); } [Test] public void CallingAsBinaryWithSizeSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(42, b => b.AsBinary(42)); } [Test] public void CallingAsBooleanSetsColumnDbTypeToBoolean() { VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean()); } [Test] public void CallingAsByteSetsColumnDbTypeToByte() { VerifyColumnDbType(DbType.Byte, b => b.AsByte()); } [Test] public void CallingAsCurrencySetsColumnDbTypeToCurrency() { VerifyColumnDbType(DbType.Currency, b => b.AsCurrency()); } [Test] public void CallingAsCustomSetsTypeToNullAndSetsCustomType() { VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test")); VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test")); } [Test] public void CallingAsDateSetsColumnDbTypeToDate() { VerifyColumnDbType(DbType.Date, b => b.AsDate()); } [Test] public void CallingAsDateTimeSetsColumnDbTypeToDateTime() { VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime()); } [Test] public void CallingAsDateTimeOffsetSetsColumnDbTypeToDateTimeOffset() { VerifyColumnDbType(DbType.DateTimeOffset, b => b.AsDateTimeOffset()); } [Test] public void CallingAsDecimalSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal()); } [Test] public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue() { VerifyColumnPrecision(2, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(1, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalWithSizeAndPrecisionSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDoubleSetsColumnDbTypeToDouble() { VerifyColumnDbType(DbType.Double, b => b.AsDouble()); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength() { VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength() { VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255)); } [Test] public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthString(255)); } [Test] public void CallingAsFloatSetsColumnDbTypeToSingle() { VerifyColumnDbType(DbType.Single, b => b.AsFloat()); } [Test] public void CallingAsGuidSetsColumnDbTypeToGuid() { VerifyColumnDbType(DbType.Guid, b => b.AsGuid()); } [Test] public void CallingAsInt16SetsColumnDbTypeToInt16() { VerifyColumnDbType(DbType.Int16, b => b.AsInt16()); } [Test] public void CallingAsInt32SetsColumnDbTypeToInt32() { VerifyColumnDbType(DbType.Int32, b => b.AsInt32()); } [Test] public void CallingAsInt64SetsColumnDbTypeToInt64() { VerifyColumnDbType(DbType.Int64, b => b.AsInt64()); } [Test] public void CallingAsStringSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString()); } [Test] public void CallingAsStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsStringWithLengthSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString(255)); } [Test] public void CallingAsAnsiStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsAnsiString(Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsFixedLengthAnsiStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthAnsiString(255, Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsFixedLengthStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthString(255, Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsString(Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsTimeSetsColumnDbTypeToTime() { VerifyColumnDbType(DbType.Time, b => b.AsTime()); } [Test] public void CallingAsXmlSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml()); } [Test] public void CallingAsXmlSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsXml(255)); } [Test] public void CallingAsXmlWithSizeSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml(255)); } [Test] public void CallingForeignKeyAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ForeignKey("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.PrimaryTable == "FooTable" && fk.ForeignKey.PrimaryColumns.Contains("BarColumn") && fk.ForeignKey.PrimaryColumns.Count == 1 && fk.ForeignKey.ForeignTable == "Bacon" && fk.ForeignKey.ForeignColumns.Contains("BaconId") && fk.ForeignKey.ForeignColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingForeignKeySetsIsForeignKeyToTrue() { VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey()); } [Test] public void CallingIdentitySetsIsIdentityToTrue() { VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity()); } [Test] public void CallingSeededIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(23, 44); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 23)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44)); } [Test] public void CallingIndexedCallsHelperWithNullIndexName() { VerifyColumnHelperCall(c => c.Indexed(), h => h.Indexed(null)); } [Test] public void CallingIndexedNamedCallsHelperWithName() { VerifyColumnHelperCall(c => c.Indexed("MyIndexName"), h => h.Indexed("MyIndexName")); } [Test] public void NullableUsesHelper() { VerifyColumnHelperCall(c => c.Nullable(), h => h.SetNullable(true)); } [Test] public void NotNullableUsesHelper() { VerifyColumnHelperCall(c => c.NotNullable(), h => h.SetNullable(false)); } [Test] public void UniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique(), h => h.Unique(null)); } [Test] public void NamedUniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique("asdf"), h => h.Unique("asdf")); } [Test] public void CallingOnTableSetsTableName() { var expressionMock = new Mock<AlterColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.OnTable("Bacon"); expressionMock.VerifySet(x => x.TableName = "Bacon"); } [Test] public void CallingPrimaryKeySetsIsPrimaryKeyToTrue() { VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey()); } [Test] public void CallingReferencedByAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ReferencedBy("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.ForeignTable == "FooTable" && fk.ForeignKey.ForeignColumns.Contains("BarColumn") && fk.ForeignKey.ForeignColumns.Count == 1 && fk.ForeignKey.PrimaryTable == "Bacon" && fk.ForeignKey.PrimaryColumns.Contains("BaconId") && fk.ForeignKey.PrimaryColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule) { var builder = new AlterColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new AlterColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDelete(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new AlterColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDeleteOrUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [Test] public void CallingWithDefaultValueAddsAlterDefaultConstraintExpression() { const int value = 42; var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.WithDefaultValue(value); columnMock.VerifySet(c => c.DefaultValue = value); collectionMock.Verify(x => x.Add(It.Is<AlterDefaultConstraintExpression>(e => e.DefaultValue.Equals(value)))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingWithDefaultAddsAlterDefaultConstraintExpression() { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<AlterColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.WithDefault(SystemMethods.NewGuid); columnMock.VerifySet(c => c.DefaultValue = SystemMethods.NewGuid); collectionMock.Verify(x => x.Add(It.Is<AlterDefaultConstraintExpression>(e => e.DefaultValue.Equals(SystemMethods.NewGuid)))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void ColumnHelperSetOnCreation() { var expressionMock = new Mock<AlterColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); Assert.IsNotNull(builder.ColumnHelper); } [Test] public void IColumnExpressionBuilder_UsesExpressionSchemaAndTableName() { var expressionMock = new Mock<AlterColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); expressionMock.SetupGet(n => n.SchemaName).Returns("Fred"); expressionMock.SetupGet(n => n.TableName).Returns("Flinstone"); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreEqual("Fred", builderAsInterface.SchemaName); Assert.AreEqual("Flinstone", builderAsInterface.TableName); } [Test] public void IColumnExpressionBuilder_UsesExpressionColumn() { var expressionMock = new Mock<AlterColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var curColumn = new Mock<ColumnDefinition>().Object; expressionMock.SetupGet(n => n.Column).Returns(curColumn); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreSame(curColumn, builderAsInterface.Column); } private void VerifyColumnHelperCall(Action<AlterColumnExpressionBuilder> callToTest, System.Linq.Expressions.Expression<Action<ColumnExpressionBuilderHelper>> expectedHelperAction) { var expressionMock = new Mock<AlterColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var helperMock = new Mock<ColumnExpressionBuilderHelper>(); var builder = new AlterColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ColumnHelper = helperMock.Object; callToTest(builder); helperMock.Verify(expectedHelperAction); } } }
// <copyright file="DriverService.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Security.Permissions; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium { /// <summary> /// Exposes the service provided by a native WebDriver server executable. /// </summary> public abstract class DriverService : ICommandServer { private string driverServicePath; private string driverServiceExecutableName; private string driverServiceHostName = "localhost"; private int driverServicePort; private bool silent; private bool hideCommandPromptWindow; private bool isDisposed; private Process driverServiceProcess; /// <summary> /// Initializes a new instance of the <see cref="DriverService"/> class. /// </summary> /// <param name="servicePath">The full path to the directory containing the executable providing the service to drive the browser.</param> /// <param name="port">The port on which the driver executable should listen.</param> /// <param name="driverServiceExecutableName">The file name of the driver service executable.</param> /// <param name="driverServiceDownloadUrl">A URL at which the driver service executable may be downloaded.</param> /// <exception cref="ArgumentException"> /// If the path specified is <see langword="null"/> or an empty string. /// </exception> /// <exception cref="DriverServiceNotFoundException"> /// If the specified driver service executable does not exist in the specified directory. /// </exception> protected DriverService(string servicePath, int port, string driverServiceExecutableName, Uri driverServiceDownloadUrl) { if (string.IsNullOrEmpty(servicePath)) { throw new ArgumentException("Path to locate driver executable cannot be null or empty.", "servicePath"); } string executablePath = Path.Combine(servicePath, driverServiceExecutableName); if (!File.Exists(executablePath)) { throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The file {0} does not exist. The driver can be downloaded at {1}", executablePath, driverServiceDownloadUrl)); } this.driverServicePath = servicePath; this.driverServiceExecutableName = driverServiceExecutableName; this.driverServicePort = port; } /// <summary> /// Occurs when the driver process starts is starting. /// </summary> public event EventHandler<DriverProcessStartingEventArgs> DriverProcessStarting; /// <summary> /// Gets the Uri of the service. /// </summary> public Uri ServiceUrl { get { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", this.driverServiceHostName, this.driverServicePort)); } } /// <summary> /// Gets or sets the host name of the service. Defaults to "localhost." /// </summary> /// <remarks> /// Most driver service executables do not allow connections from remote /// (non-local) machines. This property can be used as a workaround so /// that an IP address (like "127.0.0.1" or "::1") can be used instead. /// </remarks> public string HostName { get { return this.driverServiceHostName; } set { this.driverServiceHostName = value; } } /// <summary> /// Gets or sets the port of the service. /// </summary> public int Port { get { return this.driverServicePort; } set { this.driverServicePort = value; } } /// <summary> /// Gets or sets a value indicating whether the initial diagnostic information is suppressed /// when starting the driver server executable. Defaults to <see langword="false"/>, meaning /// diagnostic information should be shown by the driver server executable. /// </summary> public bool SuppressInitialDiagnosticInformation { get { return this.silent; } set { this.silent = value; } } /// <summary> /// Gets a value indicating whether the service is running. /// </summary> public bool IsRunning { [SecurityPermission(SecurityAction.Demand)] get { return this.driverServiceProcess != null && !this.driverServiceProcess.HasExited; } } /// <summary> /// Gets or sets a value indicating whether the command prompt window of the service should be hidden. /// </summary> public bool HideCommandPromptWindow { get { return this.hideCommandPromptWindow; } set { this.hideCommandPromptWindow = value; } } /// <summary> /// Gets the process ID of the running driver service executable. Returns 0 if the process is not running. /// </summary> public int ProcessId { get { if (this.IsRunning) { // There's a slight chance that the Process object is running, // but does not have an ID set. This should be rare, but we // definitely don't want to throw an exception. try { return this.driverServiceProcess.Id; } catch (InvalidOperationException) { } } return 0; } } /// <summary> /// Gets the executable file name of the driver service. /// </summary> protected string DriverServiceExecutableName { get { return this.driverServiceExecutableName; } } /// <summary> /// Gets the command-line arguments for the driver service. /// </summary> protected virtual string CommandLineArguments { get { return string.Format(CultureInfo.InvariantCulture, "--port={0}", this.driverServicePort); } } /// <summary> /// Gets a value indicating the time to wait for an initial connection before timing out. /// </summary> protected virtual TimeSpan InitializationTimeout { get { return TimeSpan.FromSeconds(20); } } /// <summary> /// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate. /// </summary> protected virtual TimeSpan TerminationTimeout { get { return TimeSpan.FromSeconds(10); } } /// <summary> /// Gets a value indicating whether the service has a shutdown API that can be called to terminate /// it gracefully before forcing a termination. /// </summary> protected virtual bool HasShutdown { get { return true; } } /// <summary> /// Gets a value indicating whether the service is responding to HTTP requests. /// </summary> protected virtual bool IsInitialized { get { bool isInitialized = false; try { Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri(DriverCommand.Status, UriKind.Relative)); HttpWebRequest request = HttpWebRequest.Create(serviceHealthUri) as HttpWebRequest; request.KeepAlive = false; request.Timeout = 5000; HttpWebResponse response = request.GetResponse() as HttpWebResponse; // Checking the response from the 'status' end point. Note that we are simply checking // that the HTTP status returned is a 200 status, and that the resposne has the correct // Content-Type header. A more sophisticated check would parse the JSON response and // validate its values. At the moment we do not do this more sophisticated check. isInitialized = response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase); response.Close(); } catch (WebException ex) { Console.WriteLine(ex.Message); } return isInitialized; } } /// <summary> /// Releases all resources associated with this <see cref="DriverService"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Starts the DriverService. /// </summary> [SecurityPermission(SecurityAction.Demand)] public void Start() { this.driverServiceProcess = new Process(); this.driverServiceProcess.StartInfo.FileName = Path.Combine(this.driverServicePath, this.driverServiceExecutableName); this.driverServiceProcess.StartInfo.Arguments = this.CommandLineArguments; this.driverServiceProcess.StartInfo.UseShellExecute = false; this.driverServiceProcess.StartInfo.CreateNoWindow = this.hideCommandPromptWindow; DriverProcessStartingEventArgs eventArgs = new DriverProcessStartingEventArgs(this.driverServiceProcess.StartInfo); this.OnDriverProcessStarting(eventArgs); this.driverServiceProcess.Start(); bool serviceAvailable = this.WaitForServiceInitialization(); if (!serviceAvailable) { string msg = "Cannot start the driver service on " + this.ServiceUrl; throw new WebDriverException(msg); } } /// <summary> /// Finds the specified driver service executable. /// </summary> /// <param name="executableName">The file name of the executable to find.</param> /// <param name="downloadUrl">A URL at which the driver service executable may be downloaded.</param> /// <returns>The directory containing the driver service executable.</returns> /// <exception cref="DriverServiceNotFoundException"> /// If the specified driver service executable does not exist in the current directory or in a directory on the system path. /// </exception> protected static string FindDriverServiceExecutable(string executableName, Uri downloadUrl) { string serviceDirectory = FileUtilities.FindFile(executableName); if (string.IsNullOrEmpty(serviceDirectory)) { throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The {0} file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at {1}.", executableName, downloadUrl)); } return serviceDirectory; } /// <summary> /// Releases all resources associated with this <see cref="DriverService"/>. /// </summary> /// <param name="disposing"><see langword="true"/> if the Dispose method was explicitly called; otherwise, <see langword="false"/>.</param> protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { this.Stop(); } this.isDisposed = true; } } /// <summary> /// Raises the <see cref="DriverProcessStarting"/> event. /// </summary> /// <param name="eventArgs">A <see cref="DriverProcessStartingEventArgs"/> that contains the event data.</param> protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs) { if (eventArgs == null) { throw new ArgumentNullException("eventArgs", "eventArgs must not be null"); } if (this.DriverProcessStarting != null) { this.DriverProcessStarting(this, eventArgs); } } /// <summary> /// Stops the DriverService. /// </summary> [SecurityPermission(SecurityAction.Demand)] private void Stop() { if (this.IsRunning) { if (this.HasShutdown) { Uri shutdownUrl = new Uri(this.ServiceUrl, "/shutdown"); DateTime timeout = DateTime.Now.Add(this.TerminationTimeout); while (this.IsRunning && DateTime.Now < timeout) { try { // Issue the shutdown HTTP request, then wait a short while for // the process to have exited. If the process hasn't yet exited, // we'll retry. We wait for exit here, since catching the exception // for a failed HTTP request due to a closed socket is particularly // expensive. HttpWebRequest request = HttpWebRequest.Create(shutdownUrl) as HttpWebRequest; request.KeepAlive = false; HttpWebResponse response = request.GetResponse() as HttpWebResponse; response.Close(); this.driverServiceProcess.WaitForExit(3000); } catch (WebException) { } } } // If at this point, the process still hasn't exited, wait for one // last-ditch time, then, if it still hasn't exited, kill it. Note // that falling into this branch of code should be exceedingly rare. if (this.IsRunning) { this.driverServiceProcess.WaitForExit(Convert.ToInt32(this.TerminationTimeout.TotalMilliseconds)); if (!this.driverServiceProcess.HasExited) { this.driverServiceProcess.Kill(); } } this.driverServiceProcess.Dispose(); this.driverServiceProcess = null; } } /// <summary> /// Waits until a the service is initialized, or the timeout set /// by the <see cref="InitializationTimeout"/> property is reached. /// </summary> /// <returns><see langword="true"/> if the service is properly started and receiving HTTP requests; /// otherwise; <see langword="false"/>.</returns> private bool WaitForServiceInitialization() { bool isInitialized = false; DateTime timeout = DateTime.Now.Add(this.InitializationTimeout); while (!isInitialized && DateTime.Now < timeout) { // If the driver service process has exited, we can exit early. if (!this.IsRunning) { break; } isInitialized = this.IsInitialized; } return isInitialized; } } }
using System; using System.Collections.Generic; using System.Threading; namespace Omnius.Base { public static class IDictionaryExtensions { public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (addValueFactory == null) throw new ArgumentNullException(nameof(addValueFactory)); if (updateValueFactory == null) throw new ArgumentNullException(nameof(updateValueFactory)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); TValue result; if (!dictionary.TryGetValue(key, out result)) { result = addValueFactory(key); dictionary.Add(key, result); } else { result = updateValueFactory(key, result); dictionary[key] = result; } return result; } finally { if (lockToken) Monitor.Exit(lockObject); } } public static TValue AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (updateValueFactory == null) throw new ArgumentNullException(nameof(updateValueFactory)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); TValue result; if (!dictionary.TryGetValue(key, out result)) { result = addValue; dictionary.Add(key, result); } else { result = updateValueFactory(key, result); dictionary[key] = result; } return result; } finally { if (lockToken) Monitor.Exit(lockObject); } } public static bool TryUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue newValue, Predicate<TValue> match) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (match == null) throw new ArgumentNullException(nameof(match)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); if (dictionary.TryGetValue(key, out TValue result) && match(result)) { dictionary[key] = newValue; return true; } return false; } finally { if (lockToken) Monitor.Exit(lockObject); } } public static bool TryRemove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); dictionary.TryGetValue(key, out value); return dictionary.Remove(key); } finally { if (lockToken) Monitor.Exit(lockObject); } } public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); int count = dictionary.Count; dictionary[key] = value; return (count != dictionary.Count); } finally { if (lockToken) Monitor.Exit(lockObject); } } public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> valueFactory) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); TValue result; if (dictionary.TryGetValue(key, out result)) return result; var value = valueFactory(key); dictionary.Add(key, value); return value; } finally { if (lockToken) Monitor.Exit(lockObject); } } public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); object lockObject = ExtensionsUtils.GetLockObject(dictionary); bool lockToken = false; try { if (lockObject != null) Monitor.Enter(lockObject, ref lockToken); TValue result; if (dictionary.TryGetValue(key, out result)) return result; dictionary.Add(key, value); return value; } finally { if (lockToken) Monitor.Exit(lockObject); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // ContextStackTest.cs - Unit tests for // System.ComponentModel.Design.Serialization.ContextStack // // Author: // Ivan N. Zlatev <[email protected]> // // Copyright (C) 2007 Ivan N. Zlatev <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel.Design.Serialization; using Xunit; namespace System.ComponentModel.Tests { public class ContextStackTest { [Fact] public void IntegrityTest() { ContextStack stack = new ContextStack(); string one = "one"; string two = "two"; stack.Push(two); stack.Push(one); Assert.Same(one, stack[typeof(string)]); Assert.Same(one, stack[0]); Assert.Same(one, stack.Current); Assert.Same(one, stack.Pop()); Assert.Same(two, stack[typeof(string)]); Assert.Same(two, stack[0]); Assert.Same(two, stack.Current); string three = "three"; stack.Append(three); Assert.Same(two, stack[typeof(string)]); Assert.Same(two, stack[0]); Assert.Same(two, stack.Current); Assert.Same(two, stack.Pop()); Assert.Same(three, stack[typeof(string)]); Assert.Same(three, stack[0]); Assert.Same(three, stack.Current); Assert.Same(three, stack.Pop()); Assert.Null(stack.Pop()); Assert.Null(stack.Current); } [Fact] public void Append_Context_Null() { ContextStack stack = new ContextStack(); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => stack.Append(null)); Assert.Equal(typeof(ArgumentNullException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.NotNull(ex.Message); Assert.Equal("context", ex.ParamName); } } [Fact] // Item (Int32) public void Indexer1() { ContextStack stack = new ContextStack(); string one = "one"; string two = "two"; stack.Push(one); stack.Push(two); Assert.Same(two, stack[0]); Assert.Same(one, stack[1]); Assert.Null(stack[2]); Assert.Same(two, stack.Pop()); Assert.Same(one, stack[0]); Assert.Null(stack[1]); Assert.Same(one, stack.Pop()); Assert.Null(stack[0]); Assert.Null(stack[1]); } [Fact] // Item (Int32) public void Indexer1_Level_Negative() { ContextStack stack = new ContextStack(); stack.Push(new Foo()); ArgumentOutOfRangeException ex; ex = Assert.Throws<ArgumentOutOfRangeException>(() => stack[-1]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); } ex = Assert.Throws<ArgumentOutOfRangeException>(() => stack[-5]); Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.Equal(new ArgumentOutOfRangeException("level").Message, ex.Message); Assert.Equal("level", ex.ParamName); } } [Fact] // Item (Type) public void Indexer2() { ContextStack stack = new ContextStack(); Foo foo = new Foo(); FooBar foobar = new FooBar(); stack.Push(foobar); stack.Push(foo); Assert.Same(foo, stack[typeof(Foo)]); Assert.Same(foo, stack[typeof(IFoo)]); Assert.Same(foo, stack.Pop()); Assert.Same(foobar, stack[typeof(Foo)]); Assert.Same(foobar, stack[typeof(FooBar)]); Assert.Same(foobar, stack[typeof(IFoo)]); Assert.Null(stack[typeof(string)]); } [Fact] // Item (Type) public void Indexer2_Type_Null() { ContextStack stack = new ContextStack(); stack.Push(new Foo()); ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => stack[(Type)null]); Assert.Equal(typeof(ArgumentNullException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.NotNull(ex.Message); Assert.Equal("type", ex.ParamName); } } [Fact] public void Push_Context_Null() { ContextStack stack = new ContextStack(); ArgumentNullException ex= Assert.Throws<ArgumentNullException>(()=> stack.Push(null)); Assert.Equal(typeof(ArgumentNullException), ex.GetType()); Assert.Null(ex.InnerException); if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames. { Assert.NotNull(ex.Message); Assert.Equal("context", ex.ParamName); } } [Fact] public void Append_NoItems_Success() { var stack = new ContextStack(); stack.Append("value"); Assert.Equal("value", stack[0]); } [Fact] public void Indexer_GetWithoutItems_ReturnsNull() { var stack = new ContextStack(); Assert.Null(stack[1]); Assert.Null(stack[typeof(int)]); } public interface IFoo { } public class Foo : IFoo { } public class FooBar : Foo { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace Mvc.Datatables.DynamicLinq { public class ClassFactory { public static readonly ClassFactory Instance = new ClassFactory(); static ClassFactory() { } // Trigger lazy initialization of static fields ModuleBuilder module; Dictionary<Signature, Type> classes; int classCount; ReaderWriterLock rwLock; private ClassFactory() { AssemblyName name = new AssemblyName("DynamicClasses"); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { module = assembly.DefineDynamicModule("Module"); } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } classes = new Dictionary<Signature, Type>(); rwLock = new ReaderWriterLock(); } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties) { rwLock.AcquireReaderLock(Timeout.Infinite); try { Signature signature = new Signature(properties); Type type; if (!classes.TryGetValue(signature, out type)) { type = CreateDynamicClass(signature.properties); classes.Add(signature, type); } return type; } finally { rwLock.ReleaseReaderLock(); } } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties, Type resultType = null, Type baseType = null) { rwLock.AcquireReaderLock(Timeout.Infinite); try { Signature signature = new Signature(properties); Type type; if (!classes.TryGetValue(signature, out type)) { if (resultType == null) type = CreateDynamicClass(signature.properties); else { type = CreateDynamicClass(signature.properties, resultType, baseType); } classes.Add(signature, type); } return type; } finally { rwLock.ReleaseReaderLock(); } } Type CreateDynamicClass(DynamicProperty[] properties) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(object)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { classCount++; rwLock.DowngradeFromWriterLock(ref cookie); } } Type CreateDynamicClass(DynamicProperty[] properties, Type resultType, Type baseType = null) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = null; if (baseType != null) { tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, baseType); } else { tb = this.module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(object)); } tb.AddInterfaceImplementation(resultType); FieldInfo[] fields = GenerateProperties(tb, properties, resultType); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { classCount++; rwLock.DowngradeFromWriterLock(ref cookie); } } FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties, Type returnType = null) { FieldInfo[] fields = new FieldBuilder[properties.Length]; for (int i = 0; i < properties.Length; i++) { DynamicProperty dp = properties[i]; PrintPropertyInfo(dp); FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null); if (dp.CustomAttributeBuilder != null) pb.SetCustomAttribute(dp.CustomAttributeBuilder); MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual, dp.Type, Type.EmptyTypes); ILGenerator genGet = mbGet.GetILGenerator(); genGet.Emit(OpCodes.Ldarg_0); genGet.Emit(OpCodes.Ldfld, fb); genGet.Emit(OpCodes.Ret); if (returnType != null) { var returnTypeMi = returnType.GetMethod(mbGet.Name); if (returnTypeMi != null) tb.DefineMethodOverride(mbGet, returnTypeMi); } MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual, null, new Type[] { dp.Type }); ILGenerator genSet = mbSet.GetILGenerator(); genSet.Emit(OpCodes.Ldarg_0); genSet.Emit(OpCodes.Ldarg_1); genSet.Emit(OpCodes.Stfld, fb); genSet.Emit(OpCodes.Ret); if (returnType != null) { var returnTypeMi = returnType.GetMethod(mbSet.Name); if (returnTypeMi != null) tb.DefineMethodOverride(mbSet, returnTypeMi); } pb.SetGetMethod(mbGet); pb.SetSetMethod(mbSet); fields[i] = fb; } return fields; } [Conditional("DEBUG")] void PrintPropertyInfo(DynamicProperty dp) { Debug.WriteLine(String.Format("Building Property {0} of Type {1}", dp.Name, dp.Type.Name)); } void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(bool), new Type[] { typeof(object) }); ILGenerator gen = mb.GetILGenerator(); LocalBuilder other = gen.DeclareLocal(tb); Label next = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Isinst, tb); gen.Emit(OpCodes.Stloc, other); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); } gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ret); } void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes); ILGenerator gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof(EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Ret); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection.Emit; namespace XSharp.MacroCompiler.Syntax { using static CodeGen; abstract internal partial class Node { internal virtual void Emit(ILGenerator ilg) { throw new InternalError(); } } abstract internal partial class Expr : Node { internal virtual void Emit(ILGenerator ilg, bool preserve) { throw new InternalError(); } internal virtual void EmitSet(ILGenerator ilg, bool preserve) { throw new InternalError(); } internal virtual void EmitAddr(ILGenerator ilg) { throw new InternalError(); } internal sealed override void Emit(ILGenerator ilg) { Emit(ilg, true); } } abstract internal partial class TypeExpr : Expr { } abstract internal partial class NameExpr : TypeExpr { } internal partial class CachedExpr : Expr { bool emitted = false; internal override void Emit(ILGenerator ilg, bool preserve) { if (emitted) { if (preserve) Local.EmitGet(ilg); } else { Expr.Emit(ilg); if (preserve) ilg.Emit(OpCodes.Dup); Local.Declare(ilg); Local.EmitSet(ilg); emitted = true; } } internal override void EmitAddr(ILGenerator ilg) { if (!emitted) { Expr.Emit(ilg); Local.Declare(ilg); Local.EmitSet(ilg); } Local.EmitAddr(ilg); } } internal partial class NativeTypeExpr : TypeExpr { } internal partial class IdExpr : NameExpr { internal override void Emit(ILGenerator ilg, bool preserve) { if (preserve) Symbol.EmitGet(ilg); } internal override void EmitSet(ILGenerator ilg, bool preserve) { if (preserve) ilg.Emit(OpCodes.Dup); Symbol.EmitSet(ilg); } internal override void EmitAddr(ILGenerator ilg) { Symbol.EmitAddr(ilg); } } internal partial class MemberAccessExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg); Symbol.EmitGet(ilg); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { if (preserve) ilg.Emit(OpCodes.Dup); Expr.Emit(ilg); Symbol.EmitSet(ilg); } } internal partial class ArrayLengthExpr : MemberAccessExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg, preserve); if (preserve) { ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); } } internal override void EmitSet(ILGenerator ilg, bool preserve) => throw new InternalError(); } internal partial class QualifiedNameExpr : NameExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Symbol.EmitGet(ilg); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { if (preserve) ilg.Emit(OpCodes.Dup); Symbol.EmitSet(ilg); } } internal partial class AssignExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Right.Emit(ilg); Left.EmitSet(ilg, preserve); } } internal partial class AssignOpExpr : AssignExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Right.Emit(ilg); Left.EmitSet(ilg, preserve); } } internal partial class BinaryExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Left.Emit(ilg); Right.Emit(ilg); Symbol.EmitGet(ilg); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class BinaryLogicExpr : BinaryExpr { internal override void Emit(ILGenerator ilg, bool preserve) { if (Symbol is BinaryOperatorSymbol) { var lb = ilg.DefineLabel(); var op = (Symbol as BinaryOperatorSymbol); Left.Emit(ilg); ilg.Emit(OpCodes.Dup); switch (op.Kind) { case BinaryOperatorKind.And: ilg.Emit(OpCodes.Brfalse, lb); break; case BinaryOperatorKind.Or: ilg.Emit(OpCodes.Brtrue, lb); break; default: throw new InternalError(); } ilg.Emit(OpCodes.Pop); Right.Emit(ilg); ilg.MarkLabel(lb); } else throw new InternalError(); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class UnaryExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg); Symbol.EmitGet(ilg); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class PrefixExpr : UnaryExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg); Left.EmitSet(ilg, preserve); } } internal partial class PostfixExpr : UnaryExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg); Left.EmitSet(ilg, false); Value.Emit(ilg, preserve); } } internal partial class LiteralExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (preserve) { ((Constant)Symbol).EmitGet(ilg); } } } internal partial class SelfExpr : Expr { // Not supported } internal partial class SuperExpr : Expr { // Not supported } internal partial class CheckedExpr : Expr { // TODO (nvk): to be implemented } internal partial class UncheckedExpr : Expr { // TODO (nvk): to be implemented } internal partial class TypeOfExpr : Expr { // TODO (nvk): to be implemented } internal partial class SizeOfExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (preserve) ilg.Emit(OpCodes.Sizeof, (Symbol as TypeSymbol).Type); } } internal partial class DefaultExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (preserve) EmitDefault(ilg, (TypeSymbol)Symbol); } } internal partial class TypeCast : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { ((ConversionSymbol)Symbol).Emit(Expr, Datatype, ilg); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class TypeConversion : TypeCast { } internal partial class IsExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg, preserve); if (preserve) { ilg.Emit(OpCodes.Isinst, (Symbol as TypeSymbol).Type); ilg.Emit(OpCodes.Ldnull); ilg.Emit(OpCodes.Cgt_Un); } } } internal partial class IsVarExpr : IsExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg, preserve); if (preserve) { Var.Declare(ilg); if (Check == null) { ilg.Emit(OpCodes.Isinst, (Symbol as TypeSymbol).Type); ilg.Emit(OpCodes.Dup); Var.EmitSet(ilg); ilg.Emit(OpCodes.Ldnull); ilg.Emit(OpCodes.Cgt_Un); } else { Var.EmitSet(ilg); if (Check == true) ilg.Emit(OpCodes.Ldc_I4_1); else ilg.Emit(OpCodes.Ldc_I4_0); } } } } internal partial class AsTypeExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg, preserve); if (preserve) { ilg.Emit(OpCodes.Isinst, Datatype.Type); } } } internal partial class MethodCallExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (Self != null) Self.Emit(ilg); Args.Emit(ilg); Symbol.EmitGet(ilg); if (WriteBack != null) WriteBack.Emit(ilg, false); if (!preserve && Datatype.NativeType != NativeType.Void) ilg.Emit(OpCodes.Pop); } } internal partial class CtorCallExpr : MethodCallExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Args.Emit(ilg); Symbol.EmitGet(ilg); if (WriteBack != null) WriteBack.Emit(ilg, false); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class IntrinsicCallExpr : MethodCallExpr { internal override void Emit(ILGenerator ilg, bool preserve) { switch (Kind) { case IntrinsicCallType.GetFParam: case IntrinsicCallType.GetMParam: Args.Emit(ilg); EmitGetElemSafe(ilg, Symbol, Datatype); break; case IntrinsicCallType.Chr: Args.Emit(ilg); Symbol.EmitGet(ilg); break; default: throw new InternalError(); } if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class ArrayAccessExpr : MethodCallExpr { internal override void Emit(ILGenerator ilg, bool preserve) { if (Self != null) Self.Emit(ilg); Args.Emit(ilg); var m = (PropertySymbol)Symbol; ilg.Emit(Self == null ? OpCodes.Call : OpCodes.Callvirt, m.Getter.Method); if (!preserve && Datatype.NativeType != NativeType.Void) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { var m = (PropertySymbol)Symbol; bool isVoid = m.Setter.Type.NativeType == NativeType.Void; if (preserve && isVoid) ilg.Emit(OpCodes.Dup); var t = ilg.DeclareLocal(Datatype.Type); ilg.Emit(OpCodes.Stloc, t.LocalIndex); if (Self != null) Self.Emit(ilg); if (m.ValueLast) { Args.Emit(ilg); ilg.Emit(OpCodes.Ldloc, t.LocalIndex); } else { ilg.Emit(OpCodes.Ldloc, t.LocalIndex); Args.Emit(ilg); } ilg.Emit(Self == null ? OpCodes.Call : OpCodes.Callvirt, m.Setter.Method); if (!preserve && !isVoid) ilg.Emit(OpCodes.Pop); } } internal partial class NativeArrayAccessExpr : ArrayAccessExpr { internal override void Emit(ILGenerator ilg, bool preserve) { if (Self != null) Self.Emit(ilg); Args.Emit(ilg); ilg.Emit(OpCodes.Ldelem, Datatype.Type); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { if (preserve) ilg.Emit(OpCodes.Dup); var t = ilg.DeclareLocal(Datatype.Type); ilg.Emit(OpCodes.Stloc, t.LocalIndex); if (Self != null) Self.Emit(ilg); Args.Emit(ilg); ilg.Emit(OpCodes.Ldloc, t.LocalIndex); ilg.Emit(OpCodes.Stelem, Datatype.Type); } } internal partial class EmptyExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (preserve) ((Constant)Symbol).EmitGet(ilg); } } internal partial class ExprList : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { for (int i = 0; i < Exprs.Count-1; i++) { Exprs[i].Emit(ilg, false); } Exprs.LastOrDefault()?.Emit(ilg, preserve); } } internal partial class LiteralArray : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { EmitConstant_I4(ilg, Values.Exprs.Count); ilg.Emit(OpCodes.Newarr, (Symbol as TypeSymbol).Type); for (int i = 0; i < Values.Exprs.Count; i++) { ilg.Emit(OpCodes.Dup); EmitConstant_I4(ilg, i); Values.Exprs[i].Emit(ilg); EmitArrayStoreElem(ilg, Symbol as TypeSymbol); } if (Datatype.NativeType == NativeType.Array) { ilg.Emit(OpCodes.Newobj, (Compilation.Get(WellKnownMembers.XSharp___Array_ctor) as ConstructorSymbol).Constructor); } if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class IifExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Cond.Emit(ilg); var lbFalse = ilg.DefineLabel(); var lbTrue = ilg.DefineLabel(); ilg.Emit(OpCodes.Brfalse, lbFalse); True.Emit(ilg); ilg.Emit(OpCodes.Br, lbTrue); ilg.MarkLabel(lbFalse); False.Emit(ilg); ilg.MarkLabel(lbTrue); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class MacroExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg); MethodSymbol m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions_Evaluate) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class MacroId { internal override void Emit(ILGenerator ilg, bool preserve) { Id.Emit(ilg); MethodSymbol m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___VarGet) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class MemvarExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Var.Emit(ilg); MethodSymbol m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___MemVarGet) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { var v = ilg.DeclareLocal(Compilation.Get(NativeType.Usual).Type); ilg.Emit(OpCodes.Stloc, v.LocalIndex); Var.Emit(ilg); ilg.Emit(OpCodes.Ldloc, v.LocalIndex); MethodSymbol m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___MemVarPut) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class AliasExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { if (Alias != null) Alias.Emit(ilg); Field.Emit(ilg); MethodSymbol m; if (Alias != null) m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___FieldGetWa) as MethodSymbol; else m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___FieldGet) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { var v = ilg.DeclareLocal(Compilation.Get(NativeType.Usual).Type); ilg.Emit(OpCodes.Stloc, v.LocalIndex); if (Alias != null) Alias.Emit(ilg); Field.Emit(ilg); ilg.Emit(OpCodes.Ldloc, v.LocalIndex); MethodSymbol m; if (Alias != null) m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___FieldSetWa) as MethodSymbol; else m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___FieldSet) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class AliasWaExpr : AliasExpr { internal override void Emit(ILGenerator ilg, bool preserve) { var push = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___pushWorkarea) as MethodSymbol; var pop = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___popWorkarea) as MethodSymbol; var dirty = ilg.DeclareLocal(Compilation.Get(NativeType.Boolean).Type); Alias.Emit(ilg); ilg.Emit(OpCodes.Call, push.Method); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Stloc, dirty.LocalIndex); Field.Emit(ilg, preserve); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Stloc, dirty.LocalIndex); ilg.Emit(OpCodes.Call, pop.Method); Stmt.FinallyClauses.Add(() => { var skip = ilg.DefineLabel(); ilg.Emit(OpCodes.Ldloc, dirty.LocalIndex); ilg.Emit(OpCodes.Brfalse_S, skip); ilg.Emit(OpCodes.Call, pop.Method); ilg.MarkLabel(skip); }); } internal override void EmitSet(ILGenerator ilg, bool preserve) { var push = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___pushWorkarea) as MethodSymbol; var pop = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___popWorkarea) as MethodSymbol; var dirty = ilg.DeclareLocal(Compilation.Get(NativeType.Boolean).Type); var v = ilg.DeclareLocal(Compilation.Get(NativeType.Usual).Type); ilg.Emit(OpCodes.Stloc, v.LocalIndex); Alias.Emit(ilg); ilg.Emit(OpCodes.Call, push.Method); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Stloc, dirty.LocalIndex); ilg.Emit(OpCodes.Ldloc, v.LocalIndex); Field.EmitSet(ilg, preserve); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Stloc, dirty.LocalIndex); ilg.Emit(OpCodes.Call, pop.Method); Stmt.FinallyClauses.Add(() => { var skip = ilg.DefineLabel(); ilg.Emit(OpCodes.Ldloc, dirty.LocalIndex); ilg.Emit(OpCodes.Brfalse_S, skip); ilg.Emit(OpCodes.Call, pop.Method); ilg.MarkLabel(skip); }); } internal void EmitFinallyBlock() { } } internal partial class RuntimeIdExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Expr.Emit(ilg, preserve); } } internal partial class SubstrExpr : BinaryExpr { internal override void Emit(ILGenerator ilg, bool preserve) { Left.Emit(ilg); Right.Emit(ilg); var m = Symbol as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class AutoVarExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { Var.Emit(ilg); var m = Compilation.Get(Safe ? WellKnownMembers.XSharp_RT_Functions___VarGetSafe : WellKnownMembers.XSharp_RT_Functions___VarGet) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } internal override void EmitSet(ILGenerator ilg, bool preserve) { var v = ilg.DeclareLocal(Datatype.Type); ilg.Emit(OpCodes.Stloc, v.LocalIndex); Var.Emit(ilg); ilg.Emit(OpCodes.Ldloc, v.LocalIndex); var m = Compilation.Get(WellKnownMembers.XSharp_RT_Functions___VarPut) as MethodSymbol; ilg.Emit(OpCodes.Call, m.Method); if (!preserve) ilg.Emit(OpCodes.Pop); } } internal partial class Arg : Node { internal override void Emit(ILGenerator ilg) { Expr.Emit(ilg, true); } } internal partial class ArgList : Node { internal override void Emit(ILGenerator ilg) { foreach (var a in Args) { a.Emit(ilg); } } } internal partial class Codeblock : Node { internal override void Emit(ILGenerator ilg) { if (Params != null) { foreach (var p in Params) { LocalSymbol ls = (LocalSymbol)p.Symbol; ls.Declare(ilg); var idx = Constant.Create(ls.Index); var skip = ilg.DefineLabel(); var lidx = Constant.Create(ls.Index); ParamArray.EmitGet(ilg); ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); lidx.EmitGet(ilg); ilg.Emit(OpCodes.Cgt); ilg.Emit(OpCodes.Brfalse, skip); ParamArray.EmitGet(ilg); lidx.EmitGet(ilg); if (ls.Type.IsReferenceType) ilg.Emit(OpCodes.Ldelem_Ref); else ilg.Emit(OpCodes.Ldelem,ls.Type.Type); ls.EmitSet(ilg); ilg.MarkLabel(skip); } } if (PCount != null) { PCount.Declare(ilg); ParamArray.EmitGet(ilg); ilg.Emit(OpCodes.Ldlen); ilg.Emit(OpCodes.Conv_I4); PCount.EmitSet(ilg); } Body.Emit(ilg); if (Symbol != null) Symbol.EmitGet(ilg); ilg.Emit(OpCodes.Ret); } } internal partial class CodeblockExpr : Expr { internal override void Emit(ILGenerator ilg, bool preserve) { // Emit nested codeblock var source = Token.ToString(); if (usualMacro) { var dlg = NestedBinder.Emit(Codeblock, source) as UsualMacro.MacroCodeblockDelegate; if (NestedBinder.CreatesAutoVars) CbList[CbIndex] = new UsualMacro.MacroMemVarCodeblock(dlg, NestedBinder.ParamCount, source, true); else CbList[CbIndex] = new UsualMacro.MacroCodeblock(dlg, NestedBinder.ParamCount, source, true); } else { var dlg = NestedBinder.Emit(Codeblock, source) as ObjectMacro.MacroCodeblockDelegate; ICodeblock rtc = NestedBinder.CreatesAutoVars ? new ObjectMacro.MacroMemVarCodeblock(dlg, NestedBinder.ParamCount) : new ObjectMacro.MacroCodeblock(dlg, NestedBinder.ParamCount); CbList[CbIndex] = new _Codeblock(rtc, source, true, false); } // Emit code to retrieve codeblock var lidx = Constant.Create(CbIndex); Symbol.EmitGet(ilg); lidx.EmitGet(ilg); ilg.Emit(OpCodes.Ldelem, Datatype.Type); if (!preserve) ilg.Emit(OpCodes.Pop); } } }
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.as001.as001 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = "foo"; string c = d as string; return c == "foo" ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.as002.as002 { // <Title> Simple dynamic declarations </Title> // <Description>(By Design) Spec 4.2.7: When dynamic appears in the right operand of the as operator, // the result of the expression still contains dynamic, not object // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class C { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = ""; C c = d as C; // no error return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.errorverifier.errorverifier { public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.as003.as003 { // <Title>Unary operators</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class temp { } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { temp t = new temp(); dynamic d = t as dynamic; try { d.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.default001.default001 { // <Title>Default(dynamic)</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var d = default(dynamic); if (d == null) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.is001.is001 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 3; return d is dynamic ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.is002.is002 { public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { object d = 3; return d is dynamic ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.is003.is003 { // <Title>Unary operators</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(17,18\).*CS1981</Expects> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 3; bool b = d is dynamic; if (b != true) return 1; else return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.is005.is005 { // <Title>Unary operators</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(26,18\).*CS1981</Expects> public class temp { public dynamic MyTest() { dynamic d = 3; return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new temp(); bool b = d.MyTest() is dynamic; if (b != true) return 1; else return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.statements.unaryOperators.typeof003.typeof003 { // <Title>Unary operators</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var s = Type.GetType("System.dynamic", false); if (s != null) return 1; else return 0; } } // </Code> }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents a control expression that handles multiple selections by passing control to a <see cref="SwitchCase"/>. /// </summary> [DebuggerTypeProxy(typeof(SwitchExpressionProxy))] public sealed class SwitchExpression : Expression { internal SwitchExpression(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, ReadOnlyCollection<SwitchCase> cases) { Type = type; SwitchValue = switchValue; DefaultBody = defaultBody; Comparison = comparison; Cases = cases; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. /// </summary> /// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get; } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Switch; /// <summary> /// Gets the test for the switch. /// </summary> public Expression SwitchValue { get; } /// <summary> /// Gets the collection of <see cref="SwitchCase"/> objects for the switch. /// </summary> public ReadOnlyCollection<SwitchCase> Cases { get; } /// <summary> /// Gets the test for the switch. /// </summary> public Expression DefaultBody { get; } /// <summary> /// Gets the equality comparison method, if any. /// </summary> public MethodInfo Comparison { get; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitSwitch(this); } internal bool IsLifted { get { if (SwitchValue.Type.IsNullableType()) { return (Comparison == null) || !TypeUtils.AreEquivalent(SwitchValue.Type, Comparison.GetParametersCached()[0].ParameterType.GetNonRefType()); } return false; } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="switchValue">The <see cref="SwitchValue"/> property of the result.</param> /// <param name="cases">The <see cref="Cases"/> property of the result.</param> /// <param name="defaultBody">The <see cref="DefaultBody"/> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public SwitchExpression Update(Expression switchValue, IEnumerable<SwitchCase> cases, Expression defaultBody) { if (switchValue == SwitchValue & defaultBody == DefaultBody & cases != null) { if (ExpressionUtils.SameElements(ref cases, Cases)) { return this; } } return Expression.Switch(Type, switchValue, defaultBody, Comparison, cases); } } public partial class Expression { /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, params SwitchCase[] cases) { return Switch(switchValue, null, null, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases) { return Switch(switchValue, defaultBody, null, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) { return Switch(switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="type">The result type of the switch.</param> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) { return Switch(type, switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) { return Switch(null, switchValue, defaultBody, comparison, cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="type">The result type of the switch.</param> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) { RequiresCanRead(switchValue, nameof(switchValue)); if (switchValue.Type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid(nameof(switchValue)); ReadOnlyCollection<SwitchCase> caseList = cases.ToReadOnly(); ContractUtils.RequiresNotNullItems(caseList, nameof(cases)); // Type of the result. Either provided, or it is type of the branches. Type resultType; if (type != null) resultType = type; else if (caseList.Count != 0) resultType = caseList[0].Body.Type; else if (defaultBody != null) resultType = defaultBody.Type; else resultType = typeof(void); bool customType = type != null; if (comparison != null) { ValidateMethodInfo(comparison, nameof(comparison)); ParameterInfo[] pms = comparison.GetParametersCached(); if (pms.Length != 2) { throw Error.IncorrectNumberOfMethodCallArguments(comparison, nameof(comparison)); } // Validate that the switch value's type matches the comparison method's // left hand side parameter type. ParameterInfo leftParam = pms[0]; bool liftedCall = false; if (!ParameterIsAssignable(leftParam, switchValue.Type)) { liftedCall = ParameterIsAssignable(leftParam, switchValue.Type.GetNonNullableType()); if (!liftedCall) { throw Error.SwitchValueTypeDoesNotMatchComparisonMethodParameter(switchValue.Type, leftParam.ParameterType); } } ParameterInfo rightParam = pms[1]; foreach (SwitchCase c in caseList) { ContractUtils.RequiresNotNull(c, nameof(cases)); ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases)); for (int i = 0, n = c.TestValues.Count; i < n; i++) { // When a comparison method is provided, test values can have different type but have to // be reference assignable to the right hand side parameter of the method. Type rightOperandType = c.TestValues[i].Type; if (liftedCall) { if (!rightOperandType.IsNullableType()) { throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType); } rightOperandType = rightOperandType.GetNonNullableType(); } if (!ParameterIsAssignable(rightParam, rightOperandType)) { throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType); } } } // if we have a non-boolean user-defined equals, we don't want it. if (comparison.ReturnType != typeof(bool)) { throw Error.EqualityMustReturnBoolean(comparison, nameof(comparison)); } } else if (caseList.Count != 0) { // When comparison method is not present, all the test values must have // the same type. Use the first test value's type as the baseline. Expression firstTestValue = caseList[0].TestValues[0]; foreach (SwitchCase c in caseList) { ContractUtils.RequiresNotNull(c, nameof(cases)); ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases)); // When no comparison method is provided, require all test values to have the same type. for (int i = 0, n = c.TestValues.Count; i < n; i++) { if (!TypeUtils.AreEquivalent(firstTestValue.Type, c.TestValues[i].Type)) { throw Error.AllTestValuesMustHaveSameType(nameof(cases)); } } } // Now we need to validate that switchValue.Type and testValueType // make sense in an Equal node. Fortunately, Equal throws a // reasonable error, so just call it. BinaryExpression equal = Equal(switchValue, firstTestValue, false, comparison); // Get the comparison function from equals node. comparison = equal.Method; } if (defaultBody == null) { if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied(nameof(defaultBody)); } else { ValidateSwitchCaseType(defaultBody, customType, resultType, nameof(defaultBody)); } return new SwitchExpression(resultType, switchValue, defaultBody, comparison, caseList); } /// <summary> /// If custom type is provided, all branches must be reference assignable to the result type. /// If no custom type is provided, all branches must have the same type - resultType. /// </summary> private static void ValidateSwitchCaseType(Expression @case, bool customType, Type resultType, string parameterName) { if (customType) { if (resultType != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(resultType, @case.Type)) { throw Error.ArgumentTypesMustMatch(parameterName); } } } else { if (!TypeUtils.AreEquivalent(resultType, @case.Type)) { throw Error.AllCaseBodiesMustHaveSameType(parameterName); } } } } }
/*************************************************************************** * ServiceLocator.cs * * Copyright (C) 2007 Novell, Inc. * Written by Calvin Gaisford <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using Mono.Zeroconf; namespace Giver { public delegate void ServiceHandler (object o, ServiceArgs args); public class ServiceArgs : EventArgs { private ServiceInfo serviceInfo; public ServiceInfo ServiceInfo { get { return serviceInfo; } } public ServiceArgs (ServiceInfo serviceInfo) { this.serviceInfo = serviceInfo; } } public class ServiceLocator { private System.Object locker; private ServiceBrowser browser; private Dictionary <string, ServiceInfo> services; private bool showLocals = false; public event ServiceHandler ServiceAdded; public event ServiceHandler ServiceRemoved; public bool ShowLocalServices { get { return showLocals; } set { showLocals = value; } } public int Count { get { int count; lock(locker) { count = services.Count; } return count; } } public ServiceInfo[] Services { get { List<ServiceInfo> serviceList; lock(locker) { serviceList = new List<ServiceInfo> (services.Values); } return serviceList.ToArray(); } } public ServiceLocator () { locker = new Object(); services = new Dictionary <string, ServiceInfo> (); Start(); } public void Start () { if (browser == null) { browser = new ServiceBrowser(); browser.ServiceAdded += OnServiceAdded; browser.ServiceRemoved += OnServiceRemoved; browser.Browse("_giver._tcp", "local"); } } public void Stop () { if (browser != null) { lock(locker) { services.Clear (); } browser.Dispose (); browser = null; } } private void OnServiceAdded (object o, ServiceBrowseEventArgs args) { // Mono.Zeroconf doesn't expose these flags? //if ((args.Service.Flags & LookupResultFlags.Local) > 0 && !showLocals) // return; args.Service.Resolved += OnServiceResolved; args.Service.Resolve(); //Logger.Debug("ServiceLocator:OnServiceAdded : {0}", args.Service.Name); } private void OnServiceResolved (object o, ServiceResolvedEventArgs args) { IResolvableService service = o as IResolvableService; lock(locker) { if (services.ContainsKey(service.Name)) { // TODO: When making changes (like name or photo) at runtime becomes possible // this should allow updates to this info return; // we already have it somehow } } ServiceInfo serviceInfo = new ServiceInfo (service.Name, service.HostEntry.AddressList[0], (ushort)service.Port); ITxtRecord record = service.TxtRecord; serviceInfo.UserName = record["User Name"].ValueString; serviceInfo.MachineName = record["Machine Name"].ValueString; serviceInfo.Version = record["Version"].ValueString; serviceInfo.PhotoType = record["PhotoType"].ValueString; serviceInfo.PhotoLocation = record["Photo"].ValueString; Logger.Debug("Setting default photo"); serviceInfo.Photo = Utilities.GetIcon("blankphoto", 48); lock(locker) { services[serviceInfo.Name] = serviceInfo; if(serviceInfo.PhotoType.CompareTo(Preferences.Local) == 0 || serviceInfo.PhotoType.CompareTo (Preferences.Gravatar) == 0 || serviceInfo.PhotoType.CompareTo (Preferences.Uri) == 0) { // Queue the resolution of the photo PhotoService.QueueResolve (serviceInfo); } } if (ServiceAdded != null) { Logger.Debug("About to call ServiceAdded"); ServiceAdded (this, new ServiceArgs (serviceInfo)); Logger.Debug("ServiceAdded was just called"); } else { Logger.Debug("ServiceAdded was null and not called"); } } private void OnServiceRemoved (object o, ServiceBrowseEventArgs args) { Logger.Debug("A Service was removed: {0}", args.Service.Name); lock(locker) { if(services.ContainsKey(args.Service.Name)) { ServiceInfo serviceInfo = services[args.Service.Name]; if (serviceInfo != null) services.Remove (serviceInfo.Name); if (ServiceRemoved != null) ServiceRemoved (this, new ServiceArgs (serviceInfo)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreation { public static class PrivateKeyAssociationTests { private const int PROV_RSA_FULL = 1; private const int PROV_DSS = 3; private const int PROV_DSS_DH = 13; private const int PROV_RSA_SCHANNEL = 12; private const int PROV_RSA_AES = 24; [Theory] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(PROV_RSA_FULL, KeyNumber.Signature)] [InlineData(PROV_RSA_FULL, KeyNumber.Exchange)] // No PROV_RSA_SIG, creation does not succeed with that prov type, MSDN says it is not supported. [InlineData(PROV_RSA_SCHANNEL, KeyNumber.Exchange)] [InlineData(PROV_RSA_AES, KeyNumber.Signature)] [InlineData(PROV_RSA_AES, KeyNumber.Exchange)] public static void AssociatePersistedKey_CAPI_RSA(int provType, KeyNumber keyNumber) { const string KeyName = nameof(AssociatePersistedKey_CAPI_RSA); CspParameters cspParameters = new CspParameters(provType) { KeyNumber = (int)keyNumber, KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(cspParameters)) { rsaCsp.PersistKeyInCsp = false; // Use SHA-1 because the FULL and SCHANNEL providers can't handle SHA-2. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; var generator = new RSASha1Pkcs1SignatureGenerator(rsaCsp); byte[] signature; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}-{provType}-{keyNumber}"), generator.PublicKey, hashAlgorithm); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, generator, now, now.AddDays(1), new byte[1])) using (X509Certificate2 withPrivateKey = cert.CopyWithPrivateKey(rsaCsp)) using (RSA rsa = withPrivateKey.GetRSAPrivateKey()) { signature = rsa.SignData(Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.True( rsaCsp.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm, RSASignaturePadding.Pkcs1)); } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (RSACryptoServiceProvider stillPersistedKey = new RSACryptoServiceProvider(cspParameters)) { byte[] signature2 = stillPersistedKey.SignData( Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.Equal(signature, signature2); } } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(36330)] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(PROV_RSA_FULL, KeyNumber.Signature)] [InlineData(PROV_RSA_FULL, KeyNumber.Exchange)] // No PROV_RSA_SIG, creation does not succeed with that prov type, MSDN says it is not supported. [InlineData(PROV_RSA_SCHANNEL, KeyNumber.Exchange)] [InlineData(PROV_RSA_AES, KeyNumber.Signature)] [InlineData(PROV_RSA_AES, KeyNumber.Exchange)] public static void AssociatePersistedKey_CAPIviaCNG_RSA(int provType, KeyNumber keyNumber) { const string KeyName = nameof(AssociatePersistedKey_CAPIviaCNG_RSA); CspParameters cspParameters = new CspParameters(provType) { KeyNumber = (int)keyNumber, KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(cspParameters)) { rsaCsp.PersistKeyInCsp = false; // Use SHA-1 because the FULL and SCHANNEL providers can't handle SHA-2. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; var generator = new RSASha1Pkcs1SignatureGenerator(rsaCsp); byte[] signature; CertificateRequest request = new CertificateRequest( $"CN={KeyName}-{provType}-{keyNumber}", rsaCsp, hashAlgorithm, RSASignaturePadding.Pkcs1); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, generator, now, now.AddDays(1), new byte[1])) using (X509Certificate2 withPrivateKey = cert.CopyWithPrivateKey(rsaCsp)) using (RSA rsa = withPrivateKey.GetRSAPrivateKey()) { // `rsa` will be an RSACng wrapping the CAPI key, which means it does not expose the // KeyNumber from CAPI. Assert.IsAssignableFrom<RSACng>(rsa); request = new CertificateRequest( $"CN={KeyName}-{provType}-{keyNumber}-again", rsa, hashAlgorithm, RSASignaturePadding.Pkcs1); X509Certificate2 cert2 = request.Create( request.SubjectName, generator, now, now.AddDays(1), new byte[1]); using (cert2) using (X509Certificate2 withPrivateKey2 = cert2.CopyWithPrivateKey(rsaCsp)) using (RSA rsa2 = withPrivateKey2.GetRSAPrivateKey()) { signature = rsa2.SignData( Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.True( rsaCsp.VerifyData( Array.Empty<byte>(), signature, hashAlgorithm, RSASignaturePadding.Pkcs1)); } } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (RSACryptoServiceProvider stillPersistedKey = new RSACryptoServiceProvider(cspParameters)) { byte[] signature2 = stillPersistedKey.SignData( Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.Equal(signature, signature2); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void AssociatePersistedKey_CNG_RSA() { const string KeyName = nameof(AssociatePersistedKey_CNG_RSA); CngKey cngKey = null; HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; byte[] signature; try { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.None, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey, }; cngKey = CngKey.Create(CngAlgorithm.Rsa, KeyName, creationParameters); using (RSACng rsaCng = new RSACng(cngKey)) { CertificateRequest request = new CertificateRequest( $"CN={KeyName}", rsaCng, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1))) using (RSA rsa = cert.GetRSAPrivateKey()) { signature = rsa.SignData(Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.True( rsaCng.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm, RSASignaturePadding.Pkcs1)); } } // Some certs have disposed, did they delete the key? using (CngKey stillPersistedKey = CngKey.Open(KeyName, CngProvider.MicrosoftSoftwareKeyStorageProvider)) using (RSACng rsaCng = new RSACng(stillPersistedKey)) { byte[] signature2 = rsaCng.SignData(Array.Empty<byte>(), hashAlgorithm, RSASignaturePadding.Pkcs1); Assert.Equal(signature, signature2); } } finally { cngKey?.Delete(); } } [Fact] public static void ThirdPartyProvider_RSA() { using (RSA rsaOther = new RSAOther()) { HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; CertificateRequest request = new CertificateRequest( $"CN={nameof(ThirdPartyProvider_RSA)}", rsaOther, hashAlgorithm, RSASignaturePadding.Pkcs1); byte[] signature; byte[] data = request.SubjectName.RawData; DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1))) { using (RSA rsa = cert.GetRSAPrivateKey()) { signature = rsa.SignData(data, hashAlgorithm, RSASignaturePadding.Pkcs1); } // RSAOther is exportable, so ensure PFX export succeeds byte[] pfxBytes = cert.Export(X509ContentType.Pkcs12, request.SubjectName.Name); Assert.InRange(pfxBytes.Length, 100, int.MaxValue); } Assert.True(rsaOther.VerifyData(data, signature, hashAlgorithm, RSASignaturePadding.Pkcs1)); } } [Theory] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(PROV_DSS)] [InlineData(PROV_DSS_DH)] public static void AssociatePersistedKey_CAPI_DSA(int provType) { const string KeyName = nameof(AssociatePersistedKey_CAPI_DSA); CspParameters cspParameters = new CspParameters(provType) { KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(cspParameters)) { dsaCsp.PersistKeyInCsp = false; X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaCsp); // Use SHA-1 because that's all DSACryptoServiceProvider understands. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}-{provType}"), dsaGen.PublicKey, hashAlgorithm); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaCsp)) using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey()) { byte[] signature = dsa.SignData(Array.Empty<byte>(), hashAlgorithm); Assert.True(dsaCsp.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm)); } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (var stillPersistedKey = new DSACryptoServiceProvider(cspParameters)) { stillPersistedKey.SignData(Array.Empty<byte>(), hashAlgorithm); } } } [Theory] [PlatformSpecific(TestPlatforms.Windows)] [InlineData(PROV_DSS)] [InlineData(PROV_DSS_DH)] public static void AssociatePersistedKey_CAPIviaCNG_DSA(int provType) { const string KeyName = nameof(AssociatePersistedKey_CAPIviaCNG_DSA); CspParameters cspParameters = new CspParameters(provType) { KeyContainerName = KeyName, Flags = CspProviderFlags.UseNonExportableKey, }; using (DSACryptoServiceProvider dsaCsp = new DSACryptoServiceProvider(cspParameters)) { dsaCsp.PersistKeyInCsp = false; X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaCsp); // Use SHA-1 because that's all DSACryptoServiceProvider understands. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; byte[] signature; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}-{provType}"), dsaGen.PublicKey, hashAlgorithm); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaCsp)) using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey()) { // `dsa` will be an DSACng wrapping the CAPI key Assert.IsAssignableFrom<DSACng>(dsa); request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}-{provType}-again"), dsaGen.PublicKey, hashAlgorithm); using (X509Certificate2 cert2 = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 cert2WithPrivateKey = cert2.CopyWithPrivateKey(dsa)) using (DSA dsa2 = cert2WithPrivateKey.GetDSAPrivateKey()) { signature = dsa2.SignData(Array.Empty<byte>(), hashAlgorithm); Assert.True(dsaCsp.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm)); } } // Some certs have disposed, did they delete the key? cspParameters.Flags = CspProviderFlags.UseExistingKey; using (var stillPersistedKey = new DSACryptoServiceProvider(cspParameters)) { stillPersistedKey.SignData(Array.Empty<byte>(), hashAlgorithm); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void AssociatePersistedKey_CNG_DSA() { const string KeyName = nameof(AssociatePersistedKey_CNG_DSA); CngKey cngKey = null; HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; byte[] signature; try { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.None, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey, Parameters = { new CngProperty("Length", BitConverter.GetBytes(1024), CngPropertyOptions.None), } }; cngKey = CngKey.Create(new CngAlgorithm("DSA"), KeyName, creationParameters); using (DSACng dsaCng = new DSACng(cngKey)) { X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaCng); CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}"), dsaGen.PublicKey, HashAlgorithmName.SHA256); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaCng)) using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey()) { signature = dsa.SignData(Array.Empty<byte>(), hashAlgorithm); Assert.True(dsaCng.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm)); } } // Some certs have disposed, did they delete the key? using (CngKey stillPersistedKey = CngKey.Open(KeyName, CngProvider.MicrosoftSoftwareKeyStorageProvider)) using (DSACng dsaCng = new DSACng(stillPersistedKey)) { dsaCng.SignData(Array.Empty<byte>(), hashAlgorithm); } } finally { cngKey?.Delete(); } } [Fact] public static void ThirdPartyProvider_DSA() { using (DSA dsaOther = new DSAOther()) { dsaOther.ImportParameters(TestData.GetDSA1024Params()); X509SignatureGenerator dsaGen = new DSAX509SignatureGenerator(dsaOther); // macOS DSA is limited to FIPS 186-3. HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA1; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={nameof(ThirdPartyProvider_DSA)}"), dsaGen.PublicKey, hashAlgorithm); byte[] signature; byte[] data = request.SubjectName.RawData; DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, dsaGen, now, now.AddDays(1), new byte[1])) using (X509Certificate2 certWithPrivateKey = cert.CopyWithPrivateKey(dsaOther)) { using (DSA dsa = certWithPrivateKey.GetDSAPrivateKey()) { signature = dsa.SignData(data, hashAlgorithm); } // DSAOther is exportable, so ensure PFX export succeeds byte[] pfxBytes = certWithPrivateKey.Export(X509ContentType.Pkcs12, request.SubjectName.Name); Assert.InRange(pfxBytes.Length, 100, int.MaxValue); } Assert.True(dsaOther.VerifyData(data, signature, hashAlgorithm)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void AssociatePersistedKey_CNG_ECDsa() { const string KeyName = nameof(AssociatePersistedKey_CNG_ECDsa); CngKey cngKey = null; HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; byte[] signature; try { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.None, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey, }; cngKey = CngKey.Create(CngAlgorithm.ECDsaP384, KeyName, creationParameters); using (ECDsaCng ecdsaCng = new ECDsaCng(cngKey)) { CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={KeyName}"), ecdsaCng, HashAlgorithmName.SHA256); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1))) using (ECDsa ecdsa = cert.GetECDsaPrivateKey()) { signature = ecdsa.SignData(Array.Empty<byte>(), hashAlgorithm); Assert.True(ecdsaCng.VerifyData(Array.Empty<byte>(), signature, hashAlgorithm)); } } // Some certs have disposed, did they delete the key? using (CngKey stillPersistedKey = CngKey.Open(KeyName, CngProvider.MicrosoftSoftwareKeyStorageProvider)) using (ECDsaCng ecdsaCng = new ECDsaCng(stillPersistedKey)) { ecdsaCng.SignData(Array.Empty<byte>(), hashAlgorithm); } } finally { cngKey?.Delete(); } } [Fact] public static void ThirdPartyProvider_ECDsa() { using (ECDsaOther ecdsaOther = new ECDsaOther()) { HashAlgorithmName hashAlgorithm = HashAlgorithmName.SHA256; CertificateRequest request = new CertificateRequest( new X500DistinguishedName($"CN={nameof(ThirdPartyProvider_ECDsa)}"), ecdsaOther, hashAlgorithm); byte[] signature; byte[] data = request.SubjectName.RawData; DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1))) { using (ECDsa ecdsa = cert.GetECDsaPrivateKey()) { signature = ecdsa.SignData(data, hashAlgorithm); } // ECDsaOther is exportable, so ensure PFX export succeeds byte[] pfxBytes = cert.Export(X509ContentType.Pkcs12, request.SubjectName.Name); Assert.InRange(pfxBytes.Length, 100, int.MaxValue); } Assert.True(ecdsaOther.VerifyData(data, signature, hashAlgorithm)); } } private sealed class RSASha1Pkcs1SignatureGenerator : X509SignatureGenerator { private readonly X509SignatureGenerator _realRsaGenerator; internal RSASha1Pkcs1SignatureGenerator(RSA rsa) { _realRsaGenerator = X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1); } protected override PublicKey BuildPublicKey() => _realRsaGenerator.PublicKey; public override byte[] GetSignatureAlgorithmIdentifier(HashAlgorithmName hashAlgorithm) { if (hashAlgorithm == HashAlgorithmName.SHA1) return "300D06092A864886F70D0101050500".HexToByteArray(); throw new InvalidOperationException(); } public override byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) => _realRsaGenerator.SignData(data, hashAlgorithm); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Roslyn.Utilities; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal abstract partial class AbstractCodeModelService : ICodeModelService { private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps = new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>(); protected readonly ISyntaxFactsService SyntaxFactsService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly AbstractNodeNameGenerator _nodeNameGenerator; private readonly AbstractNodeLocator _nodeLocator; private readonly AbstractCodeModelEventCollector _eventCollector; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly IFormattingRule _lineAdjustmentFormattingRule; private readonly IFormattingRule _endRegionFormattingRule; protected AbstractCodeModelService( HostLanguageServices languageServiceProvider, IEditorOptionsFactoryService editorOptionsFactoryService, IEnumerable<IRefactorNotifyService> refactorNotifyServices, IFormattingRule lineAdjustmentFormattingRule, IFormattingRule endRegionFormattingRule) { Debug.Assert(languageServiceProvider != null); Debug.Assert(editorOptionsFactoryService != null); this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>(); _editorOptionsFactoryService = editorOptionsFactoryService; _lineAdjustmentFormattingRule = lineAdjustmentFormattingRule; _endRegionFormattingRule = endRegionFormattingRule; _refactorNotifyServices = refactorNotifyServices; _nodeNameGenerator = CreateNodeNameGenerator(); _nodeLocator = CreateNodeLocator(); _eventCollector = CreateCodeModelEventCollector(); } protected string GetNewLineCharacter(SourceText text) { return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter(); } protected int GetTabSize(SourceText text) { var snapshot = text.FindCorrespondingEditorTextSnapshot(); return GetTabSize(snapshot); } protected int GetTabSize(ITextSnapshot snapshot) { if (snapshot == null) { throw new ArgumentNullException(nameof(snapshot)); } var textBuffer = snapshot.TextBuffer; return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize(); } protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter) { while (current.ContainsAnnotations) { current = nextTokenGetter(current); } return current; } protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree) { var nameOrdinalMap = new Dictionary<string, int>(); var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty; foreach (var node in GetFlattenedMemberNodes(syntaxTree)) { var name = _nodeNameGenerator.GenerateName(node); int ordinal; if (!nameOrdinalMap.TryGetValue(name, out ordinal)) { ordinal = 0; } nameOrdinalMap[name] = ++ordinal; var key = new SyntaxNodeKey(name, ordinal); nodeKeyMap = nodeKeyMap.Add(key, node); } return nodeKeyMap; } private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree) { return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap); } public SyntaxNodeKey GetNodeKey(SyntaxNode node) { var nodeKey = TryGetNodeKey(node); if (nodeKey.IsEmpty) { throw new ArgumentException(); } return nodeKey; } public SyntaxNodeKey TryGetNodeKey(SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree); SyntaxNodeKey nodeKey; if (!nodeKeyMap.TryGetKey(node, out nodeKey)) { return SyntaxNodeKey.Empty; } return nodeKey; } public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); SyntaxNode node; if (!nodeKeyMap.TryGetValue(nodeKey, out node)) { throw new ArgumentException(); } return node; } public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node) { var nodeKeyMap = GetNodeKeyMap(syntaxTree); return nodeKeyMap.TryGetValue(nodeKey, out node); } public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree) { return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true); } protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false); } public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container) { return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true); } /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); public abstract string Language { get; } public abstract string AssemblyAttributeString { get; } public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol); case SymbolKind.Field: return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol); case SymbolKind.Method: return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol); case SymbolKind.Namespace: return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol); case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)symbol; switch (namedType.TypeKind) { case TypeKind.Class: case TypeKind.Module: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType); case TypeKind.Delegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType); case TypeKind.Enum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType); case TypeKind.Interface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType); case TypeKind.Struct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType); default: throw Exceptions.ThrowEFail(); } case SymbolKind.Property: var propertySymbol = (IPropertySymbol)symbol; return propertySymbol.IsWithEvents ? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol) : (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol); default: throw Exceptions.ThrowEFail(); } } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> public abstract EnvDTE.CodeElement CreateInternalCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Pointer || typeSymbol.TypeKind == TypeKind.TypeParameter || typeSymbol.TypeKind == TypeKind.Submission) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Error || typeSymbol.TypeKind == TypeKind.Unknown) { return ExternalCodeUnknown.Create(state, projectId, typeSymbol); } var project = state.Workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } if (typeSymbol.TypeKind == TypeKind.Dynamic) { var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object); return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj); } EnvDTE.CodeElement element; if (TryGetElementFromSource(state, project, typeSymbol, out element)) { return element; } EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol); switch (elementKind) { case EnvDTE.vsCMElement.vsCMElementClass: case EnvDTE.vsCMElement.vsCMElementModule: return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementInterface: return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementDelegate: return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementEnum: return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol); case EnvDTE.vsCMElement.vsCMElementStruct: return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol); default: Debug.Fail("Unsupported element kind: " + elementKind); throw Exceptions.ThrowEInvalidArg(); } } public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); public abstract bool IsParameterNode(SyntaxNode node); public abstract bool IsAttributeNode(SyntaxNode node); public abstract bool IsAttributeArgumentNode(SyntaxNode node); public abstract bool IsOptionNode(SyntaxNode node); public abstract bool IsImportNode(SyntaxNode node); public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId) { var project = workspace.CurrentSolution.GetProject(projectId); if (project == null) { throw Exceptions.ThrowEFail(); } return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol; } protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); var accessorKind = GetAccessorKind(node); return CodeAccessorFunction.Create(state, parentObj, accessorKind); } protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { var parentNode = GetEffectiveParentForAttribute(node); AbstractCodeElement parentObject; if (IsParameterNode(parentNode)) { var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } else { var nodeKey = parentNode.AncestorsAndSelf() .Select(n => TryGetNodeKey(n)) .FirstOrDefault(nk => nk != SyntaxNodeKey.Empty); if (nodeKey == SyntaxNodeKey.Empty) { // This is an assembly-level attribute. parentNode = fileCodeModel.GetSyntaxRoot(); parentObject = null; } else { parentNode = fileCodeModel.LookupNode(nodeKey); var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement); } } string name; int ordinal; GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal); return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal); } protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode; string name; GetImportParentAndName(node, out parentNode, out name); AbstractCodeElement parentObj = null; if (parentNode != null) { var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent); } return CodeImport.Create(state, fileCodeModel, parentObj, name); } protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string name = GetParameterName(node); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeParameter.Create(state, parentObj, name); } protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { string name; int ordinal; GetOptionNameAndOrdinal(node.Parent, node, out name, out ordinal); return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string namespaceName; int ordinal; GetInheritsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode parentNode = node .Ancestors() .FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty); if (parentNode == null) { throw new InvalidOperationException(); } string namespaceName; int ordinal; GetImplementsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal); var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode); var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent); return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal); } protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node) { SyntaxNode attributeNode; int index; GetAttributeArgumentParentAndIndex(node, out attributeNode, out index); var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode); var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute); return CodeAttributeArgument.Create(state, codeAttributeObj, index); } public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); public abstract string GetUnescapedName(string name); public abstract string GetName(SyntaxNode node); public abstract SyntaxNode GetNodeWithName(SyntaxNode node); public abstract SyntaxNode SetName(SyntaxNode node, string name); public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel); public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); public void Rename(ISymbol symbol, string newName, Solution solution) { // TODO: (tomescht) make this testable through unit tests. // Right now we have to go through the project system to find all // the outstanding CodeElements which might be affected by the // rename. This is silly. This functionality should be moved down // into the service layer. var workspace = solution.Workspace as VisualStudioWorkspaceImpl; if (workspace == null) { throw Exceptions.ThrowEFail(); } // Save the node keys. var nodeKeyValidation = new NodeKeyValidation(); foreach (var project in workspace.ProjectTracker.ImmutableProjects) { nodeKeyValidation.AddProject(project); } // Rename symbol. var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Options).WaitAndGetResult_CodeModel(CancellationToken.None); var changedDocuments = newSolution.GetChangedDocuments(solution); // Notify third parties of the coming rename operation and let exceptions propagate out _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); // Update the workspace. if (!workspace.TryApplyChanges(newSolution)) { throw Exceptions.ThrowEFail(); } // Notify third parties of the completed rename operation and let exceptions propagate out _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); // Update the node keys. nodeKeyValidation.RestoreKeys(); } public abstract bool IsValidExternalSymbol(ISymbol symbol); public abstract string GetExternalSymbolName(ISymbol symbol); public abstract string GetExternalSymbolFullName(ISymbol symbol); public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetStartPoint(node, part); } public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part) { return _nodeLocator.GetEndPoint(node, part); } public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol); public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node); public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node); public abstract SyntaxNode GetNodeWithType(SyntaxNode node); public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node); public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node); protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol) { switch (typeSymbol.TypeKind) { case TypeKind.Array: case TypeKind.Class: return EnvDTE.vsCMElement.vsCMElementClass; case TypeKind.Interface: return EnvDTE.vsCMElement.vsCMElementInterface; case TypeKind.Struct: return EnvDTE.vsCMElement.vsCMElementStruct; case TypeKind.Enum: return EnvDTE.vsCMElement.vsCMElementEnum; case TypeKind.Delegate: return EnvDTE.vsCMElement.vsCMElementDelegate; case TypeKind.Module: return EnvDTE.vsCMElement.vsCMElementModule; default: Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind); throw Exceptions.ThrowEInvalidArg(); } } protected bool TryGetElementFromSource(CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element) { element = null; if (!typeSymbol.IsDefinition) { return false; } // Here's the strategy for determine what source file we'd try to return an element from. // 1. Prefer source files that we don't heuristically flag as generated code. // 2. If all of the source files are generated code, pick the first one. var generatedCodeRecognitionService = project.Solution.Workspace.Services.GetService<IGeneratedCodeRecognitionService>(); Compilation compilation = null; Tuple<DocumentId, Location> generatedCode = null; DocumentId chosenDocumentId = null; Location chosenLocation = null; foreach (var location in typeSymbol.Locations) { if (location.IsInSource) { compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None); if (compilation.ContainsSyntaxTree(location.SourceTree)) { var document = project.GetDocument(location.SourceTree); if (generatedCodeRecognitionService?.IsGeneratedCode(document) == false) { chosenLocation = location; chosenDocumentId = document.Id; break; } else { generatedCode = generatedCode ?? Tuple.Create(document.Id, location); } } } } if (chosenDocumentId == null && generatedCode != null) { chosenDocumentId = generatedCode.Item1; chosenLocation = generatedCode.Item2; } if (chosenDocumentId != null) { var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId); if (fileCodeModel != null) { var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel); element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol)); return element != null; } } return false; } public abstract bool IsAccessorNode(SyntaxNode node); public abstract MethodKind GetAccessorKind(SyntaxNode node); public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal); public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); public abstract string GetAttributeTarget(SyntaxNode attributeNode); public abstract string GetAttributeValue(SyntaxNode attributeNode); public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node); public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null); public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value); public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); public abstract string GetImportAlias(SyntaxNode node); public abstract string GetImportNamespaceOrType(SyntaxNode node); public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name); public abstract SyntaxNode CreateImportNode(string name, string alias = null); public abstract string GetParameterName(SyntaxNode node); public virtual string GetParameterFullName(SyntaxNode node) { return GetParameterName(node); } public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode); public abstract SyntaxNode CreateParameterNode(string name, string type); public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); public abstract bool SupportsEventThrower { get; } public abstract bool GetCanOverride(SyntaxNode memberNode); public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); public abstract string GetComment(SyntaxNode node); public abstract SyntaxNode SetComment(SyntaxNode node, string value); public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); public abstract string GetDocComment(SyntaxNode node); public abstract SyntaxNode SetDocComment(SyntaxNode node, string value); public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind); public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); public abstract bool GetIsConstant(SyntaxNode variableNode); public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value); public abstract bool GetIsDefault(SyntaxNode propertyNode); public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); public abstract bool GetIsGeneric(SyntaxNode memberNode); public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode); public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); public abstract bool GetMustImplement(SyntaxNode memberNode); public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract Document Delete(Document document, SyntaxNode node); public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); public abstract string GetInitExpression(SyntaxNode node); public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value); public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode); protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination); public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified) { // Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive" // Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8) // We therefore check for this first. if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) { return Accessibility.ProtectedOrInternal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0) { return Accessibility.Private; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0) { return Accessibility.Internal; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0) { return Accessibility.Protected; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0) { return Accessibility.Public; } else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0) { return GetDefaultAccessibility(targetSymbolKind, destination); } else { throw new ArgumentException(ServicesVSResources.Invalid_access, nameof(access)); } } public bool GetWithEvents(EnvDTE.vsCMAccess access) { return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0; } protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type) { // TODO(DustinCa): Verify this list against VB switch (type) { case EnvDTE.vsCMTypeRef.vsCMTypeRefBool: return SpecialType.System_Boolean; case EnvDTE.vsCMTypeRef.vsCMTypeRefByte: return SpecialType.System_Byte; case EnvDTE.vsCMTypeRef.vsCMTypeRefChar: return SpecialType.System_Char; case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal: return SpecialType.System_Decimal; case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble: return SpecialType.System_Double; case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat: return SpecialType.System_Single; case EnvDTE.vsCMTypeRef.vsCMTypeRefInt: return SpecialType.System_Int32; case EnvDTE.vsCMTypeRef.vsCMTypeRefLong: return SpecialType.System_Int64; case EnvDTE.vsCMTypeRef.vsCMTypeRefObject: return SpecialType.System_Object; case EnvDTE.vsCMTypeRef.vsCMTypeRefShort: return SpecialType.System_Int16; case EnvDTE.vsCMTypeRef.vsCMTypeRefString: return SpecialType.System_String; case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid: return SpecialType.System_Void; default: // TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does... throw new ArgumentException(); } } private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation) { return compilation.GetSpecialType(GetSpecialType(type)); } protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position); public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position) { if (type is EnvDTE.CodeTypeRef) { return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position); } else if (type is EnvDTE.CodeType) { return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation); } ITypeSymbol typeSymbol; if (type is EnvDTE.vsCMTypeRef || type is int) { typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation); } else if (type is string) { typeSymbol = GetTypeSymbolFromPartialName((string)type, semanticModel, position); } else { throw new InvalidOperationException(); } if (typeSymbol == null) { throw new ArgumentException(); } return typeSymbol; } public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); protected abstract int GetAttributeIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified attribute. /// </summary> public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeIndexInContainer, GetAttributeNodes); } protected abstract int GetAttributeArgumentIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetAttributeArgumentIndexInContainer, GetAttributeArgumentNodes); } protected abstract int GetImportIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetImportIndexInContainer, GetImportNodes); } protected abstract int GetParameterIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetParameterIndexInContainer, GetParameterNodes); } /// <summary> /// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true. /// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found. /// </summary> protected abstract int GetMemberIndexInContainer( SyntaxNode containerNode, Func<SyntaxNode, bool> predicate); /// <summary> /// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string /// representing the name of a member. This function translates the argument and returns the /// 1-based position of the specified member. /// </summary> public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel) { return PositionVariantToInsertionIndex( position, containerNode, fileCodeModel, GetMemberIndexInContainer, n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false)); } private int PositionVariantToInsertionIndex( object position, SyntaxNode containerNode, FileCodeModel fileCodeModel, Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer, Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes) { int result; if (position is int) { result = (int)position; } else if (position is EnvDTE.CodeElement) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position); if (codeElement == null || codeElement.FileCodeModel != fileCodeModel) { throw Exceptions.ThrowEInvalidArg(); } var positionNode = codeElement.LookupNode(); if (positionNode == null) { throw Exceptions.ThrowEFail(); } result = getIndexInContainer(containerNode, child => child == positionNode); } else if (position is string) { var name = (string)position; result = getIndexInContainer(containerNode, child => GetName(child) == name); } else if (position == null || position == Type.Missing) { result = 0; } else { // Nothing we can handle... throw Exceptions.ThrowEInvalidArg(); } // -1 means to insert at the end, so we'll return the last child. return result == -1 ? getChildNodes(containerNode).ToArray().Length : result; } protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode); protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode); protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode); protected void GetNodesAroundInsertionIndex<TSyntaxNode>( TSyntaxNode containerNode, int childIndexToInsertAfter, out TSyntaxNode insertBeforeNode, out TSyntaxNode insertAfterNode) where TSyntaxNode : SyntaxNode { var childNodes = GetLogicalMemberNodes(containerNode).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length); // Initialize the nodes that we'll insert the new member before and after. insertBeforeNode = null; insertAfterNode = null; if (childIndexToInsertAfter == 0) { if (childNodes.Length > 0) { insertBeforeNode = (TSyntaxNode)childNodes[0]; } } else { insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1]; if (childIndexToInsertAfter < childNodes.Length) { insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter]; } } if (insertBeforeNode != null) { insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode); } if (insertAfterNode != null) { insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode); } } private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex) { var childNodes = GetLogicalMemberNodes(container).ToArray(); // Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members. // If it isn't 0, it means to insert the member node *after* the node at the 1-based index. Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length); if (insertionIndex == 0) { return 0; } else { var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]); return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1; } } private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex) { return insertionIndex; } protected abstract bool IsCodeModelNode(SyntaxNode node); protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span); protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container); protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container); protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container); protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container); protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container); private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode(); var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan); var formattingRules = Formatter.GetDefaultFormattingRules(document); if (additionalRules != null) { formattingRules = additionalRules.Concat(formattingRules); } return Formatter.FormatAsync( document, new TextSpan[] { formattingSpan }, options: null, rules: formattingRules, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } private SyntaxNode InsertNode( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode node, Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer, CancellationToken cancellationToken, out Document newDocument) { var root = document.GetSyntaxRootSynchronously(cancellationToken); // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); var gen = SyntaxGenerator.GetGenerator(document); node = node.WithAdditionalAnnotations(annotation); if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport) { // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? node = node.WithAdditionalAnnotations(Simplifier.Annotation); } var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode); var newRoot = root.ReplaceNode(containerNode, newContainerNode); document = document.WithSyntaxRoot(newRoot); if (!batchMode) { document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken); } document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken); // out param newDocument = document; // new node return document .GetSyntaxRootSynchronously(cancellationToken) .GetAnnotatedNodesAndTokens(annotation) .Single() .AsNode(); } /// <summary> /// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>. /// This is used to determine whether a blank line should be added inside the body when formatting. /// </summary> protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode); public Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken) { // Annotate the member we're inserting so we can get back to it. var annotation = new SyntaxAnnotation(); // REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before? var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation); var oldRoot = document.GetSyntaxRootSynchronously(cancellationToken); var newRoot = oldRoot.ReplaceNode(node, annotatedNode); document = document.WithSyntaxRoot(newRoot); var additionalRules = AddBlankLineToMethodBody(node, newNode) ? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule) : null; document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken); return document; } public SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeInsertionIndex(containerNode, insertionIndex), containerNode, attributeNode, InsertAttributeListIntoContainer, cancellationToken, out newDocument); return GetAttributeFromAttributeDeclarationNode(finalNode); } public SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetAttributeArgumentInsertionIndex(containerNode, insertionIndex), containerNode, attributeArgumentNode, InsertAttributeArgumentIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetImportInsertionIndex(containerNode, insertionIndex), containerNode, importNode, InsertImportIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetParameterInsertionIndex(containerNode, insertionIndex), containerNode, parameterNode, InsertParameterIntoContainer, cancellationToken, out newDocument); return finalNode; } public SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode memberNode, CancellationToken cancellationToken, out Document newDocument) { var finalNode = InsertNode( document, batchMode, GetMemberInsertionIndex(containerNode, insertionIndex), containerNode, memberNode, InsertMemberNodeIntoContainer, cancellationToken, out newDocument); return GetVariableFromFieldNode(finalNode); } public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree) { return _eventCollector.Collect(oldTree, newTree); } public abstract bool IsNamespace(SyntaxNode node); public abstract bool IsType(SyntaxNode node); public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return SpecializedCollections.EmptyList<string>(); } public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel) { // descendants may override (particularly VB). return false; } public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken) { // descendants may override (particularly VB). return document; } public abstract string[] GetFunctionExtenderNames(); public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetPropertyExtenderNames(); public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); public abstract string[] GetExternalTypeExtenderNames(); public abstract object GetExternalTypeExtender(string name, string externalLocation); public abstract string[] GetTypeExtenderNames(); public abstract object GetTypeExtender(string name, AbstractCodeType codeType); public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer) { // can be override by languages if needed } public virtual void EnsureBufferFormatted(ITextBuffer buffer) { // can be override by languages if needed } } }
namespace NArrange.Tests.Core { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using NArrange.Core; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; using NArrange.CSharp; using NArrange.Tests.CSharp; using NUnit.Framework; /// <summary> /// Test fixture for the CodeArranger class. /// </summary> [TestFixture] public class CodeArrangerTests { #region Fields /// <summary> /// Set of test elements for arranging. /// </summary> private ReadOnlyCollection<ICodeElement> _testElements; #endregion Fields #region Methods /// <summary> /// Tests arrangement with nested regions. /// </summary> [Test] public void ArrangeNestedRegionTest() { List<ICodeElement> elements = new List<ICodeElement>(); TypeElement type = new TypeElement(); type.Type = TypeElementType.Class; type.Name = "TestClass"; FieldElement field = new FieldElement(); field.Name = "val"; field.Type = "int"; type.AddChild(field); elements.Add(type); // Create a configuration with a nested region CodeConfiguration codeConfiguration = new CodeConfiguration(); ElementConfiguration typeConfiguration = new ElementConfiguration(); typeConfiguration.ElementType = ElementType.Type; RegionConfiguration regionConfiguration1 = new RegionConfiguration(); regionConfiguration1.Name = "Region1"; RegionConfiguration regionConfiguration2 = new RegionConfiguration(); regionConfiguration2.Name = "Region2"; ElementConfiguration fieldConfiguration = new ElementConfiguration(); fieldConfiguration.ElementType = ElementType.Field; regionConfiguration2.Elements.Add(fieldConfiguration); regionConfiguration1.Elements.Add(regionConfiguration2); typeConfiguration.Elements.Add(regionConfiguration1); codeConfiguration.Elements.Add(typeConfiguration); CodeArranger arranger = new CodeArranger(codeConfiguration); ReadOnlyCollection<ICodeElement> arrangedElements = arranger.Arrange(elements.AsReadOnly()); Assert.AreEqual(1, arrangedElements.Count, "Unexpected number of arranged elements."); TypeElement arrangedType = arrangedElements[0] as TypeElement; Assert.IsNotNull(arrangedType, "Expected a type element after arranging."); Assert.AreEqual(1, arrangedType.Children.Count, "Unexpected number of arranged child elements."); RegionElement arrangedRegion1 = arrangedType.Children[0] as RegionElement; Assert.IsNotNull(arrangedRegion1, "Expected a region element after arranging."); Assert.AreEqual(regionConfiguration1.Name, arrangedRegion1.Name); Assert.AreEqual(1, arrangedRegion1.Children.Count, "Unexpected number of arranged child elements."); RegionElement arrangedRegion2 = arrangedRegion1.Children[0] as RegionElement; Assert.IsNotNull(arrangedRegion2, "Expected a region element after arranging."); Assert.AreEqual(regionConfiguration2.Name, arrangedRegion2.Name); Assert.AreEqual(1, arrangedRegion2.Children.Count, "Unexpected number of arranged child elements."); FieldElement arrangedFieldElement = arrangedRegion2.Children[0] as FieldElement; Assert.IsNotNull(arrangedFieldElement, "Expected a field element after arranging."); } /// <summary> /// Tests arranging static fields with and without dependencies. /// </summary> [Test] public void ArrangeStaticFieldsTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Type = TypeElementType.Class; classElement.Access = CodeAccess.Public; classElement.Name = "TestClass"; FieldElement fieldElement1 = new FieldElement(); fieldElement1.MemberModifiers = MemberModifiers.Static; fieldElement1.Access = CodeAccess.Protected; fieldElement1.Type = "object"; fieldElement1.Name = "_obj"; fieldElement1.InitialValue = "typeof(int).ToString();"; classElement.AddChild(fieldElement1); // This field has a static dependency. Normally it would be sorted first // due to its access, but we want to make sure it gets added after the // field for which it is dependent. FieldElement fieldElement2 = new FieldElement(); fieldElement2.MemberModifiers = MemberModifiers.Static; fieldElement2.Access = CodeAccess.Public; fieldElement2.Type = "bool"; fieldElement2.Name = "Initialized"; fieldElement2.InitialValue = "_initializationString != null"; classElement.AddChild(fieldElement2); FieldElement fieldElement3 = new FieldElement(); fieldElement3.MemberModifiers = MemberModifiers.Static; fieldElement3.Access = CodeAccess.Private; fieldElement3.Type = "string"; fieldElement3.Name = "_initializationString"; fieldElement3.InitialValue = "_obj"; classElement.AddChild(fieldElement3); codeElements.Add(classElement); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); TypeElement typeElement = arranged[0] as TypeElement; Assert.IsNotNull(typeElement, "Expected a type element."); List<FieldElement> staticFields = new List<FieldElement>(); Action<ICodeElement> findStaticFields = delegate(ICodeElement codeElement) { FieldElement fieldElement = codeElement as FieldElement; if (fieldElement != null && fieldElement.MemberModifiers == MemberModifiers.Static) { staticFields.Add(fieldElement); } }; ElementUtilities.ProcessElementTree(typeElement, findStaticFields); Assert.AreEqual(3, staticFields.Count, "Unexpected number of static fields after arranging."); Assert.AreEqual("_obj", staticFields[0].Name); Assert.AreEqual("_initializationString", staticFields[1].Name); Assert.AreEqual("Initialized", staticFields[2].Name); // // Remove the dependency // fieldElement2.InitialValue = "true"; fieldElement3.InitialValue = "\"test\""; arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); typeElement = arranged[0] as TypeElement; Assert.IsNotNull(typeElement, "Expected a type element."); staticFields.Clear(); ElementUtilities.ProcessElementTree(typeElement, findStaticFields); Assert.AreEqual(3, staticFields.Count, "Unexpected number of static fields after arranging."); Assert.AreEqual("Initialized", staticFields[0].Name); Assert.AreEqual("_obj", staticFields[1].Name); Assert.AreEqual("_initializationString", staticFields[2].Name); } /// <summary> /// Test the construction with a null configuration. /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void CreateWithNullTest() { CodeArranger arranger = new CodeArranger(null); } /// <summary> /// Tests arranging a condition directive. /// </summary> [Test] public void DefaultArrangeConditionDirectiveTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); ConditionDirectiveElement ifCondition = new ConditionDirectiveElement(); ifCondition.ConditionExpression = "DEBUG"; FieldElement field1 = new FieldElement(); field1.Name = "zField"; field1.Type = "int"; FieldElement field2 = new FieldElement(); field2.Name = "aField"; field2.Type = "int"; ifCondition.AddChild(field1); ifCondition.AddChild(field2); ifCondition.ElseCondition = new ConditionDirectiveElement(); FieldElement field3 = new FieldElement(); field3.Name = "testField"; field3.Type = "int"; FieldElement field1Clone = field1.Clone() as FieldElement; FieldElement field2Clone = field2.Clone() as FieldElement; TypeElement classElement = new TypeElement(); classElement.Name = "TestClass"; classElement.AddChild(field1Clone); classElement.AddChild(field2Clone); ifCondition.ElseCondition.AddChild(field3); ifCondition.ElseCondition.AddChild(classElement); codeElements.Add(ifCondition); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); ConditionDirectiveElement ifConditionTest = arranged[0] as ConditionDirectiveElement; Assert.IsNotNull(ifConditionTest, "Expected a condition directive element."); Assert.AreEqual(2, ifConditionTest.Children.Count, "After arranging, an unexpected number of nested elements were returned."); Assert.AreEqual(field2.Name, ifConditionTest.Children[0].Name); Assert.AreEqual(field1.Name, ifConditionTest.Children[1].Name); ConditionDirectiveElement elseConditionTest = ifConditionTest.ElseCondition; Assert.IsNotNull(elseConditionTest, "Expected a condition directive element."); Assert.AreEqual(2, ifConditionTest.Children.Count, "After arranging, an unexpected number of nested elements were returned."); Assert.AreEqual(field3.Name, elseConditionTest.Children[0].Name); Assert.AreEqual(classElement.Name, elseConditionTest.Children[1].Name); TypeElement classElementTest = elseConditionTest.Children[1] as TypeElement; Assert.IsNotNull(classElementTest, "Expected a type element."); Assert.AreEqual(1, classElementTest.Children.Count); Assert.AreEqual("Fields", classElementTest.Children[0].Name); } /// <summary> /// Tests arranging an enumeration. /// </summary> [Test] public void DefaultArrangeEnumerationTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement usingElement = new UsingElement(); usingElement.Name = "System"; TypeElement enumElement = new TypeElement(); enumElement.Type = TypeElementType.Enum; enumElement.Access = CodeAccess.Public; enumElement.Name = "TestEnum"; enumElement.BodyText = "Value1 = 1,\r\nValue2 = 2"; NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; namespaceElement.AddChild(usingElement); namespaceElement.AddChild(enumElement); codeElements.Add(namespaceElement); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); NamespaceElement namespaceElementTest = arranged[0] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(2, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); Assert.AreEqual(ElementType.Using, namespaceElement.Children[0].ElementType); RegionElement regionElement = namespaceElementTest.Children[1] as RegionElement; Assert.IsNotNull(regionElement, "Expected a region element."); Assert.AreEqual("Enumerations", regionElement.Name, "Unexpected region name."); Assert.AreEqual(1, regionElement.Children.Count, "After arranging, an unexpected number of region elements were returned."); TypeElement typeElement = regionElement.Children[0] as TypeElement; Assert.IsNotNull(typeElement, "Expected a type element."); Assert.AreEqual(TypeElementType.Enum, typeElement.Type, "Unexpected type element type."); Assert.AreEqual(enumElement.Name, typeElement.Name, "Unexpected type element name."); } /// <summary> /// Tests arranging a nested class. /// </summary> [Test] public void DefaultArrangeNestedClassTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement parentClassElement = new TypeElement(); parentClassElement.Type = TypeElementType.Class; parentClassElement.Access = CodeAccess.Public; parentClassElement.Name = "ParentClass"; TypeElement classElement = new TypeElement(); classElement.Type = TypeElementType.Class; classElement.Access = CodeAccess.Private; classElement.Name = "NestedClass"; parentClassElement.AddChild(classElement); NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; namespaceElement.AddChild(parentClassElement); MethodElement methodElement = new MethodElement(); methodElement.Type = "void"; methodElement.Access = CodeAccess.Public; methodElement.Name = "DoSomething"; classElement.AddChild(methodElement); FieldElement fieldElement = new FieldElement(); fieldElement.Type = "bool"; fieldElement.Access = CodeAccess.Private; fieldElement.Name = "_val"; classElement.AddChild(fieldElement); PropertyElement propertyElement = new PropertyElement(); propertyElement.Type = "bool"; propertyElement.Access = CodeAccess.Public; propertyElement.Name = "Value"; propertyElement.BodyText = "return _val"; classElement.AddChild(propertyElement); codeElements.Add(namespaceElement); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); NamespaceElement namespaceElementTest = arranged[0] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(1, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); RegionElement typeRegionElement = namespaceElementTest.Children[0] as RegionElement; Assert.IsNotNull(typeRegionElement, "Expected a region element."); Assert.AreEqual("Types", typeRegionElement.Name); Assert.AreEqual(1, typeRegionElement.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); TypeElement parentTypeElement = typeRegionElement.Children[0] as TypeElement; Assert.IsNotNull(parentTypeElement, "Expected a type element."); Assert.AreEqual(TypeElementType.Class, parentTypeElement.Type, "Unexpected type element type."); Assert.AreEqual(parentClassElement.Name, parentTypeElement.Name, "Unexpected type element name."); Assert.AreEqual(1, parentTypeElement.Children.Count, "After arranging, an unexpected number of parent class elements were returned."); RegionElement nestedTypeRegionElement = parentTypeElement.Children[0] as RegionElement; Assert.IsNotNull(nestedTypeRegionElement, "Expected a region element."); Assert.AreEqual("Nested Types", nestedTypeRegionElement.Name, "Unexpected region name."); Assert.AreEqual(1, nestedTypeRegionElement.Children.Count, "After arranging, an unexpected number of parent class region elements were returned."); TypeElement nestedTypeElement = nestedTypeRegionElement.Children[0] as TypeElement; Assert.IsNotNull(nestedTypeElement, "Expected a type element."); Assert.AreEqual(TypeElementType.Class, nestedTypeElement.Type, "Unexpected type element type."); Assert.AreEqual(classElement.Name, nestedTypeElement.Name, "Unexpected type element name."); Assert.AreEqual(3, nestedTypeElement.Children.Count, "An unexpected number of class child elements were returned."); List<RegionElement> nestedRegionElements = new List<RegionElement>(); foreach (ICodeElement classChildElement in nestedTypeElement.Children) { RegionElement nestedRegionElement = classChildElement as RegionElement; Assert.IsNotNull( nestedRegionElement, "Expected a region element but was {0}.", classChildElement.ElementType); nestedRegionElements.Add(nestedRegionElement); } Assert.AreEqual("Fields", nestedRegionElements[0].Name, "Unexpected region element name."); Assert.AreEqual("Properties", nestedRegionElements[1].Name, "Unexpected region element name."); Assert.AreEqual("Methods", nestedRegionElements[2].Name, "Unexpected region element name."); GroupElement fieldGroupElement = nestedRegionElements[0].Children[0].Children[0] as GroupElement; Assert.IsNotNull(fieldGroupElement, "Expected a group element for fields."); foreach (ICodeElement codeElement in fieldGroupElement.Children) { FieldElement fieldElementTest = codeElement as FieldElement; Assert.IsNotNull( fieldElementTest, "Expected a field element but was type {0}: {1}", codeElement.ElementType, codeElement); } Assert.AreEqual(1, nestedRegionElements[1].Children.Count); foreach (ICodeElement codeElement in nestedRegionElements[1].Children[0].Children) { PropertyElement propertyElementTest = codeElement as PropertyElement; Assert.IsNotNull( propertyElementTest, "Expected a property element but was type {0}: {1}", codeElement.ElementType, codeElement); } Assert.AreEqual(1, nestedRegionElements[2].Children.Count); foreach (ICodeElement codeElement in nestedRegionElements[2].Children[0].Children) { MethodElement methodElementTest = codeElement as MethodElement; Assert.IsNotNull( methodElementTest, "Expected a method element but was type {0}: {1}", codeElement.ElementType, codeElement); } } /// <summary> /// Tests arranging with the default configuration except moving using directivesNo. /// </summary> [Test] public void DefaultArrangeNoUsingMoveTest() { CodeConfiguration configuration = CodeConfiguration.Default.Clone() as CodeConfiguration; configuration.Formatting.Usings.MoveTo = CodeLevel.None; CodeArranger arranger = new CodeArranger(configuration); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(_testElements); // // Verify using statements were grouped and sorted correctly // Assert.AreEqual(3, arranged.Count, "An unexpected number of root elements were returned from Arrange."); RegionElement regionElement = arranged[0] as RegionElement; Assert.IsNotNull(regionElement, "Expected a region element."); Assert.AreEqual("Header", regionElement.Name); GroupElement groupElement = arranged[1] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("Namespace", groupElement.Name, "Unexpected group name."); Assert.AreEqual(1, groupElement.Children.Count, "Group contains an unexpected number of child elements."); groupElement = groupElement.Children[0] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("System", groupElement.Name, "Unexpected group name."); Assert.AreEqual(7, groupElement.Children.Count, "Group contains an unexpected number of child elements."); string lastUsingName = null; foreach (CodeElement groupedElement in groupElement.Children) { UsingElement usingElement = groupedElement as UsingElement; Assert.IsNotNull(usingElement, "Expected a using element."); string usingName = usingElement.Name; if (lastUsingName != null) { Assert.AreEqual( -1, lastUsingName.CompareTo(usingName), "Expected using statements to be sorted by name."); } } // // Verify the namespace arrangement // NamespaceElement namespaceElement = arranged[2] as NamespaceElement; Assert.IsNotNull(namespaceElement, "Expected a namespace element."); } /// <summary> /// Tests arranging a simple class. /// </summary> [Test] public void DefaultArrangeSimpleClassTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Type = TypeElementType.Class; classElement.Access = CodeAccess.Public; classElement.Name = "TestClass"; NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; namespaceElement.AddChild(classElement); MethodElement methodElement = new MethodElement(); methodElement.Type = "void"; methodElement.Access = CodeAccess.Public; methodElement.Name = "DoSomething"; classElement.AddChild(methodElement); FieldElement fieldElement = new FieldElement(); fieldElement.Type = "bool"; fieldElement.Access = CodeAccess.Private; fieldElement.Name = "_val"; classElement.AddChild(fieldElement); PropertyElement propertyElement = new PropertyElement(); propertyElement.Type = "bool"; propertyElement.Access = CodeAccess.Public; propertyElement.Name = "Value"; propertyElement.BodyText = "return _val"; classElement.AddChild(propertyElement); codeElements.Add(namespaceElement); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); NamespaceElement namespaceElementTest = arranged[0] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(1, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); RegionElement typeRegionElement = namespaceElementTest.Children[0] as RegionElement; Assert.IsNotNull(typeRegionElement, "Expected a region element."); Assert.AreEqual("Types", typeRegionElement.Name); Assert.AreEqual(1, typeRegionElement.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); TypeElement typeElement = typeRegionElement.Children[0] as TypeElement; Assert.IsNotNull(typeElement, "Expected a type element."); Assert.AreEqual(TypeElementType.Class, typeElement.Type, "Unexpected type element type."); Assert.AreEqual(classElement.Name, typeElement.Name, "Unexpected type element name."); Assert.AreEqual(3, typeElement.Children.Count, "An unexpected number of class child elements were returned."); List<RegionElement> regionElements = new List<RegionElement>(); foreach (ICodeElement classChildElement in typeElement.Children) { RegionElement regionElement = classChildElement as RegionElement; Assert.IsNotNull( regionElement, "Expected a region element but was {0}.", classChildElement.ElementType); regionElements.Add(regionElement); } Assert.AreEqual("Fields", regionElements[0].Name, "Unexpected region element name."); Assert.AreEqual("Properties", regionElements[1].Name, "Unexpected region element name."); Assert.AreEqual("Methods", regionElements[2].Name, "Unexpected region element name."); GroupElement fieldGroupElement = regionElements[0].Children[0].Children[0] as GroupElement; Assert.IsNotNull(fieldGroupElement, "Expected a group element for fields."); foreach (ICodeElement codeElement in fieldGroupElement.Children) { FieldElement fieldElementTest = codeElement as FieldElement; Assert.IsNotNull( fieldElementTest, "Expected a field element but was type {0}: {1}", codeElement.ElementType, codeElement); } Assert.AreEqual(1, regionElements[1].Children.Count); foreach (ICodeElement codeElement in regionElements[1].Children[0].Children) { PropertyElement propertyElementTest = codeElement as PropertyElement; Assert.IsNotNull( propertyElementTest, "Expected a property element but was type {0}: {1}", codeElement.ElementType, codeElement); } Assert.AreEqual(1, regionElements[2].Children.Count); foreach (ICodeElement codeElement in regionElements[2].Children[0].Children) { MethodElement methodElementTest = codeElement as MethodElement; Assert.IsNotNull( methodElementTest, "Expected a method element but was type {0}: {1}", codeElement.ElementType, codeElement); } } /// <summary> /// Tests arranging a structure with the StructLayout attribute. /// </summary> [Test] public void DefaultArrangeStructLayoutTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement structElement = new TypeElement(); structElement.Type = TypeElementType.Structure; structElement.Access = CodeAccess.Public; structElement.Name = "TestStructure"; structElement.AddAttribute(new AttributeElement("System.Runtime.InteropServices.StructLayout")); NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; namespaceElement.AddChild(structElement); FieldElement fieldElement1 = new FieldElement(); fieldElement1.Type = "int"; fieldElement1.Access = CodeAccess.Public; fieldElement1.Name = "z"; structElement.AddChild(fieldElement1); FieldElement fieldElement2 = new FieldElement(); fieldElement2.Type = "int"; fieldElement2.Access = CodeAccess.Public; fieldElement2.Name = "x"; structElement.AddChild(fieldElement2); FieldElement fieldElement3 = new FieldElement(); fieldElement3.Type = "int"; fieldElement3.Access = CodeAccess.Public; fieldElement3.Name = "y"; structElement.AddChild(fieldElement3); codeElements.Add(namespaceElement); CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); NamespaceElement namespaceElementTest = arranged[0] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(1, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); RegionElement typeRegionElement = namespaceElementTest.Children[0] as RegionElement; Assert.IsNotNull(typeRegionElement, "Expected a region element."); Assert.AreEqual("Types", typeRegionElement.Name); Assert.AreEqual(1, typeRegionElement.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); TypeElement typeElement = typeRegionElement.Children[0] as TypeElement; Assert.IsNotNull(typeElement, "Expected a type element."); Assert.AreEqual(TypeElementType.Structure, typeElement.Type, "Unexpected type element type."); Assert.AreEqual(structElement.Name, typeElement.Name, "Unexpected type element name."); Assert.AreEqual(1, typeElement.Children.Count, "An unexpected number of class child elements were returned."); RegionElement regionElement = typeElement.Children[0] as RegionElement; Assert.IsNotNull(regionElement, "Expected a region element but was {0}.", regionElement.ElementType); Assert.AreEqual("Fixed Fields", regionElement.Name, "Unexpected region name."); Assert.AreEqual(3, regionElement.Children.Count, "Unexpected number of region child elements."); // The fields should not have been sorted Assert.AreEqual(fieldElement1.Name, regionElement.Children[0].Name); Assert.AreEqual(fieldElement2.Name, regionElement.Children[1].Name); Assert.AreEqual(fieldElement3.Name, regionElement.Children[2].Name); } /// <summary> /// Tests arranging with the default configuration. /// </summary> [Test] public void DefaultArrangeTest() { CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(_testElements); // // Verify using statements were grouped and sorted correctly // Assert.AreEqual(2, arranged.Count, "An unexpected number of root elements were returned from Arrange."); RegionElement regionElement = arranged[0] as RegionElement; Assert.IsNotNull(regionElement, "Expected a region element."); Assert.AreEqual("Header", regionElement.Name); // // Verify the namespace arrangement // NamespaceElement namespaceElement = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElement, "Expected a namespace element."); Assert.IsTrue(namespaceElement.Children.Count > 0); GroupElement groupElement = namespaceElement.Children[0] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("Namespace", groupElement.Name, "Unexpected group name."); Assert.AreEqual(1, groupElement.Children.Count, "Group contains an unexpected number of child elements."); groupElement = groupElement.Children[0] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("System", groupElement.Name, "Unexpected group name."); Assert.AreEqual(8, groupElement.Children.Count, "Group contains an unexpected number of child elements."); string lastUsingName = null; foreach (CodeElement groupedElement in groupElement.Children) { UsingElement usingElement = groupedElement as UsingElement; Assert.IsNotNull(usingElement, "Expected a using element."); string usingName = usingElement.Name; if (lastUsingName != null) { Assert.AreEqual( -1, lastUsingName.CompareTo(usingName), "Expected using statements to be sorted by name."); } } } /// <summary> /// Tests arranging using statements in a region with the default configuration. /// </summary> [Test] public void DefaultArrangeUsingsInRegionTest() { CodeArranger arranger = new CodeArranger(CodeConfiguration.Default); List<ICodeElement> codeElements = new List<ICodeElement>(); RegionElement regionElement = new RegionElement(); regionElement.Name = "Using Directives"; UsingElement usingElement1 = new UsingElement(); usingElement1.Name = "System"; regionElement.AddChild(usingElement1); UsingElement usingElement2 = new UsingElement(); usingElement2.Name = "System.Text"; regionElement.AddChild(usingElement2); codeElements.Add(regionElement); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); // // Verify using statements were stripped from the region // Assert.AreEqual(1, arranged.Count, "An unexpected number of root elements were returned from Arrange."); GroupElement groupElement = arranged[0] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("Namespace", groupElement.Name); groupElement = groupElement.Children[0] as GroupElement; Assert.IsNotNull(groupElement, "Expected a group element."); Assert.AreEqual("System", groupElement.Name); foreach (ICodeElement arrangedElement in groupElement.Children) { Assert.IsTrue(arrangedElement is UsingElement, "Expected a using element."); } } /// <summary> /// Tests moving usings to the namespace level. /// </summary> [Test] public void MoveUsingsBasicTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement using1 = new UsingElement(); using1.Name = "System"; using1.IsMovable = true; UsingElement using2 = new UsingElement(); using2.Name = "System.IO"; using2.IsMovable = true; UsingElement using3 = new UsingElement(); using3.Name = "System.Collections"; using3.IsMovable = true; codeElements.Add(using1); codeElements.Add(using2); NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; namespaceElement.AddChild(using3); codeElements.Add(namespaceElement); CodeConfiguration configuration = CodeConfiguration.Default.Clone() as CodeConfiguration; CodeArranger arranger; // // Do not move. // configuration.Formatting.Usings.MoveTo = CodeLevel.None; arranger = new CodeArranger(configuration); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(2, arranged.Count, "After arranging, an unexpected number of elements were returned."); GroupElement fileGroup = arranged[0] as GroupElement; Assert.IsNotNull(fileGroup); GroupElement innerGroup = fileGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.IO", innerGroup.Children[1].Name); NamespaceElement namespaceElementTest = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(1, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); GroupElement namespaceGroup = namespaceElementTest.Children[0] as GroupElement; Assert.IsNotNull(namespaceGroup); innerGroup = namespaceGroup.Children[0] as GroupElement; Assert.AreEqual("System.Collections", innerGroup.Children[0].Name); // // Move to file level; // configuration.Formatting.Usings.MoveTo = CodeLevel.File; arranger = new CodeArranger(configuration); arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(2, arranged.Count, "After arranging, an unexpected number of elements were returned."); fileGroup = arranged[0] as GroupElement; Assert.IsNotNull(fileGroup); innerGroup = fileGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.Collections", innerGroup.Children[1].Name); Assert.AreEqual("System.IO", innerGroup.Children[2].Name); namespaceElementTest = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); // // Move to namespace. // configuration.Formatting.Usings.MoveTo = CodeLevel.Namespace; arranger = new CodeArranger(configuration); arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(1, arranged.Count, "After arranging, an unexpected number of elements were returned."); namespaceElementTest = arranged[0] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(1, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); namespaceGroup = namespaceElementTest.Children[0] as GroupElement; Assert.IsNotNull(namespaceGroup); innerGroup = namespaceGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.Collections", innerGroup.Children[1].Name); Assert.AreEqual("System.IO", innerGroup.Children[2].Name); // // Move back to file level; // configuration.Formatting.Usings.MoveTo = CodeLevel.File; arranger = new CodeArranger(configuration); arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(2, arranged.Count, "After arranging, an unexpected number of elements were returned."); fileGroup = arranged[0] as GroupElement; Assert.IsNotNull(fileGroup); innerGroup = fileGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.Collections", innerGroup.Children[1].Name); Assert.AreEqual("System.IO", innerGroup.Children[2].Name); namespaceElementTest = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); } /// <summary> /// Tests moving usings to the file level. /// </summary> [Test] public void MoveUsingsToFileTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement using1 = new UsingElement(); using1.Name = "System"; using1.IsMovable = true; codeElements.Add(using1); NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; codeElements.Add(namespaceElement); // Nested region and groups RegionElement region = new RegionElement(); region.Name = "Region"; namespaceElement.AddChild(region); GroupElement group = new GroupElement(); group.Name = "Group"; region.AddChild(group); UsingElement using2 = new UsingElement(); using2.Name = "System.IO"; using2.IsMovable = true; group.AddChild(using2); UsingElement using3 = new UsingElement(); using3.Name = "System.Collections"; using3.IsMovable = true; namespaceElement.AddChild(using3); TypeElement class1 = new TypeElement(); class1.Name = "Class1"; namespaceElement.AddChild(class1); TypeElement class2 = new TypeElement(); class2.Name = "Class2"; namespaceElement.AddChild(class2); CodeConfiguration configuration = CodeConfiguration.Default.Clone() as CodeConfiguration; CodeArranger arranger; // // Move to file. // configuration.Formatting.Usings.MoveTo = CodeLevel.File; arranger = new CodeArranger(configuration); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(2, arranged.Count, "After arranging, an unexpected number of elements were returned."); GroupElement fileGroup = arranged[0] as GroupElement; Assert.IsNotNull(fileGroup); GroupElement innerGroup = fileGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.Collections", innerGroup.Children[1].Name); Assert.AreEqual("System.IO", innerGroup.Children[2].Name); NamespaceElement namespaceElementTest = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(2, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); RegionElement typeRegion = namespaceElementTest.Children[1] as RegionElement; Assert.IsNotNull(typeRegion); Assert.AreEqual("Class1", typeRegion.Children[0].Name); Assert.AreEqual("Class2", typeRegion.Children[1].Name); } /// <summary> /// Tests moving usings to the namespace level. /// </summary> [Test] public void MoveUsingsToNamespaceTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement using1 = new UsingElement(); using1.Name = "System"; using1.IsMovable = true; codeElements.Add(using1); // Nested region and groups RegionElement region = new RegionElement(); region.Name = "Region"; codeElements.Add(region); GroupElement group = new GroupElement(); group.Name = "Group"; region.AddChild(group); UsingElement using2 = new UsingElement(); using2.Name = "System.IO"; using2.IsMovable = true; group.AddChild(using2); NamespaceElement namespaceElement = new NamespaceElement(); namespaceElement.Name = "TestNamespace"; codeElements.Add(namespaceElement); UsingElement using3 = new UsingElement(); using3.Name = "System.Collections"; using3.IsMovable = true; namespaceElement.AddChild(using3); TypeElement class1 = new TypeElement(); class1.Name = "Class1"; namespaceElement.AddChild(class1); TypeElement class2 = new TypeElement(); class2.Name = "Class2"; namespaceElement.AddChild(class2); CodeConfiguration configuration = CodeConfiguration.Default.Clone() as CodeConfiguration; CodeArranger arranger; // // Move to namespace. // configuration.Formatting.Usings.MoveTo = CodeLevel.Namespace; arranger = new CodeArranger(configuration); ReadOnlyCollection<ICodeElement> arranged = arranger.Arrange(codeElements.AsReadOnly()); Assert.AreEqual(2, arranged.Count, "After arranging, an unexpected number of elements were returned."); NamespaceElement namespaceElementTest = arranged[1] as NamespaceElement; Assert.IsNotNull(namespaceElementTest, "Expected a namespace element."); Assert.AreEqual(2, namespaceElementTest.Children.Count, "After arranging, an unexpected number of namespace elements were returned."); GroupElement namespaceGroup = namespaceElementTest.Children[0] as GroupElement; Assert.IsNotNull(namespaceGroup); GroupElement innerGroup = namespaceGroup.Children[0] as GroupElement; Assert.AreEqual("System", innerGroup.Children[0].Name); Assert.AreEqual("System.Collections", innerGroup.Children[1].Name); Assert.AreEqual("System.IO", innerGroup.Children[2].Name); RegionElement typeRegion = namespaceElementTest.Children[1] as RegionElement; Assert.IsNotNull(typeRegion); Assert.AreEqual("Class1", typeRegion.Children[0].Name); Assert.AreEqual("Class2", typeRegion.Children[1].Name); } /// <summary> /// Performs setup for this test fixture. /// </summary> [TestFixtureSetUp] public void TestFixtureSetup() { CSharpTestFile testFile = CSharpTestUtilities.GetClassMembersFile(); using (TextReader reader = testFile.GetReader()) { CSharpParser parser = new CSharpParser(); _testElements = parser.Parse(reader); Assert.IsTrue(_testElements.Count > 0, "Test file does not contain any elements."); } } #endregion Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// IEnumerable interface. /// </summary> public abstract partial class IEnumerable_Generic_Tests<T> : TestBase<T> { #region IEnumerable<T> Helper Methods /// <summary> /// Creates an instance of an IEnumerable{T} that can be used for testing. /// </summary> /// <param name="count">The number of unique items that the returned IEnumerable{T} contains.</param> /// <returns>An instance of an IEnumerable{T} that can be used for testing.</returns> protected abstract IEnumerable<T> GenericIEnumerableFactory(int count); /// <summary> /// Modifies the given IEnumerable such that any enumerators for that IEnumerable will be /// invalidated. /// </summary> /// <param name="enumerable">An IEnumerable to modify</param> /// <returns>true if the enumerable was successfully modified. Else false.</returns> protected delegate bool ModifyEnumerable(IEnumerable<T> enumerable); /// <summary> /// To be implemented in the concrete collections test classes. Returns a set of ModifyEnumerable delegates /// that modify the enumerable passed to them. /// </summary> protected abstract IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations); protected virtual ModifyOperation ModifyEnumeratorThrows => ModifyOperation.Add | ModifyOperation.Insert | ModifyOperation.Remove | ModifyOperation.Clear; protected virtual ModifyOperation ModifyEnumeratorAllowed => ModifyOperation.None; /// <summary> /// The Reset method is provided for COM interoperability. It does not necessarily need to be /// implemented; instead, the implementer can simply throw a NotSupportedException. /// /// If Reset is not implemented, this property must return False. The default value is true. /// </summary> protected virtual bool ResetImplemented => true; /// <summary> /// When calling Current of the enumerator before the first MoveNext, after the end of the collection, /// or after modification of the enumeration, the resulting behavior is undefined. Tests are included /// to cover two behavioral scenarios: /// - Throwing an InvalidOperationException /// - Returning an undefined value. /// /// If this property is set to true, the tests ensure that the exception is thrown. The default value is /// false. /// </summary> protected virtual bool Enumerator_Current_UndefinedOperation_Throws => false; /// <summary> /// When calling MoveNext or Reset after modification of the enumeration, the resulting behavior is /// undefined. Tests are included to cover two behavioral scenarios: /// - Throwing an InvalidOperationException /// - Execute MoveNext or Reset. /// /// If this property is set to true, the tests ensure that the exception is thrown. The default value is /// true. /// </summary> protected virtual bool Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException => true; /// <summary> /// Specifies whether this IEnumerable follows some sort of ordering pattern. /// </summary> protected virtual EnumerableOrder Order => EnumerableOrder.Sequential; /// <summary> /// An enum to allow specification of the order of the Enumerable. Used in validation for enumerables. /// </summary> protected enum EnumerableOrder { Unspecified, Sequential } #endregion #region Validation private void RepeatTest( Action<IEnumerator<T>, T[], int> testCode, int iters = 3) { IEnumerable<T> enumerable = GenericIEnumerableFactory(32); T[] items = enumerable.ToArray(); IEnumerator<T> enumerator = enumerable.GetEnumerator(); for (var i = 0; i < iters; i++) { testCode(enumerator, items, i); if (!ResetImplemented) { enumerator = enumerable.GetEnumerator(); } else { enumerator.Reset(); } } } private void RepeatTest( Action<IEnumerator<T>, T[]> testCode, int iters = 3) { RepeatTest((e, i, it) => testCode(e, i), iters); } private void VerifyModifiedEnumerator( IEnumerator<T> enumerator, object expectedCurrent, bool expectCurrentThrow, bool atEnd) { if (expectCurrentThrow) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } else { object current = enumerator.Current; for (var i = 0; i < 3; i++) { Assert.Equal(expectedCurrent, current); current = enumerator.Current; } } Assert.Throws<InvalidOperationException>( () => enumerator.MoveNext()); if (!!ResetImplemented) { Assert.Throws<InvalidOperationException>( () => enumerator.Reset()); } } private void VerifyEnumerator( IEnumerator<T> enumerator, T[] expectedItems) { VerifyEnumerator( enumerator, expectedItems, 0, expectedItems.Length, true, true); } private void VerifyEnumerator( IEnumerator<T> enumerator, T[] expectedItems, int startIndex, int count, bool validateStart, bool validateEnd) { bool needToMatchAllExpectedItems = count - startIndex == expectedItems.Length; if (validateStart) { for (var i = 0; i < 3; i++) { if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } else { var cur = enumerator.Current; } } } int iterations; if (Order == EnumerableOrder.Unspecified) { var itemsVisited = new BitArray( needToMatchAllExpectedItems ? count : expectedItems.Length, false); for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; var itemFound = false; for (var i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && Equals( currentItem, expectedItems[ i + (needToMatchAllExpectedItems ? startIndex : 0)])) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "itemFound"); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } if (needToMatchAllExpectedItems) { for (var i = 0; i < itemsVisited.Length; i++) { Assert.True(itemsVisited[i]); } } else { var visitedItemCount = 0; for (var i = 0; i < itemsVisited.Length; i++) { if (itemsVisited[i]) { ++visitedItemCount; } } Assert.Equal(count, visitedItemCount); } } else if (Order == EnumerableOrder.Sequential) { for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; Assert.Equal(expectedItems[iterations], currentItem); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } } else { throw new ArgumentException( "EnumerableOrder is invalid."); } Assert.Equal(count, iterations); if (validateEnd) { for (var i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext(), "enumerator.MoveNext() returned true past the expected end."); if (Enumerator_Current_UndefinedOperation_Throws) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } else { var cur = enumerator.Current; } } } } #endregion #region GetEnumerator() [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_GetEnumerator_NoExceptionsWhileGetting(int count) { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); enumerable.GetEnumerator().Dispose(); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_GetEnumerator_ReturnsUniqueEnumerator(int count) { //Tests that the enumerators returned by GetEnumerator operate independently of one another IEnumerable<T> enumerable = GenericIEnumerableFactory(count); int iterations = 0; foreach (T item in enumerable) foreach (T item2 in enumerable) foreach (T item3 in enumerable) iterations++; Assert.Equal(count * count * count, iterations); } #endregion #region Enumerator.MoveNext [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_FromStartToFinish(int count) { int iterations = 0; using (IEnumerator<T> enumerator = GenericIEnumerableFactory(count).GetEnumerator()) { while (enumerator.MoveNext()) iterations++; Assert.Equal(count, iterations); } } /// <summary> /// For most collections, all calls to MoveNext after disposal of an enumerator will return false. /// Some collections (SortedList), however, treat a call to dispose as if it were a call to Reset. Since the docs /// specify neither of these as being strictly correct, we leave the method virtual. /// </summary> [Theory] [MemberData(nameof(ValidCollectionSizes))] public virtual void Enumerator_MoveNext_AfterDisposal(int count) { IEnumerator<T> enumerator = GenericIEnumerableFactory(count).GetEnumerator(); for (int i = 0; i < count; i++) enumerator.MoveNext(); enumerator.Dispose(); Assert.False(enumerator.MoveNext()); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_AfterEndOfCollection(int count) { using (IEnumerator<T> enumerator = GenericIEnumerableFactory(count).GetEnumerator()) { for (int i = 0; i < count; i++) enumerator.MoveNext(); Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } else { enumerator.MoveNext(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedBeforeEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { enumerator.MoveNext(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } else { enumerator.MoveNext(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedDuringEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) { enumerator.MoveNext(); } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } else { enumerator.MoveNext(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_MoveNext_ModifiedAfterEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) { enumerator.MoveNext(); } } }); } [Fact] public void IEnumerable_Generic_Enumerator_MoveNextHitsAllItems() { RepeatTest( (enumerator, items) => { var iterations = 0; while (enumerator.MoveNext()) { iterations++; } Assert.Equal(items.Length, iterations); }); } [Fact] public void IEnumerable_Generic_Enumerator_MoveNextFalseAfterEndOfCollection() { RepeatTest( (enumerator, items) => { while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); }); } #endregion #region Enumerator.Current [Fact] public void IEnumerable_Generic_Enumerator_Current() { // Verify that current returns proper result. RepeatTest( (enumerator, items, iteration) => { if (iteration == 1) { VerifyEnumerator( enumerator, items, 0, items.Length / 2, true, false); } else { VerifyEnumerator(enumerator, items); } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_ReturnsSameValueOnRepeatedCalls(int count) { using (IEnumerator<T> enumerator = GenericIEnumerableFactory(count).GetEnumerator()) { while (enumerator.MoveNext()) { T current = enumerator.Current; Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); Assert.Equal(current, enumerator.Current); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_ReturnsSameObjectsOnDifferentEnumerators(int count) { // Ensures that the elements returned from enumeration are exactly the same collection of // elements returned from a previous enumeration IEnumerable<T> enumerable = GenericIEnumerableFactory(count); Dictionary<T, int> firstValues = new Dictionary<T, int>(count); Dictionary<T, int> secondValues = new Dictionary<T, int>(count); foreach (T item in enumerable) firstValues[item] = firstValues.ContainsKey(item) ? firstValues[item]++ : 1; foreach (T item in enumerable) secondValues[item] = secondValues.ContainsKey(item) ? secondValues[item]++ : 1; Assert.Equal(firstValues.Count, secondValues.Count); foreach (T key in firstValues.Keys) Assert.Equal(firstValues[key], secondValues[key]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_BeforeFirstMoveNext_UndefinedBehavior(int count) { T current; IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_AfterEndOfEnumerable_UndefinedBehavior(int count) { T current; IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) ; if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_ModifiedDuringEnumeration_UndefinedBehavior(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { T current; IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { if (Enumerator_Current_UndefinedOperation_Throws) Assert.Throws<InvalidOperationException>(() => enumerator.Current); else current = enumerator.Current; } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Current_ModifiedDuringEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { T current; IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { current = enumerator.Current; } } }); } #endregion #region Enumerator.Reset [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_BeforeIteration_Support(int count) { using (IEnumerator<T> enumerator = GenericIEnumerableFactory(count).GetEnumerator()) { if (ResetImplemented) enumerator.Reset(); else Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedBeforeEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { enumerator.Reset(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedBeforeEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { if (ModifyEnumerable(enumerable)) { enumerator.Reset(); } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedDuringEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { enumerator.Reset(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedDuringEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { for (int i = 0; i < count / 2; i++) enumerator.MoveNext(); if (ModifyEnumerable(enumerable)) { enumerator.Reset(); } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedAfterEnumeration_ThrowsInvalidOperationException(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorThrows), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) { if (Enumerator_ModifiedDuringEnumeration_ThrowsInvalidOperationException) { Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { enumerator.Reset(); } } } }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IEnumerable_Generic_Enumerator_Reset_ModifiedAfterEnumeration_Succeeds(int count) { Assert.All(GetModifyEnumerables(ModifyEnumeratorAllowed), ModifyEnumerable => { IEnumerable<T> enumerable = GenericIEnumerableFactory(count); using (IEnumerator<T> enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) ; if (ModifyEnumerable(enumerable)) { enumerator.Reset(); } } }); } [Fact] public void IEnumerable_Generic_Enumerator_Reset() { if (!ResetImplemented) { RepeatTest( (enumerator, items) => { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); }); RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length / 2, true, false); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, items.Length / 2, items.Length - (items.Length / 2), false, true); } else if (iter == 2) { VerifyEnumerator(enumerator, items); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, 0, 0, false, true); } else { VerifyEnumerator(enumerator, items); } }); } else { RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length / 2, true, false); enumerator.Reset(); enumerator.Reset(); } else if (iter == 3) { VerifyEnumerator(enumerator, items); enumerator.Reset(); enumerator.Reset(); } else { VerifyEnumerator(enumerator, items); } }, 5); } } #endregion } }
namespace android.content { [global::MonoJavaBridge.JavaClass()] public sealed partial class ContentValues : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ContentValues() { InitJNI(); } internal ContentValues(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get1251; public global::java.lang.Object get(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._get1251, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._get1251, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _put1252; public void put(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1253; public void put(java.lang.String arg0, java.lang.Byte arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1253, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1253, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1254; public void put(java.lang.String arg0, java.lang.Short arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1255; public void put(java.lang.String arg0, java.lang.Integer arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1255, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1255, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1256; public void put(java.lang.String arg0, java.lang.Long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1256, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1256, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1257; public void put(java.lang.String arg0, java.lang.Boolean arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1257, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1257, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1258; public void put(java.lang.String arg0, byte[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1258, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1258, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1259; public void put(java.lang.String arg0, java.lang.Float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1259, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1259, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _put1260; public void put(java.lang.String arg0, java.lang.Double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._put1260, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._put1260, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _equals1261; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContentValues._equals1261, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._equals1261, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString1262; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._toString1262)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._toString1262)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode1263; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentValues._hashCode1263); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._hashCode1263); } internal static global::MonoJavaBridge.MethodId _clear1264; public void clear() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._clear1264); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._clear1264); } internal static global::MonoJavaBridge.MethodId _size1265; public int size() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentValues._size1265); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._size1265); } internal static global::MonoJavaBridge.MethodId _putAll1266; public void putAll(android.content.ContentValues arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._putAll1266, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._putAll1266, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _remove1267; public void remove(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._remove1267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._remove1267, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _containsKey1268; public bool containsKey(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.ContentValues._containsKey1268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._containsKey1268, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getAsString1269; public global::java.lang.String getAsString(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsString1269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsString1269, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _putNull1270; public void putNull(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._putNull1270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._putNull1270, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _writeToParcel1271; public void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.ContentValues._writeToParcel1271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._writeToParcel1271, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents1272; public int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.ContentValues._describeContents1272); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._describeContents1272); } internal static global::MonoJavaBridge.MethodId _getAsLong1273; public global::java.lang.Long getAsLong(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsLong1273, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsLong1273, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _getAsInteger1274; public global::java.lang.Integer getAsInteger(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsInteger1274, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsInteger1274, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer; } internal static global::MonoJavaBridge.MethodId _getAsShort1275; public global::java.lang.Short getAsShort(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsShort1275, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Short; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsShort1275, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Short; } internal static global::MonoJavaBridge.MethodId _getAsByte1276; public global::java.lang.Byte getAsByte(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsByte1276, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Byte; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsByte1276, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Byte; } internal static global::MonoJavaBridge.MethodId _getAsDouble1277; public global::java.lang.Double getAsDouble(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsDouble1277, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Double; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsDouble1277, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Double; } internal static global::MonoJavaBridge.MethodId _getAsFloat1278; public global::java.lang.Float getAsFloat(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsFloat1278, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Float; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsFloat1278, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Float; } internal static global::MonoJavaBridge.MethodId _getAsBoolean1279; public global::java.lang.Boolean getAsBoolean(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsBoolean1279, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Boolean; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsBoolean1279, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Boolean; } internal static global::MonoJavaBridge.MethodId _getAsByteArray1280; public byte[] getAsByteArray(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._getAsByteArray1280, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._getAsByteArray1280, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; } internal static global::MonoJavaBridge.MethodId _valueSet1281; public global::java.util.Set valueSet() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.ContentValues._valueSet1281)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.ContentValues.staticClass, global::android.content.ContentValues._valueSet1281)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _ContentValues1282; public ContentValues() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.ContentValues.staticClass, global::android.content.ContentValues._ContentValues1282); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ContentValues1283; public ContentValues(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.ContentValues.staticClass, global::android.content.ContentValues._ContentValues1283, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ContentValues1284; public ContentValues(android.content.ContentValues arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.ContentValues.staticClass, global::android.content.ContentValues._ContentValues1284, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static global::java.lang.String TAG { get { return "ContentValues"; } } internal static global::MonoJavaBridge.FieldId _CREATOR1285; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.ContentValues.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/ContentValues")); global::android.content.ContentValues._get1251 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "get", "(Ljava/lang/String;)Ljava/lang/Object;"); global::android.content.ContentValues._put1252 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.content.ContentValues._put1253 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Byte;)V"); global::android.content.ContentValues._put1254 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Short;)V"); global::android.content.ContentValues._put1255 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Integer;)V"); global::android.content.ContentValues._put1256 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Long;)V"); global::android.content.ContentValues._put1257 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Boolean;)V"); global::android.content.ContentValues._put1258 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;[B)V"); global::android.content.ContentValues._put1259 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Float;)V"); global::android.content.ContentValues._put1260 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Double;)V"); global::android.content.ContentValues._equals1261 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.content.ContentValues._toString1262 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "toString", "()Ljava/lang/String;"); global::android.content.ContentValues._hashCode1263 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "hashCode", "()I"); global::android.content.ContentValues._clear1264 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "clear", "()V"); global::android.content.ContentValues._size1265 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "size", "()I"); global::android.content.ContentValues._putAll1266 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "putAll", "(Landroid/content/ContentValues;)V"); global::android.content.ContentValues._remove1267 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "remove", "(Ljava/lang/String;)V"); global::android.content.ContentValues._containsKey1268 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "containsKey", "(Ljava/lang/String;)Z"); global::android.content.ContentValues._getAsString1269 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsString", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.content.ContentValues._putNull1270 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "putNull", "(Ljava/lang/String;)V"); global::android.content.ContentValues._writeToParcel1271 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.content.ContentValues._describeContents1272 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "describeContents", "()I"); global::android.content.ContentValues._getAsLong1273 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsLong", "(Ljava/lang/String;)Ljava/lang/Long;"); global::android.content.ContentValues._getAsInteger1274 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsInteger", "(Ljava/lang/String;)Ljava/lang/Integer;"); global::android.content.ContentValues._getAsShort1275 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsShort", "(Ljava/lang/String;)Ljava/lang/Short;"); global::android.content.ContentValues._getAsByte1276 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsByte", "(Ljava/lang/String;)Ljava/lang/Byte;"); global::android.content.ContentValues._getAsDouble1277 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsDouble", "(Ljava/lang/String;)Ljava/lang/Double;"); global::android.content.ContentValues._getAsFloat1278 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsFloat", "(Ljava/lang/String;)Ljava/lang/Float;"); global::android.content.ContentValues._getAsBoolean1279 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsBoolean", "(Ljava/lang/String;)Ljava/lang/Boolean;"); global::android.content.ContentValues._getAsByteArray1280 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "getAsByteArray", "(Ljava/lang/String;)[B"); global::android.content.ContentValues._valueSet1281 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "valueSet", "()Ljava/util/Set;"); global::android.content.ContentValues._ContentValues1282 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "<init>", "()V"); global::android.content.ContentValues._ContentValues1283 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "<init>", "(I)V"); global::android.content.ContentValues._ContentValues1284 = @__env.GetMethodIDNoThrow(global::android.content.ContentValues.staticClass, "<init>", "(Landroid/content/ContentValues;)V"); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Serialization; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { /// <summary> /// Execution state of a Block. /// </summary> public enum ExecutionState { /// <summary> No command executing </summary> Idle, /// <summary> Executing a command </summary> Executing, } /// <summary> /// A container for a sequence of Fungus comands. /// </summary> [ExecuteInEditMode] [RequireComponent(typeof(Flowchart))] [AddComponentMenu("")] public class Block : Node { [SerializeField] protected int itemId = -1; // Invalid flowchart item id [FormerlySerializedAs("sequenceName")] [Tooltip("The name of the block node as displayed in the Flowchart window")] [SerializeField] protected string blockName = "New Block"; [TextArea(2, 5)] [Tooltip("Description text to display under the block node")] [SerializeField] protected string description = ""; [Tooltip("An optional Event Handler which can execute the block when an event occurs")] [SerializeField] protected EventHandler eventHandler; [SerializeField] protected List<Command> commandList = new List<Command>(); protected ExecutionState executionState; protected Command activeCommand; /// <summary> // Index of last command executed before the current one. // -1 indicates no previous command. /// </summary> protected int previousActiveCommandIndex = -1; protected int jumpToCommandIndex = -1; protected int executionCount; protected bool executionInfoSet = false; protected virtual void Awake() { SetExecutionInfo(); } /// <summary> /// Populate the command metadata used to control execution. /// </summary> protected virtual void SetExecutionInfo() { // Give each child command a reference back to its parent block // and tell each command its index in the list. int index = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null) { continue; } command.ParentBlock = this; command.CommandIndex = index++; } // Ensure all commands are at their correct indent level // This should have already happened in the editor, but may be necessary // if commands are added to the Block at runtime. UpdateIndentLevels(); executionInfoSet = true; } #if UNITY_EDITOR // The user can modify the command list order while playing in the editor, // so we keep the command indices updated every frame. There's no need to // do this in player builds so we compile this bit out for those builds. protected virtual void Update() { int index = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null)// Null entry will be deleted automatically later { continue; } command.CommandIndex = index++; } } #endif #region Public members /// <summary> /// The execution state of the Block. /// </summary> public virtual ExecutionState State { get { return executionState; } } /// <summary> /// Unique identifier for the Block. /// </summary> public virtual int ItemId { get { return itemId; } set { itemId = value; } } /// <summary> /// The name of the block node as displayed in the Flowchart window. /// </summary> public virtual string BlockName { get { return blockName; } set { blockName = value; } } /// <summary> /// Description text to display under the block node /// </summary> public virtual string Description { get { return description; } } /// <summary> /// An optional Event Handler which can execute the block when an event occurs. /// Note: Using the concrete class instead of the interface here because of weird editor behaviour. /// </summary> public virtual EventHandler _EventHandler { get { return eventHandler; } set { eventHandler = value; } } /// <summary> /// The currently executing command. /// </summary> public virtual Command ActiveCommand { get { return activeCommand; } } /// <summary> /// Timer for fading Block execution icon. /// </summary> public virtual float ExecutingIconTimer { get; set; } /// <summary> /// The list of commands in the sequence. /// </summary> public virtual List<Command> CommandList { get { return commandList; } } /// <summary> /// Controls the next command to execute in the block execution coroutine. /// </summary> public virtual int JumpToCommandIndex { set { jumpToCommandIndex = value; } } /// <summary> /// Returns the parent Flowchart for this Block. /// </summary> public virtual Flowchart GetFlowchart() { return GetComponent<Flowchart>(); } /// <summary> /// Returns true if the Block is executing a command. /// </summary> public virtual bool IsExecuting() { return (executionState == ExecutionState.Executing); } /// <summary> /// Returns the number of times this Block has executed. /// </summary> public virtual int GetExecutionCount() { return executionCount; } /// <summary> /// Start a coroutine which executes all commands in the Block. Only one running instance of each Block is permitted. /// </summary> public virtual void StartExecution() { StartCoroutine(Execute()); } /// <summary> /// A coroutine method that executes all commands in the Block. Only one running instance of each Block is permitted. /// </summary> /// <param name="commandIndex">Index of command to start execution at</param> /// <param name="onComplete">Delegate function to call when execution completes</param> public virtual IEnumerator Execute(int commandIndex = 0, Action onComplete = null) { if (executionState != ExecutionState.Idle) { yield break; } if (!executionInfoSet) { SetExecutionInfo(); } executionCount++; var flowchart = GetFlowchart(); executionState = ExecutionState.Executing; BlockSignals.DoBlockStart(this); #if UNITY_EDITOR // Select the executing block & the first command flowchart.SelectedBlock = this; if (commandList.Count > 0) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(commandList[0]); } #endif jumpToCommandIndex = commandIndex; int i = 0; while (true) { // Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue() if (jumpToCommandIndex > -1) { i = jumpToCommandIndex; jumpToCommandIndex = -1; } // Skip disabled commands, comments and labels while (i < commandList.Count && (!commandList[i].enabled || commandList[i].GetType() == typeof(Comment) || commandList[i].GetType() == typeof(Label))) { i = commandList[i].CommandIndex + 1; } if (i >= commandList.Count) { break; } // The previous active command is needed for if / else / else if commands if (activeCommand == null) { previousActiveCommandIndex = -1; } else { previousActiveCommandIndex = activeCommand.CommandIndex; } var command = commandList[i]; activeCommand = command; if (flowchart.IsActive()) { // Auto select a command in some situations if ((flowchart.SelectedCommands.Count == 0 && i == 0) || (flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex)) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(commandList[i]); } } command.IsExecuting = true; // This icon timer is managed by the FlowchartWindow class, but we also need to // set it here in case a command starts and finishes execution before the next window update. command.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime; BlockSignals.DoCommandExecute(this, command, i, commandList.Count); command.Execute(); // Wait until the executing command sets another command to jump to via Command.Continue() while (jumpToCommandIndex == -1) { yield return null; } #if UNITY_EDITOR if (flowchart.StepPause > 0f) { yield return new WaitForSeconds(flowchart.StepPause); } #endif command.IsExecuting = false; } executionState = ExecutionState.Idle; activeCommand = null; BlockSignals.DoBlockEnd(this); if (onComplete != null) { onComplete(); } } /// <summary> /// Stop executing commands in this Block. /// </summary> public virtual void Stop() { // Tell the executing command to stop immediately if (activeCommand != null) { activeCommand.IsExecuting = false; activeCommand.OnStopExecuting(); } // This will cause the execution loop to break on the next iteration jumpToCommandIndex = int.MaxValue; } /// <summary> /// Returns a list of all Blocks connected to this one. /// </summary> public virtual List<Block> GetConnectedBlocks() { var connectedBlocks = new List<Block>(); for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command != null) { command.GetConnectedBlocks(ref connectedBlocks); } } return connectedBlocks; } /// <summary> /// Returns the type of the previously executing command. /// </summary> /// <returns>The previous active command type.</returns> public virtual System.Type GetPreviousActiveCommandType() { if (previousActiveCommandIndex >= 0 && previousActiveCommandIndex < commandList.Count) { return commandList[previousActiveCommandIndex].GetType(); } return null; } /// <summary> /// Recalculate the indent levels for all commands in the list. /// </summary> public virtual void UpdateIndentLevels() { int indentLevel = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null) { continue; } if (command.CloseBlock()) { indentLevel--; } // Negative indent level is not permitted indentLevel = Math.Max(indentLevel, 0); command.IndentLevel = indentLevel; if (command.OpenBlock()) { indentLevel++; } } } /// <summary> /// Returns the index of the Label command with matching key, or -1 if not found. /// </summary> public virtual int GetLabelIndex(string labelKey) { if (labelKey.Length == 0) { return -1; } for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; var labelCommand = command as Label; if (labelCommand != null && String.Compare(labelCommand.Key, labelKey, true) == 0) { return i; } } return -1; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.Assemblies; namespace System.Reflection.Runtime.TypeParsing { // // Parser for type names passed to GetType() apis. // internal sealed class TypeParser { // // Parses a typename. The typename may be optionally postpended with a "," followed by a legal assembly name. // public static TypeName ParseAssemblyQualifiedTypeName(string s, bool throwOnError) { if (throwOnError) return ParseAssemblyQualifiedTypeName(s); try { return ParseAssemblyQualifiedTypeName(s); } catch (ArgumentException) { return null; } } // // Parses a typename. The typename may be optionally postpended with a "," followed by a legal assembly name. // private static TypeName ParseAssemblyQualifiedTypeName(String s) { // Desktop compat: a whitespace-only "typename" qualified by an assembly name throws an ArgumentException rather than // a TypeLoadException. int idx = 0; while (idx < s.Length && Char.IsWhiteSpace(s[idx])) { idx++; } if (idx < s.Length && s[idx] == ',') throw new ArgumentException(SR.Arg_TypeLoadNullStr); try { TypeParser parser = new TypeParser(s); NonQualifiedTypeName typeName = parser.ParseNonQualifiedTypeName(); TokenType token = parser._lexer.GetNextToken(); if (token == TokenType.End) return typeName; if (token == TokenType.Comma) { RuntimeAssemblyName assemblyName = parser._lexer.GetNextAssemblyName(); token = parser._lexer.Peek; if (token != TokenType.End) throw new ArgumentException(); return new AssemblyQualifiedTypeName(typeName, assemblyName); } throw new ArgumentException(); } catch (TypeLexer.IllegalEscapeSequenceException) { // Emulates a CLR4.5 bug that causes any string that contains an illegal escape sequence to be parsed as the empty string. return ParseAssemblyQualifiedTypeName(String.Empty); } } private TypeParser(String s) { _lexer = new TypeLexer(s); } // // Parses a type name without any assembly name qualification. // private NonQualifiedTypeName ParseNonQualifiedTypeName() { // Parse the named type or constructed generic type part first. NonQualifiedTypeName typeName = ParseNamedOrConstructedGenericTypeName(); // Iterate through any "has-element" qualifiers ([], &, *). for (;;) { TokenType token = _lexer.Peek; if (token == TokenType.End) break; if (token == TokenType.Asterisk) { _lexer.Skip(); typeName = new PointerTypeName(typeName); } else if (token == TokenType.Ampersand) { _lexer.Skip(); typeName = new ByRefTypeName(typeName); } else if (token == TokenType.OpenSqBracket) { _lexer.Skip(); token = _lexer.GetNextToken(); if (token == TokenType.Asterisk) { typeName = new MultiDimArrayTypeName(typeName, 1); token = _lexer.GetNextToken(); } else { int rank = 1; while (token == TokenType.Comma) { token = _lexer.GetNextToken(); rank++; } if (rank == 1) typeName = new ArrayTypeName(typeName); else typeName = new MultiDimArrayTypeName(typeName, rank); } if (token != TokenType.CloseSqBracket) throw new ArgumentException(); } else { break; } } return typeName; } // // Foo or Foo+Inner or Foo[String] or Foo+Inner[String] // private NonQualifiedTypeName ParseNamedOrConstructedGenericTypeName() { NamedTypeName namedType = ParseNamedTypeName(); // Because "[" is used both for generic arguments and array indexes, we must peek two characters deep. if (!(_lexer.Peek == TokenType.OpenSqBracket && (_lexer.PeekSecond == TokenType.Other || _lexer.PeekSecond == TokenType.OpenSqBracket))) return namedType; else { _lexer.Skip(); LowLevelListWithIList<TypeName> genericTypeArguments = new LowLevelListWithIList<TypeName>(); for (;;) { TypeName genericTypeArgument = ParseGenericTypeArgument(); genericTypeArguments.Add(genericTypeArgument); TokenType token = _lexer.GetNextToken(); if (token == TokenType.CloseSqBracket) break; if (token != TokenType.Comma) throw new ArgumentException(); } return new ConstructedGenericTypeName(namedType, genericTypeArguments); } } // // Foo or Foo+Inner // private NamedTypeName ParseNamedTypeName() { NamedTypeName namedType = ParseNamespaceTypeName(); while (_lexer.Peek == TokenType.Plus) { _lexer.Skip(); String nestedTypeName = _lexer.GetNextIdentifier(); namedType = new NestedTypeName(nestedTypeName, namedType); } return namedType; } // // Non-nested named type. // private NamespaceTypeName ParseNamespaceTypeName() { String fullName = _lexer.GetNextIdentifier(); return new NamespaceTypeName(fullName); } // // Parse a generic argument. In particular, generic arguments can take the special form [<typename>,<assemblyname>]. // private TypeName ParseGenericTypeArgument() { TokenType token = _lexer.GetNextToken(); if (token == TokenType.Other) { NonQualifiedTypeName nonQualifiedTypeName = ParseNonQualifiedTypeName(); return nonQualifiedTypeName; } else if (token == TokenType.OpenSqBracket) { RuntimeAssemblyName assemblyName = null; NonQualifiedTypeName typeName = ParseNonQualifiedTypeName(); token = _lexer.GetNextToken(); if (token == TokenType.Comma) { assemblyName = _lexer.GetNextEmbeddedAssemblyName(); token = _lexer.GetNextToken(); } if (token != TokenType.CloseSqBracket) throw new ArgumentException(); if (assemblyName == null) return typeName; else return new AssemblyQualifiedTypeName(typeName, assemblyName); } else throw new ArgumentException(); } private readonly TypeLexer _lexer; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Budgy.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSetTableAdapters; using EIDSS.Reports.Document.Lim.Transfer; namespace EIDSS.Reports.Document.ActiveSurveillance { partial class SessionReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SessionReport)); this.DetailReportDiagnosis = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailDiagnosis = new DevExpress.XtraReports.UI.DetailBand(); this.m_DiagnosisSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.m_FarmSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportAnimal = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailAnimal = new DevExpress.XtraReports.UI.DetailBand(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.m_SessionReportDataSet = new EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSet(); this.m_SessionAdapter = new EIDSS.Reports.Document.ActiveSurveillance.SessionReportDataSetTableAdapters.SessionTableAdapter(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.SessionIDCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionIDCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionStatusCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionStatusCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionDateCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionStartDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SeparatorCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.SessionEndDateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.CampaignIDCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.CampaignIDCell = new DevExpress.XtraReports.UI.XRTableCell(); this.CampaignNameCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.CampaignNameCell = new DevExpress.XtraReports.UI.XRTableCell(); this.CampaignTypeCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.CampaignTypeCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.SiteCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.SiteCell = new DevExpress.XtraReports.UI.XRTableCell(); this.OfficerCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.OfficerCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DateCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.DateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.RegionCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.RegionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.RayonCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.RayonCell = new DevExpress.XtraReports.UI.XRTableCell(); this.TownVillageCaptionCell = new DevExpress.XtraReports.UI.XRTableCell(); this.SpaceCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.TownVillageCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReportSummary = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailSummary = new DevExpress.XtraReports.UI.DetailBand(); this.m_SummarySubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportActions = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailActions = new DevExpress.XtraReports.UI.DetailBand(); this.m_ActionsSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportCases = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailCases = new DevExpress.XtraReports.UI.DetailBand(); this.m_CasesSubreport = new DevExpress.XtraReports.UI.XRSubreport(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionReportDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.PageHeader.Expanded = false; resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseBorders = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.xrTable2, 0); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportDiagnosis // this.DetailReportDiagnosis.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailDiagnosis}); resources.ApplyResources(this.DetailReportDiagnosis, "DetailReportDiagnosis"); this.DetailReportDiagnosis.Level = 0; this.DetailReportDiagnosis.Name = "DetailReportDiagnosis"; this.DetailReportDiagnosis.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // DetailDiagnosis // this.DetailDiagnosis.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_DiagnosisSubreport}); resources.ApplyResources(this.DetailDiagnosis, "DetailDiagnosis"); this.DetailDiagnosis.Name = "DetailDiagnosis"; this.DetailDiagnosis.StylePriority.UseBorders = false; this.DetailDiagnosis.StylePriority.UseTextAlignment = false; // // m_DiagnosisSubreport // resources.ApplyResources(this.m_DiagnosisSubreport, "m_DiagnosisSubreport"); this.m_DiagnosisSubreport.Name = "m_DiagnosisSubreport"; this.m_DiagnosisSubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionDiagnosisReport(); // // m_FarmSubreport // resources.ApplyResources(this.m_FarmSubreport, "m_FarmSubreport"); this.m_FarmSubreport.Name = "m_FarmSubreport"; this.m_FarmSubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReport(); // // DetailReportAnimal // this.DetailReportAnimal.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailAnimal}); this.DetailReportAnimal.Level = 1; this.DetailReportAnimal.Name = "DetailReportAnimal"; // // DetailAnimal // this.DetailAnimal.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_FarmSubreport}); resources.ApplyResources(this.DetailAnimal, "DetailAnimal"); this.DetailAnimal.Name = "DetailAnimal"; this.DetailAnimal.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // ReportFooter // resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; // // m_SessionReportDataSet // this.m_SessionReportDataSet.DataSetName = "SessionReportDataSet"; this.m_SessionReportDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_SessionAdapter // this.m_SessionAdapter.ClearBeforeFill = true; // // xrTable2 // resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow4, this.xrTableRow5, this.xrTableRow6, this.xrTableRow7}); this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.SessionIDCaptionCell, this.SpaceCell1, this.SessionIDCell, this.SessionStatusCaptionCell, this.SpaceCell2, this.SessionStatusCell, this.SessionDateCaptionCell, this.SpaceCell3, this.SessionStartDateCell, this.SeparatorCell1, this.SessionEndDateCell}); this.xrTableRow4.Name = "xrTableRow4"; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // SessionIDCaptionCell // this.SessionIDCaptionCell.Name = "SessionIDCaptionCell"; this.SessionIDCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SessionIDCaptionCell, "SessionIDCaptionCell"); // // SpaceCell1 // this.SpaceCell1.Name = "SpaceCell1"; resources.ApplyResources(this.SpaceCell1, "SpaceCell1"); // // SessionIDCell // this.SessionIDCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SessionIDCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strSessionID")}); this.SessionIDCell.Name = "SessionIDCell"; this.SessionIDCell.StylePriority.UseBorders = false; resources.ApplyResources(this.SessionIDCell, "SessionIDCell"); // // SessionStatusCaptionCell // this.SessionStatusCaptionCell.Name = "SessionStatusCaptionCell"; this.SessionStatusCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SessionStatusCaptionCell, "SessionStatusCaptionCell"); // // SpaceCell2 // this.SpaceCell2.Name = "SpaceCell2"; resources.ApplyResources(this.SpaceCell2, "SpaceCell2"); // // SessionStatusCell // this.SessionStatusCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SessionStatusCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strSessionStatus")}); this.SessionStatusCell.Name = "SessionStatusCell"; this.SessionStatusCell.StylePriority.UseBorders = false; resources.ApplyResources(this.SessionStatusCell, "SessionStatusCell"); // // SessionDateCaptionCell // this.SessionDateCaptionCell.Name = "SessionDateCaptionCell"; this.SessionDateCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SessionDateCaptionCell, "SessionDateCaptionCell"); // // SpaceCell3 // this.SpaceCell3.Name = "SpaceCell3"; resources.ApplyResources(this.SpaceCell3, "SpaceCell3"); // // SessionStartDateCell // this.SessionStartDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SessionStartDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.datStartDate", "{0:MM/dd/yyyy}")}); this.SessionStartDateCell.Name = "SessionStartDateCell"; this.SessionStartDateCell.StylePriority.UseBorders = false; this.SessionStartDateCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SessionStartDateCell, "SessionStartDateCell"); // // SeparatorCell1 // this.SeparatorCell1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SeparatorCell1.Name = "SeparatorCell1"; this.SeparatorCell1.StylePriority.UseBorders = false; this.SeparatorCell1.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SeparatorCell1, "SeparatorCell1"); // // SessionEndDateCell // this.SessionEndDateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SessionEndDateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.datEndDate", "{0:MM/dd/yyyy}")}); this.SessionEndDateCell.Name = "SessionEndDateCell"; this.SessionEndDateCell.StylePriority.UseBorders = false; resources.ApplyResources(this.SessionEndDateCell, "SessionEndDateCell"); // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.CampaignIDCaptionCell, this.SpaceCell4, this.CampaignIDCell, this.CampaignNameCaptionCell, this.SpaceCell5, this.CampaignNameCell, this.CampaignTypeCaptionCell, this.SpaceCell6, this.CampaignTypeCell}); this.xrTableRow5.Name = "xrTableRow5"; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // CampaignIDCaptionCell // this.CampaignIDCaptionCell.Name = "CampaignIDCaptionCell"; this.CampaignIDCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.CampaignIDCaptionCell, "CampaignIDCaptionCell"); // // SpaceCell4 // this.SpaceCell4.Name = "SpaceCell4"; resources.ApplyResources(this.SpaceCell4, "SpaceCell4"); // // CampaignIDCell // this.CampaignIDCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.CampaignIDCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strCampaignID")}); this.CampaignIDCell.Name = "CampaignIDCell"; this.CampaignIDCell.StylePriority.UseBorders = false; resources.ApplyResources(this.CampaignIDCell, "CampaignIDCell"); // // CampaignNameCaptionCell // this.CampaignNameCaptionCell.Name = "CampaignNameCaptionCell"; this.CampaignNameCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.CampaignNameCaptionCell, "CampaignNameCaptionCell"); // // SpaceCell5 // this.SpaceCell5.Name = "SpaceCell5"; resources.ApplyResources(this.SpaceCell5, "SpaceCell5"); // // CampaignNameCell // this.CampaignNameCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.CampaignNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strCampaignName")}); this.CampaignNameCell.Name = "CampaignNameCell"; this.CampaignNameCell.StylePriority.UseBorders = false; resources.ApplyResources(this.CampaignNameCell, "CampaignNameCell"); // // CampaignTypeCaptionCell // this.CampaignTypeCaptionCell.Name = "CampaignTypeCaptionCell"; this.CampaignTypeCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.CampaignTypeCaptionCell, "CampaignTypeCaptionCell"); // // SpaceCell6 // this.SpaceCell6.Name = "SpaceCell6"; resources.ApplyResources(this.SpaceCell6, "SpaceCell6"); // // CampaignTypeCell // this.CampaignTypeCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.CampaignTypeCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strCampaignType")}); this.CampaignTypeCell.Name = "CampaignTypeCell"; this.CampaignTypeCell.StylePriority.UseBorders = false; resources.ApplyResources(this.CampaignTypeCell, "CampaignTypeCell"); // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.SiteCaptionCell, this.SpaceCell7, this.SiteCell, this.OfficerCaptionCell, this.SpaceCell8, this.OfficerCell, this.DateCaptionCell, this.SpaceCell9, this.DateCell}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // SiteCaptionCell // this.SiteCaptionCell.Name = "SiteCaptionCell"; this.SiteCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.SiteCaptionCell, "SiteCaptionCell"); // // SpaceCell7 // this.SpaceCell7.Name = "SpaceCell7"; resources.ApplyResources(this.SpaceCell7, "SpaceCell7"); // // SiteCell // this.SiteCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.SiteCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strSite")}); this.SiteCell.Name = "SiteCell"; this.SiteCell.StylePriority.UseBorders = false; resources.ApplyResources(this.SiteCell, "SiteCell"); // // OfficerCaptionCell // this.OfficerCaptionCell.Name = "OfficerCaptionCell"; this.OfficerCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.OfficerCaptionCell, "OfficerCaptionCell"); // // SpaceCell8 // this.SpaceCell8.Name = "SpaceCell8"; resources.ApplyResources(this.SpaceCell8, "SpaceCell8"); // // OfficerCell // this.OfficerCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.OfficerCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strOfficer")}); this.OfficerCell.Name = "OfficerCell"; this.OfficerCell.StylePriority.UseBorders = false; resources.ApplyResources(this.OfficerCell, "OfficerCell"); // // DateCaptionCell // this.DateCaptionCell.Name = "DateCaptionCell"; this.DateCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.DateCaptionCell, "DateCaptionCell"); // // SpaceCell9 // this.SpaceCell9.Name = "SpaceCell9"; resources.ApplyResources(this.SpaceCell9, "SpaceCell9"); // // DateCell // this.DateCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.DateCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.datEnteredDate", "{0:MM/dd/yyyy}")}); this.DateCell.Name = "DateCell"; this.DateCell.StylePriority.UseBorders = false; resources.ApplyResources(this.DateCell, "DateCell"); // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.RegionCaptionCell, this.SpaceCell10, this.RegionCell, this.RayonCaptionCell, this.SpaceCell11, this.RayonCell, this.TownVillageCaptionCell, this.SpaceCell12, this.TownVillageCell}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // RegionCaptionCell // this.RegionCaptionCell.Name = "RegionCaptionCell"; this.RegionCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.RegionCaptionCell, "RegionCaptionCell"); // // SpaceCell10 // this.SpaceCell10.Name = "SpaceCell10"; resources.ApplyResources(this.SpaceCell10, "SpaceCell10"); // // RegionCell // this.RegionCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.RegionCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strRegion")}); this.RegionCell.Name = "RegionCell"; this.RegionCell.StylePriority.UseBorders = false; resources.ApplyResources(this.RegionCell, "RegionCell"); // // RayonCaptionCell // this.RayonCaptionCell.Name = "RayonCaptionCell"; this.RayonCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.RayonCaptionCell, "RayonCaptionCell"); // // SpaceCell11 // this.SpaceCell11.Name = "SpaceCell11"; resources.ApplyResources(this.SpaceCell11, "SpaceCell11"); // // RayonCell // this.RayonCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.RayonCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strRayon")}); this.RayonCell.Name = "RayonCell"; this.RayonCell.StylePriority.UseBorders = false; resources.ApplyResources(this.RayonCell, "RayonCell"); // // TownVillageCaptionCell // this.TownVillageCaptionCell.Name = "TownVillageCaptionCell"; this.TownVillageCaptionCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.TownVillageCaptionCell, "TownVillageCaptionCell"); // // SpaceCell12 // this.SpaceCell12.Name = "SpaceCell12"; resources.ApplyResources(this.SpaceCell12, "SpaceCell12"); // // TownVillageCell // this.TownVillageCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.TownVillageCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.m_SessionReportDataSet, "Session.strSettlement")}); this.TownVillageCell.Name = "TownVillageCell"; this.TownVillageCell.StylePriority.UseBorders = false; resources.ApplyResources(this.TownVillageCell, "TownVillageCell"); // // DetailReportSummary // this.DetailReportSummary.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailSummary}); this.DetailReportSummary.Level = 2; this.DetailReportSummary.Name = "DetailReportSummary"; // // DetailSummary // this.DetailSummary.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_SummarySubreport}); resources.ApplyResources(this.DetailSummary, "DetailSummary"); this.DetailSummary.Name = "DetailSummary"; this.DetailSummary.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // m_SummarySubreport // resources.ApplyResources(this.m_SummarySubreport, "m_SummarySubreport"); this.m_SummarySubreport.Name = "m_SummarySubreport"; this.m_SummarySubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionSummaryReport(); // // DetailReportActions // this.DetailReportActions.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailActions}); this.DetailReportActions.Level = 3; this.DetailReportActions.Name = "DetailReportActions"; // // DetailActions // this.DetailActions.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_ActionsSubreport}); resources.ApplyResources(this.DetailActions, "DetailActions"); this.DetailActions.Name = "DetailActions"; this.DetailActions.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // m_ActionsSubreport // resources.ApplyResources(this.m_ActionsSubreport, "m_ActionsSubreport"); this.m_ActionsSubreport.Name = "m_ActionsSubreport"; this.m_ActionsSubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionActionsReport(); // // DetailReportCases // this.DetailReportCases.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailCases}); this.DetailReportCases.Level = 4; this.DetailReportCases.Name = "DetailReportCases"; // // DetailCases // this.DetailCases.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.m_CasesSubreport}); resources.ApplyResources(this.DetailCases, "DetailCases"); this.DetailCases.Name = "DetailCases"; this.DetailCases.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // m_CasesSubreport // resources.ApplyResources(this.m_CasesSubreport, "m_CasesSubreport"); this.m_CasesSubreport.Name = "m_CasesSubreport"; this.m_CasesSubreport.ReportSource = new EIDSS.Reports.Document.ActiveSurveillance.SessionCasesReport(); // // SessionReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportDiagnosis, this.DetailReportAnimal, this.ReportFooter, this.DetailReportSummary, this.DetailReportActions, this.DetailReportCases}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "14.1"; this.Controls.SetChildIndex(this.DetailReportCases, 0); this.Controls.SetChildIndex(this.DetailReportActions, 0); this.Controls.SetChildIndex(this.DetailReportSummary, 0); this.Controls.SetChildIndex(this.ReportFooter, 0); this.Controls.SetChildIndex(this.DetailReportAnimal, 0); this.Controls.SetChildIndex(this.DetailReportDiagnosis, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionReportDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportDiagnosis; private DevExpress.XtraReports.UI.DetailBand DetailDiagnosis; private DevExpress.XtraReports.UI.DetailReportBand DetailReportAnimal; private DevExpress.XtraReports.UI.DetailBand DetailAnimal; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private SessionReportDataSet m_SessionReportDataSet; private SessionTableAdapter m_SessionAdapter; private DevExpress.XtraReports.UI.XRSubreport m_FarmSubreport; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell SessionIDCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell1; private DevExpress.XtraReports.UI.XRTableCell SessionIDCell; private DevExpress.XtraReports.UI.XRTableCell SessionStatusCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell2; private DevExpress.XtraReports.UI.XRTableCell SessionStatusCell; private DevExpress.XtraReports.UI.XRTableCell SessionDateCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell3; private DevExpress.XtraReports.UI.XRTableCell SessionEndDateCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell CampaignIDCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell4; private DevExpress.XtraReports.UI.XRTableCell CampaignIDCell; private DevExpress.XtraReports.UI.XRTableCell CampaignNameCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell5; private DevExpress.XtraReports.UI.XRTableCell CampaignNameCell; private DevExpress.XtraReports.UI.XRTableCell CampaignTypeCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell6; private DevExpress.XtraReports.UI.XRTableCell CampaignTypeCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell SiteCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell7; private DevExpress.XtraReports.UI.XRTableCell SiteCell; private DevExpress.XtraReports.UI.XRTableCell OfficerCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell8; private DevExpress.XtraReports.UI.XRTableCell OfficerCell; private DevExpress.XtraReports.UI.XRTableCell DateCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell9; private DevExpress.XtraReports.UI.XRTableCell DateCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell RegionCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell10; private DevExpress.XtraReports.UI.XRTableCell RegionCell; private DevExpress.XtraReports.UI.XRTableCell RayonCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell11; private DevExpress.XtraReports.UI.XRTableCell RayonCell; private DevExpress.XtraReports.UI.XRTableCell TownVillageCaptionCell; private DevExpress.XtraReports.UI.XRTableCell SpaceCell12; private DevExpress.XtraReports.UI.XRTableCell TownVillageCell; private DevExpress.XtraReports.UI.XRSubreport m_DiagnosisSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportSummary; private DevExpress.XtraReports.UI.DetailBand DetailSummary; private DevExpress.XtraReports.UI.XRSubreport m_SummarySubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportActions; private DevExpress.XtraReports.UI.DetailBand DetailActions; private DevExpress.XtraReports.UI.XRSubreport m_ActionsSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportCases; private DevExpress.XtraReports.UI.DetailBand DetailCases; private DevExpress.XtraReports.UI.XRSubreport m_CasesSubreport; private DevExpress.XtraReports.UI.XRTableCell SessionStartDateCell; private DevExpress.XtraReports.UI.XRTableCell SeparatorCell1; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using Python.Runtime; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Framework.Execution; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Orders; using QuantConnect.Securities; using QuantConnect.Tests.Engine.DataFeeds; namespace QuantConnect.Tests.Algorithm.Framework.Execution { [TestFixture] public class SpreadExecutionModelTests { [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void OrdersAreNotSubmittedWhenNoTargetsToExecute(Language language) { var actualOrdersSubmitted = new List<SubmitOrderRequest>(); var orderProcessor = new Mock<IOrderProcessor>(); orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>())) .Returns((OrderTicket)null) .Callback((SubmitOrderRequest request) => actualOrdersSubmitted.Add(request)); var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.Transactions.SetOrderProcessor(orderProcessor.Object); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = new SecurityChanges(Enumerable.Empty<Security>(), Enumerable.Empty<Security>()); model.OnSecuritiesChanged(algorithm, changes); model.Execute(algorithm, new IPortfolioTarget[0]); Assert.AreEqual(0, actualOrdersSubmitted.Count); } [TestCase(Language.CSharp, 240, 1, 10)] [TestCase(Language.CSharp, 250, 0, 0)] [TestCase(Language.Python, 240, 1, 10)] [TestCase(Language.Python, 250, 0, 0)] public void OrdersAreSubmittedWhenRequiredForTargetsToExecute( Language language, decimal currentPrice, int expectedOrdersSubmitted, decimal expectedTotalQuantity) { var actualOrdersSubmitted = new List<SubmitOrderRequest>(); var time = new DateTime(2018, 8, 2, 14, 0, 0); var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.SetDateTime(time.AddMinutes(5)); var security = algorithm.AddEquity(Symbols.AAPL.Value); security.SetMarketPrice(new TradeBar { Value = 250 }); // pushing the ask higher will cause the spread the widen and no trade to happen var ask = expectedOrdersSubmitted == 0 ? currentPrice * 1.1m : currentPrice; security.SetMarketPrice(new QuoteBar { Time = time, Symbol = Symbols.AAPL, Ask = new Bar(ask, ask, ask, ask), Bid = new Bar(currentPrice, currentPrice, currentPrice, currentPrice) }); algorithm.SetFinishedWarmingUp(); var orderProcessor = new Mock<IOrderProcessor>(); orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>())) .Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request)) .Callback((SubmitOrderRequest request) => actualOrdersSubmitted.Add(request)); orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny<Func<Order, bool>>())) .Returns(new List<Order>()); algorithm.Transactions.SetOrderProcessor(orderProcessor.Object); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = new SecurityChanges(new[] { security }, Enumerable.Empty<Security>()); model.OnSecuritiesChanged(algorithm, changes); var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) }; model.Execute(algorithm, targets); Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count); Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity)); if (actualOrdersSubmitted.Count == 1) { var request = actualOrdersSubmitted[0]; Assert.AreEqual(expectedTotalQuantity, request.Quantity); Assert.AreEqual(algorithm.UtcTime, request.Time); } } [TestCase(Language.CSharp, 1, 10, true)] [TestCase(Language.Python, 1, 10, true)] [TestCase(Language.CSharp, 0, 0, false)] [TestCase(Language.Python, 0, 0, false)] public void FillsOnTradesOnlyRespectingExchangeOpen(Language language, int expectedOrdersSubmitted, decimal expectedTotalQuantity, bool exchangeOpen) { var actualOrdersSubmitted = new List<SubmitOrderRequest>(); var time = new DateTime(2018, 8, 2, 0, 0, 0); if (exchangeOpen) { time = time.AddHours(14); } var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.SetDateTime(time.AddMinutes(5)); var security = algorithm.AddEquity(Symbols.AAPL.Value); security.SetMarketPrice(new TradeBar { Value = 250 }); algorithm.SetFinishedWarmingUp(); var orderProcessor = new Mock<IOrderProcessor>(); orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>())) .Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request)) .Callback((SubmitOrderRequest request) => actualOrdersSubmitted.Add(request)); orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny<Func<Order, bool>>())) .Returns(new List<Order>()); algorithm.Transactions.SetOrderProcessor(orderProcessor.Object); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = new SecurityChanges(new[] { security }, Enumerable.Empty<Security>()); model.OnSecuritiesChanged(algorithm, changes); var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) }; model.Execute(algorithm, targets); Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count); Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity)); if (actualOrdersSubmitted.Count == 1) { var request = actualOrdersSubmitted[0]; Assert.AreEqual(expectedTotalQuantity, request.Quantity); Assert.AreEqual(algorithm.UtcTime, request.Time); } } [TestCase(Language.CSharp, MarketDataType.TradeBar)] [TestCase(Language.Python, MarketDataType.TradeBar)] [TestCase(Language.CSharp, MarketDataType.QuoteBar)] [TestCase(Language.Python, MarketDataType.QuoteBar)] public void OnSecuritiesChangeDoesNotThrow( Language language, MarketDataType marketDataType) { var time = new DateTime(2018, 8, 2, 16, 0, 0); Func<double, int, BaseData> func = (x, i) => { var price = Convert.ToDecimal(x); switch (marketDataType) { case MarketDataType.TradeBar: return new TradeBar(time.AddMinutes(i), Symbols.AAPL, price, price, price, price, 100m); case MarketDataType.QuoteBar: var bar = new Bar(price, price, price, price); return new QuoteBar(time.AddMinutes(i), Symbols.AAPL, bar, 10m, bar, 10m); default: throw new ArgumentException($"Invalid MarketDataType: {marketDataType}"); } }; var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.SetDateTime(time.AddMinutes(5)); var security = algorithm.AddEquity(Symbols.AAPL.Value); security.SetMarketPrice(new TradeBar { Value = 250 }); algorithm.SetFinishedWarmingUp(); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = new SecurityChanges(new[] { security }, Enumerable.Empty<Security>()); Assert.DoesNotThrow(() => model.OnSecuritiesChanged(algorithm, changes)); } private static IExecutionModel GetExecutionModel(Language language) { const decimal acceptingSpreadPercent = 0.005m; if (language == Language.Python) { using (Py.GIL()) { const string name = nameof(SpreadExecutionModel); var instance = Py.Import(name).GetAttr(name).Invoke(acceptingSpreadPercent.ToPython()); return new ExecutionModelPythonWrapper(instance); } } return new SpreadExecutionModel(acceptingSpreadPercent); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class ToLookupTests { [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ILookup_MembersBehaveCorrectly(Labeled<ParallelQuery<int>> labeled, int count) { int NonExistentKey = count * 2; ILookup<int, int> lookup = labeled.Item.ToLookup(x => x); // Count Assert.Equal(count, lookup.Count); // Contains Assert.All(lookup, group => lookup.Contains(group.Key)); Assert.False(lookup.Contains(NonExistentKey)); // Indexer Assert.All(lookup, group => Assert.Equal(group, lookup[group.Key])); Assert.Equal(Enumerable.Empty<int>(), lookup[NonExistentKey]); // GetEnumerator IEnumerator e1 = ((IEnumerable)lookup).GetEnumerator(); IEnumerator<IGrouping<int, int>> e2 = lookup.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); Assert.Equal(((IGrouping<int,int>)e1.Current).Key, e2.Current.Key); } Assert.False(e2.MoveNext()); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x * 2); Assert.All(lookup, group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2); Assert.All(lookup, group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_ElementSelector(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x * 2, new ModularCongruenceComparer(count * 2)); Assert.All(lookup, group => { seen.Add(group.Key / 2); Assert.Equal(group.Key, Assert.Single(group) * 2); }); seen.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); ILookup<int, int> lookup = query.ToLookup(x => x, y => y * 2, new ModularCongruenceComparer(count)); Assert.All(lookup, group => { seen.Add(group.Key); Assert.Equal(group.Key * 2, Assert.Single(group)); }); seen.AssertComplete(); if (count < 1) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_ElementSelector_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x % 2); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x % 2, y => -y); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_ElementSelector(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x, new ModularCongruenceComparer(2)); Assert.All(lookup, group => { seenOuter.Add(group.Key % 2); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key % 2, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); if (count < 2) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_CustomComparator(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seenOuter = new IntegerRangeSet(0, Math.Min(count, 2)); ILookup<int, int> lookup = query.ToLookup(x => x, y => -y, new ModularCongruenceComparer(2)); Assert.All(lookup, group => { seenOuter.Add(group.Key % 2); IntegerRangeSet seenInner = new IntegerRangeSet(0, (count + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key % 2, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); if (count < 2) { Assert.Empty(lookup[-1]); } } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 128 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_DuplicateKeys_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ToLookup_DuplicateKeys_ElementSelector_CustomComparator(labeled, count); } [Fact] public static void ToDictionary_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler))); AssertThrows.EventuallyCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void ToLookup_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler))); AssertThrows.OtherTokenCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToLookup(x => x, new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => source.ToLookup(x => x, y => y, new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void ToLookup_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x)); AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, EqualityComparer<int>.Default)); AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, y => y)); AssertThrows.AlreadyCanceled(source => source.ToLookup(x => x, y => y, EqualityComparer<int>.Default)); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))] public static void ToLookup_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, new FailingEqualityComparer<int>())); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToLookup(x => x, y => y, new FailingEqualityComparer<int>())); } [Fact] public static void ToLookup_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToLookup(x => x, y => y, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup((Func<int, int>)null, y => y, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToLookup(x => x, (Func<int, int>)null, EqualityComparer<int>.Default)); } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript{ using Microsoft.JScript.Vsa; using System; using System.Collections; using System.Globalization; using System.Text; using System.Text.RegularExpressions; public class StringPrototype : StringObject{ internal static readonly StringPrototype ob = new StringPrototype(FunctionPrototype.ob, ObjectPrototype.ob); internal static StringConstructor _constructor; internal StringPrototype(FunctionPrototype funcprot, ObjectPrototype parent) : base(parent, ""){ this.noExpando = true; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_anchor)] public static String anchor(Object thisob, Object anchorName){ String thisStr = Convert.ToString(thisob); String anchorStr = Convert.ToString(anchorName); return "<A NAME=\""+anchorStr+"\">"+thisStr+"</A>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_big)] public static String big(Object thisob){ return "<BIG>"+Convert.ToString(thisob)+"</BIG>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_blink)] public static String blink(Object thisob){ return "<BLINK>"+Convert.ToString(thisob)+"</BLINK>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_bold)] public static String bold(Object thisob){ return "<B>"+Convert.ToString(thisob)+"</B>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_charAt)] public static String charAt(Object thisob, double pos){ String thisStr = Convert.ToString(thisob); double position = Convert.ToInteger(pos); if (position < 0 || !(position < thisStr.Length)) return ""; return thisStr.Substring((int)position, 1); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_charCodeAt)] public static Object charCodeAt(Object thisob, double pos){ //This returns an object so that integers stay integers String thisStr = Convert.ToString(thisob); double position = Convert.ToInteger(pos); if (position < 0 || !(position < thisStr.Length)) return Double.NaN; return (int)(thisStr[(int)position]); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject|JSFunctionAttributeEnum.HasVarArgs, JSBuiltin.String_concat)] public static String concat(Object thisob, params Object[] args){ StringBuilder concat = new StringBuilder(Convert.ToString(thisob)); for (int i = 0; i < args.Length; i++) concat.Append(Convert.ToString(args[i])); return concat.ToString(); } public static StringConstructor constructor{ get{ return StringPrototype._constructor; } } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_fixed)] public static String @fixed(Object thisob){ return "<TT>"+Convert.ToString(thisob)+"</TT>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_fontcolor)] public static String fontcolor(Object thisob, Object colorName){ String thisStr = Convert.ToString(thisob); String colorStr = Convert.ToString(thisob); return "<FONT COLOR=\""+colorStr+"\">"+thisStr+"</FONT>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_fontsize)] public static String fontsize(Object thisob, Object fontSize){ String thisStr = Convert.ToString(thisob); String fontStr = Convert.ToString(fontSize); return "<FONT SIZE=\""+fontStr+"\">"+thisStr+"</FONT>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_indexOf)] public static int indexOf(Object thisob, Object searchString, double position){ String thisStr = Convert.ToString(thisob); String searchStr = Convert.ToString(searchString); double startIndex = Convert.ToInteger(position); int length = thisStr.Length; if (startIndex < 0) startIndex = 0; if (startIndex >= length) return searchStr.Length == 0 ? 0 : -1; return thisStr.IndexOf(searchStr, (int)startIndex); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_italics)] public static String italics(Object thisob){ return "<I>"+Convert.ToString(thisob)+"</I>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_lastIndexOf)] public static int lastIndexOf(Object thisob, Object searchString, double position){ String thisStr = Convert.ToString(thisob); String searchStr = Convert.ToString(searchString); int length = thisStr.Length; int j = position != position || position > length ? length : (int)position; if (j < 0) j = 0; if (j >= length) j = length; int slength = searchStr.Length; if (slength == 0) return j; int k = j - 1 + slength; if (k >= length) k = length-1; if (k < 0) return -1; return thisStr.LastIndexOf(searchStr, k); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_link)] public static String link(Object thisob, Object linkRef){ String thisStr = Convert.ToString(thisob); String linkStr = Convert.ToString(linkRef); return "<A HREF=\""+linkStr+"\">"+thisStr+"</A>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_localeCompare)] public static int localeCompare(Object thisob, Object thatob){ return String.Compare(Convert.ToString(thisob), Convert.ToString(thatob), StringComparison.CurrentCulture); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject|JSFunctionAttributeEnum.HasEngine, JSBuiltin.String_match)] public static Object match(Object thisob, VsaEngine engine, Object regExp){ String thisStr = Convert.ToString(thisob); RegExpObject regExpObject = StringPrototype.ToRegExpObject(regExp, engine); Match match; if (!regExpObject.globalInt){ match = regExpObject.regex.Match(thisStr); if (!match.Success){ regExpObject.lastIndexInt = 0; return DBNull.Value; } if (regExpObject.regExpConst != null){ regExpObject.lastIndexInt = regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, match, thisStr); return new RegExpMatch(regExpObject.regExpConst.arrayPrototype, regExpObject.regex, match, thisStr); }else return new RegExpMatch(engine.Globals.globalObject.originalRegExp.arrayPrototype, regExpObject.regex, match, thisStr); } MatchCollection matches = regExpObject.regex.Matches(thisStr); if (matches.Count == 0){ regExpObject.lastIndexInt = 0; return DBNull.Value; } match = matches[matches.Count - 1]; regExpObject.lastIndexInt = regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, match, thisStr); return new RegExpMatch( regExpObject.regExpConst.arrayPrototype, regExpObject.regex, matches, thisStr); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_replace)] public static String replace(Object thisob, Object regExp, Object replacement){ String thisStr = Convert.ToString(thisob); RegExpObject regExpObject = regExp as RegExpObject; if (regExpObject != null) return StringPrototype.ReplaceWithRegExp(thisStr, regExpObject, replacement); Regex regex = regExp as Regex; if (regex != null) return StringPrototype.ReplaceWithRegExp(thisStr, new RegExpObject(regex), replacement); return StringPrototype.ReplaceWithString(thisStr, Convert.ToString(regExp), Convert.ToString(replacement)); } private static String ReplaceWithRegExp(String thisob, RegExpObject regExpObject, Object replacement){ RegExpReplace replacer = replacement is ScriptFunction ? (RegExpReplace)(new ReplaceUsingFunction(regExpObject.regex, (ScriptFunction)replacement, thisob)) : (RegExpReplace)(new ReplaceWithString(Convert.ToString(replacement))); MatchEvaluator matchEvaluator = new MatchEvaluator(replacer.Evaluate); String newString = regExpObject.globalInt ? regExpObject.regex.Replace(thisob, matchEvaluator) : regExpObject.regex.Replace(thisob, matchEvaluator, 1); regExpObject.lastIndexInt = replacer.lastMatch == null ? 0 : regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, replacer.lastMatch, thisob); return newString; } private static String ReplaceWithString(String thisob, String searchString, String replaceString){ int index = thisob.IndexOf(searchString); if (index < 0) return thisob; StringBuilder newString = new StringBuilder(thisob.Substring(0, index)); newString.Append(replaceString); newString.Append(thisob.Substring(index + searchString.Length)); return newString.ToString(); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject|JSFunctionAttributeEnum.HasEngine, JSBuiltin.String_search)] public static int search(Object thisob, VsaEngine engine, Object regExp){ String thisStr = Convert.ToString(thisob); RegExpObject regExpObject = StringPrototype.ToRegExpObject(regExp, engine); Match match = regExpObject.regex.Match(thisStr); if (!match.Success){ regExpObject.lastIndexInt = 0; return -1; } regExpObject.lastIndexInt = regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, match, thisStr); return match.Index; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_slice)] public static String slice(Object thisob, double start, Object end){ String thisStr = Convert.ToString(thisob); int length = thisStr.Length; double startIndex = Convert.ToInteger(start); double endIndex = (end == null || end is Missing) ? length : Convert.ToInteger(end); if (startIndex < 0){ startIndex = length + startIndex; if (startIndex < 0) startIndex = 0; }else if (startIndex > length) startIndex = length; if (endIndex < 0){ endIndex = length + endIndex; if (endIndex < 0) endIndex = 0; }else if (endIndex > length) endIndex = length; int nChars = (int)(endIndex - startIndex); if (nChars <= 0) return ""; else return thisStr.Substring((int)startIndex, nChars); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_small)] public static String small(Object thisob){ return "<SMALL>"+Convert.ToString(thisob)+"</SMALL>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject|JSFunctionAttributeEnum.HasEngine, JSBuiltin.String_split)] public static ArrayObject split(Object thisob, VsaEngine engine, Object separator, Object limit){ String thisStr = Convert.ToString(thisob); uint limitValue = UInt32.MaxValue; if (limit != null && !(limit is Missing) && limit != DBNull.Value){ double lmt = Convert.ToInteger(limit); if (lmt >= 0 && lmt < UInt32.MaxValue) limitValue = (uint)lmt; } if (limitValue == 0) return (ArrayObject)engine.GetOriginalArrayConstructor().Construct(); if (separator == null || separator is Missing){ ArrayObject array = (ArrayObject)engine.GetOriginalArrayConstructor().Construct(); array.SetValueAtIndex(0, thisob); return array; } RegExpObject regExpObject = separator as RegExpObject; if (regExpObject != null) return StringPrototype.SplitWithRegExp(thisStr, engine, regExpObject, limitValue); Regex regex = separator as Regex; if (regex != null) return StringPrototype.SplitWithRegExp(thisStr, engine, new RegExpObject(regex), limitValue); return StringPrototype.SplitWithString(thisStr, engine, Convert.ToString(separator), limitValue); } private static ArrayObject SplitWithRegExp(String thisob, VsaEngine engine, RegExpObject regExpObject, uint limit){ ArrayObject array = (ArrayObject)engine.GetOriginalArrayConstructor().Construct(); Match match = regExpObject.regex.Match(thisob); if (!match.Success){ array.SetValueAtIndex(0, thisob); regExpObject.lastIndexInt = 0; return array; } Match lastMatch; int prevIndex = 0; uint i = 0; do{ int len = match.Index - prevIndex; if (len > 0) { array.SetValueAtIndex(i++, thisob.Substring(prevIndex, len)); if (limit > 0 && i >= limit){ regExpObject.lastIndexInt = regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, match, thisob); return array; } } prevIndex = match.Index + match.Length; lastMatch = match; match = match.NextMatch(); }while(match.Success); if (prevIndex < thisob.Length) array.SetValueAtIndex(i, thisob.Substring(prevIndex)); regExpObject.lastIndexInt = regExpObject.regExpConst.UpdateConstructor(regExpObject.regex, lastMatch, thisob); return array; } private static ArrayObject SplitWithString(String thisob, VsaEngine engine, String separator, uint limit){ ArrayObject array = (ArrayObject)engine.GetOriginalArrayConstructor().Construct(); if (separator.Length == 0){ if (limit > thisob.Length) limit = (uint)thisob.Length; for (int i = 0; i < limit; i++) array.SetValueAtIndex((uint)i, thisob[i].ToString()); }else{ int prevIndex = 0; uint i = 0; int index; while ((index = thisob.IndexOf(separator, prevIndex)) >= 0){ array.SetValueAtIndex(i++, thisob.Substring(prevIndex, index-prevIndex)); if (i >= limit) return array; prevIndex = index + separator.Length; } if (i == 0) array.SetValueAtIndex(0, thisob); else array.SetValueAtIndex(i, thisob.Substring(prevIndex)); } return array; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_strike)] public static String strike(Object thisob){ return "<STRIKE>"+Convert.ToString(thisob)+"</STRIKE>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_sub)] public static String sub(Object thisob){ return "<SUB>"+Convert.ToString(thisob)+"</SUB>"; } [NotRecommended("substr")] [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_substr)] public static String substr(Object thisob, double start, Object count){ String thisStr = thisob as String; if (thisStr == null) thisStr = Convert.ToString(thisob); int length = thisStr.Length; double startIndex = Convert.ToInteger(start); if (startIndex < 0) startIndex += length; if (startIndex < 0) startIndex = 0; else if (startIndex > length) startIndex = length; int nChars = count is int ? (int)count : ((count == null || count is Missing) ? length-(int)Runtime.DoubleToInt64(startIndex) : (int)Runtime.DoubleToInt64(Convert.ToInteger(count))); if (startIndex+nChars > length) nChars = length - (int)startIndex; if (nChars <= 0) return ""; else return thisStr.Substring((int)startIndex, nChars); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_substring)] public static String substring(Object thisob, double start, Object end){ String thisStr = thisob as String; if (thisStr == null) thisStr = Convert.ToString(thisob); int length = thisStr.Length; double startIndex = Convert.ToInteger(start); if (startIndex < 0) startIndex = 0; else if (startIndex > length) startIndex = length; double endIndex = (end == null || end is Missing) ? length : Convert.ToInteger(end); if (endIndex < 0) endIndex = 0; else if (endIndex > length) endIndex = length; if (startIndex > endIndex){ double temp = startIndex; startIndex = endIndex; endIndex = temp; } return thisStr.Substring((int)startIndex, (int)(endIndex - startIndex)); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_sup)] public static String sup(Object thisob){ return "<SUP>"+Convert.ToString(thisob)+"</SUP>"; } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_toLocaleLowerCase)] public static String toLocaleLowerCase(Object thisob){ return Convert.ToString(thisob).ToLower(CultureInfo.CurrentUICulture); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_toLocaleUpperCase)] public static String toLocaleUpperCase(Object thisob){ return Convert.ToString(thisob).ToUpperInvariant(); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_toLowerCase)] public static String toLowerCase(Object thisob){ return Convert.ToString(thisob).ToLowerInvariant(); } private static RegExpObject ToRegExpObject(Object regExp, VsaEngine engine){ if (regExp == null || regExp is Missing) return (RegExpObject)engine.GetOriginalRegExpConstructor().Construct("", false, false, false); RegExpObject result = regExp as RegExpObject; if (result != null) return result; Regex regex = regExp as Regex; if (regex != null) return new RegExpObject(regex); return (RegExpObject)engine.GetOriginalRegExpConstructor().Construct(Convert.ToString(regExp), false, false, false); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_toString)] public static String toString(Object thisob){ StringObject strob = thisob as StringObject; if (strob != null) return strob.value; ConcatString concatStr = thisob as ConcatString; if (concatStr != null) return concatStr.ToString(); IConvertible ic = Convert.GetIConvertible(thisob); if (Convert.GetTypeCode(thisob, ic) == TypeCode.String) return ic.ToString(null); throw new JScriptException(JSError.StringExpected); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_toUpperCase)] public static String toUpperCase(Object thisob){ return Convert.ToString(thisob).ToUpperInvariant(); } [JSFunctionAttribute(JSFunctionAttributeEnum.HasThisObject, JSBuiltin.String_valueOf)] public static Object valueOf(Object thisob){ return StringPrototype.toString(thisob); } } }
using System; namespace DataStructures.HashTables { /* * * Implementation of Quadratic Probing Hash Table * */ public class QPHashTable : HashTableBase { private const double MAX_LOAD_FACTOR = (double)0.6; private HashSlot[] table; private int entries; public QPHashTable() : this(new HashProviderBase()) { } public QPHashTable(HashProviderBase hashProvider) : base(hashProvider) { this.table = new HashSlot[16]; this.entries = 0; } #region ABSTRACT IMPLEMENTATION public override object GetValue(object key) { bool success = false; object result = GetValueFromTable(key, this.table, out success); if(success) { return result; } else { throw new InvalidOperationException("Cannot get value from non-existent key"); } } public override void SetValue(object key, object value) { ResizeTableIfNeed(); SetValueInTable(key, value, this.table); entries++; } public override void Remove(object key) { } public override LoadFactor GetLoadFactor() { return new LoadFactor(this.entries, this.table.Length); } #endregion #region PRIVATE METHODS private object GetValueFromTable(object key, HashSlot[] table, out bool foundSuccess) { int size = table.Length; int hash = base.GetHash(key); int index = GetIndexFromHash(hash, size); //entry index bool success = false; object sValue = null; for(int i = 0 ; i < size; i++) { index = GetNextQuadraticIndex(index, i, size); if(table[index] != null) { if(table[index].Key == key) { sValue = table[index].Value; success = true; break; } } else break; } if(success) { foundSuccess = true; return sValue; } else { foundSuccess = false; return null; } } private int GetNextQuadraticIndex(int entryIndex, int iterator, int tableSize) { //TESTSETSE TEST //return (entryIndex + 1) % tableSize; double result = -1; int i = iterator; double c1 = 0.5; double c2 = 0.5; if(iterator == 0) { return entryIndex; } else { result = entryIndex + (c1 * i) + (c2 * (i * i)); result = result % tableSize; } int resultIndex = (int)result; return resultIndex; } private void SetValueInTable(object key, object value, HashSlot[] table) { int size = table.Length; int hash = base.GetHash(key); int index = GetIndexFromHash(hash, size); bool success = false; for(int i = 0 ; i < size; i++) { index = GetNextQuadraticIndex(index, i, size); if(table[index] == null) { table[index] = new HashSlot(key, value); success = true; break; } else if(table[index].Key == key) { table[index] = new HashSlot(key, value); success = true; break; } } if(!success) { throw new Exception("_INTERNAL_EXCEPTION > QPHashTable > 'SetValueInTable()' :: loop ends, value not inserted"); } } private int GetIndexFromHash(int hash, int tableSize) { int index = hash; if(index < 0) // index must be non-negative number { unchecked { index = (~index); ++index; } } return index % tableSize; } private void ResizeTableIfNeed() { if(GetLoadFactor().Factor > MAX_LOAD_FACTOR) { int newSize = this.table.Length * 2; HashSlot[] newTable = new HashSlot[newSize]; Rehash(this.table, newTable); this.table = newTable; } } private void Rehash(HashSlot[] source, HashSlot[] destination) { int size = source.Length; for(int i = 0 ; i < size; i++) { if(source[i] != null) { SetValueInTable(source[i].Key, source[i].Value, destination); } } } #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using Encog.Cloud.Indicator.Basic; using Encog.Cloud.Indicator.Server; using Encog.Examples.Indicator.Avg; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Util.Arrayutil; using Encog.Util.CSV; using Encog.Util.File; using Directory = System.IO.Directory; namespace Encog.Examples.Indicator.ImportData { /// <summary> /// This is the actual indicator that will be called remotely from /// NinjaTrader. /// </summary> public class MyInd : BasicIndicator { /// <summary> /// Used to normalize the difference between the two SMAs. /// </summary> private readonly NormalizedField _fieldDifference; /// <summary> /// Used to normalize the pip profit/loss outcome. /// </summary> private readonly NormalizedField _fieldOutcome; /// <summary> /// Holds the data as it is downloaded. /// </summary> private readonly InstrumentHolder _holder = new InstrumentHolder(); /// <summary> /// The machine learning method used to predict. /// </summary> private readonly IMLRegression _method; /// <summary> /// The path to store the data files. /// </summary> private readonly string _path; /// <summary> /// The number of rows downloaded. /// </summary> private int _rowsDownloaded; /// <summary> /// Construct the indicator. /// </summary> /// <param name="theMethod">The machine learning method to use.</param> /// <param name="thePath">The path to use.</param> public MyInd(IMLRegression theMethod, string thePath) : base(theMethod != null) { _method = theMethod; _path = thePath; RequestData("CLOSE[1]"); RequestData("SMA(10)[" + Config.InputWindow + "]"); RequestData("SMA(25)[" + Config.InputWindow + "]"); _fieldDifference = new NormalizedField(NormalizationAction.Normalize, "diff", Config.DiffRange, -Config.DiffRange, 1, -1); _fieldOutcome = new NormalizedField(NormalizationAction.Normalize, "out", Config.PipRange, -Config.PipRange, 1, -1); } /// <summary> /// The number of rows downloaded. /// </summary> public int RowsDownloaded { get { return _rowsDownloaded; } } /// <summary> /// Called to notify the indicator that a bar has been received. /// </summary> /// <param name="packet">The packet received.</param> public override void NotifyPacket(IndicatorPacket packet) { long when = long.Parse(packet.Args[0]); if (_method == null) { if (_holder.Record(when, 2, packet.Args)) { _rowsDownloaded++; } } else { var input = new BasicMLData(Config.PredictWindow); const int fastIndex = 2; const int slowIndex = fastIndex + Config.InputWindow; for (int i = 0; i < 3; i++) { double fast = CSVFormat.EgFormat.Parse(packet.Args[fastIndex + i]); double slow = CSVFormat.EgFormat.Parse(packet.Args[slowIndex + i]); double diff = _fieldDifference.Normalize((fast - slow)/Config.PipSize); input[i] = _fieldDifference.Normalize(diff); } IMLData result = _method.Compute(input); double d = result[0]; d = _fieldOutcome.DeNormalize(d); String[] args = { "?", // line 1 "?", // line 2 CSVFormat.EgFormat.Format(d, EncogFramework.DefaultPrecision), // bar 1 }; // arrow 2 Link.WritePacket(IndicatorLink.PacketInd, args); } } /// <summary> /// Determine the next file to process. /// </summary> /// <returns>The next file.</returns> public string NextFile() { int mx = -1; string[] list = Directory.GetFiles(_path); foreach (string file in list) { var fn = new FileInfo(file); if (fn.Name.StartsWith("collected") && fn.Name.EndsWith(".csv")) { int idx = fn.Name.IndexOf(".csv"); String str = fn.Name.Substring(9, idx - 9); int n = int.Parse(str); mx = Math.Max(n, mx); } } return FileUtil.CombinePath(new FileInfo(_path), "collected" + (mx + 1) + ".csv").ToString(); } /// <summary> /// Write the files that were collected. /// </summary> public void WriteCollectedFile() { string targetFile = NextFile(); using (var outfile = new StreamWriter(targetFile)) { // output header outfile.Write("\"WHEN\""); int index = 0; foreach (String str in DataRequested) { String str2; // strip off [ if needed int ix = str.IndexOf('['); if (ix != -1) { str2 = str.Substring(0, ix).Trim(); } else { str2 = str; } int c = DataCount[index++]; if (c <= 1) { outfile.Write(",\"" + str2 + "\""); } else { for (int i = 0; i < c; i++) { outfile.Write(",\"" + str2 + "-b" + i + "\""); } } } outfile.WriteLine(); // output data foreach (long key in _holder.Sorted) { String str = _holder.Data[key]; outfile.WriteLine(key + "," + str); } } } /// <summary> /// Notify on termination, write the collected file. /// </summary> public override void NotifyTermination() { if (_method == null) { WriteCollectedFile(); } } } }
// 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.Threading; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public class SqlNotificationTest : IDisposable { // Misc constants private const int CALLBACK_TIMEOUT = 5000; // milliseconds // Database schema private readonly string _tableName = $"dbo.[SQLDEP_{Guid.NewGuid().ToString()}]"; private readonly string _queueName = $"SQLDEP_{Guid.NewGuid().ToString()}"; private readonly string _serviceName = $"SQLDEP_{Guid.NewGuid().ToString()}"; private readonly string _schemaQueue; // Connection information used by all tests private readonly string _startConnectionString; private readonly string _execConnectionString; public SqlNotificationTest() { _startConnectionString = DataTestUtility.TcpConnStr; _execConnectionString = DataTestUtility.TcpConnStr; _schemaQueue = $"[{_queueName}]"; Setup(); } public void Dispose() { Cleanup(); } #region StartStop_Tests [CheckConnStrSetupFact] public void Test_DoubleStart_SameConnStr() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); Assert.False(SqlDependency.Start(_startConnectionString), "Expected failure when trying to start listener."); Assert.False(SqlDependency.Stop(_startConnectionString), "Expected failure when trying to completely stop listener."); Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } [CheckConnStrSetupFact] public void Test_DoubleStart_DifferentConnStr() { SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString); // just change something that doesn't impact the dependency dispatcher if (cb.ShouldSerialize("connect timeout")) cb.ConnectTimeout = cb.ConnectTimeout + 1; else cb.ConnectTimeout = 50; Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => SqlDependency.Start(cb.ToString())); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); Assert.False(SqlDependency.Stop(cb.ToString()), "Expected failure when trying to completely stop listener."); } } [CheckConnStrSetupFact] public void Test_Start_DifferentDB() { SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString) { InitialCatalog = "tempdb" }; string altDatabaseConnectionString = cb.ToString(); Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); Assert.True(SqlDependency.Start(altDatabaseConnectionString), "Failed to start listener."); Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); Assert.True(SqlDependency.Stop(altDatabaseConnectionString), "Failed to stop listener."); } #endregion #region SqlDependency_Tests [CheckConnStrSetupFact] public void Test_SingleDependency_NoStart() { using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { Console.WriteLine("4 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader()); } } [CheckConnStrSetupFact] public void Test_SingleDependency_Stopped() { SqlDependency.Start(_startConnectionString); SqlDependency.Stop(_startConnectionString); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { // Delegate won't be called, since notifications were stoppped Console.WriteLine("5 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); }; DataTestUtility.AssertThrowsWrapper<InvalidOperationException>(() => cmd.ExecuteReader()); } } [CheckConnStrSetupFact] public void Test_SingleDependency_AllDefaults_SqlAuth() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); ManualResetEvent updateCompleted = new ManualResetEvent(false); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd); dep.OnChange += delegate (object o, SqlNotificationEventArgs arg) { Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Update, arg.Info, "Unexpected Info value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Data, arg.Source, "Unexpected Source value."); notificationReceived.Set(); }; cmd.ExecuteReader(); } int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount); DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value."); updateCompleted.Set(); Assert.True(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification not received within the timeout period"); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } } [CheckConnStrSetupFact] public void Test_SingleDependency_CustomQueue_SqlAuth() { Assert.True(SqlDependency.Start(_startConnectionString, _queueName), "Failed to start listener."); try { // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); ManualResetEvent updateCompleted = new ManualResetEvent(false); using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); SqlDependency dep = new SqlDependency(cmd, "service=" + _serviceName + ";local database=msdb", 0); dep.OnChange += delegate (object o, SqlNotificationEventArgs args) { Assert.True(updateCompleted.WaitOne(CALLBACK_TIMEOUT, false), "Received notification, but update did not complete."); Console.WriteLine("7 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source); notificationReceived.Set(); }; cmd.ExecuteReader(); } int count = RunSQL("UPDATE " + _tableName + " SET c=" + Environment.TickCount); DataTestUtility.AssertEqualsWithDescription(1, count, "Unexpected count value."); updateCompleted.Set(); Assert.False(notificationReceived.WaitOne(CALLBACK_TIMEOUT, false), "Notification should not be received."); } finally { Assert.True(SqlDependency.Stop(_startConnectionString, _queueName), "Failed to stop listener."); } } /// <summary> /// SqlDependecy premature timeout /// </summary> [CheckConnStrSetupFact] public void Test_SingleDependency_Timeout() { Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener."); try { // with resolution of 15 seconds, SqlDependency should fire timeout notification only after 45 seconds, leave 5 seconds gap from both sides. const int SqlDependencyTimerResolution = 15; // seconds const int testTimeSeconds = SqlDependencyTimerResolution * 3 - 5; const int minTimeoutEventInterval = testTimeSeconds - 1; const int maxTimeoutEventInterval = testTimeSeconds + SqlDependencyTimerResolution + 1; // create a new event every time to avoid mixing notification callbacks ManualResetEvent notificationReceived = new ManualResetEvent(false); DateTime startUtcTime; using (SqlConnection conn = new SqlConnection(_execConnectionString)) using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn)) { conn.Open(); // create SqlDependency with timeout SqlDependency dep = new SqlDependency(cmd, null, testTimeSeconds); dep.OnChange += delegate (object o, SqlNotificationEventArgs arg) { // notification of Timeout can arrive either from server or from client timer. Handle both situations here: SqlNotificationInfo info = arg.Info; if (info == SqlNotificationInfo.Unknown) { // server timed out before the client, replace it with Error to produce consistent output for trun info = SqlNotificationInfo.Error; } DataTestUtility.AssertEqualsWithDescription(SqlNotificationType.Change, arg.Type, "Unexpected Type value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationInfo.Error, arg.Info, "Unexpected Info value."); DataTestUtility.AssertEqualsWithDescription(SqlNotificationSource.Timeout, arg.Source, "Unexpected Source value."); notificationReceived.Set(); }; cmd.ExecuteReader(); startUtcTime = DateTime.UtcNow; } Assert.True( notificationReceived.WaitOne(TimeSpan.FromSeconds(maxTimeoutEventInterval), false), string.Format("Notification not received within the maximum timeout period of {0} seconds", maxTimeoutEventInterval)); // notification received in time, check that it is not too early TimeSpan notificationTime = DateTime.UtcNow - startUtcTime; Assert.True( notificationTime >= TimeSpan.FromSeconds(minTimeoutEventInterval), string.Format( "Notification was not expected before {0} seconds: received after {1} seconds", minTimeoutEventInterval, notificationTime.TotalSeconds)); } finally { Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener."); } } #endregion #region Utility_Methods private static string[] CreateSqlSetupStatements(string tableName, string queueName, string serviceName) { return new string[] { string.Format("CREATE TABLE {0}(a INT NOT NULL, b NVARCHAR(10), c INT NOT NULL)", tableName), string.Format("INSERT INTO {0} (a, b, c) VALUES (1, 'foo', 0)", tableName), string.Format("CREATE QUEUE {0}", queueName), string.Format("CREATE SERVICE [{0}] ON QUEUE {1} ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification])", serviceName, queueName) }; } private static string[] CreateSqlCleanupStatements(string tableName, string queueName, string serviceName) { return new string[] { string.Format("DROP TABLE {0}", tableName), string.Format("DROP SERVICE [{0}]", serviceName), string.Format("DROP QUEUE {0}", queueName) }; } private void Setup() { RunSQL(CreateSqlSetupStatements(_tableName, _schemaQueue, _serviceName)); } private void Cleanup() { RunSQL(CreateSqlCleanupStatements(_tableName, _schemaQueue, _serviceName)); } private int RunSQL(params string[] stmts) { int count = -1; using (SqlConnection conn = new SqlConnection(_execConnectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); foreach (string stmt in stmts) { cmd.CommandText = stmt; int tmp = cmd.ExecuteNonQuery(); count = ((0 <= tmp) ? ((0 <= count) ? count + tmp : tmp) : count); } } return count; } #endregion } }
namespace Microsoft.Protocols.TestSuites.MS_OXWSCORE { using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to test operations related to creation, retrieving, updating, movement, copy, and deletion of base, contact, distribution list, email, meeting, post, and task items on the server. /// </summary> [TestClass] public class S08_ManageSevenKindsOfItems : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the test class. /// </summary> /// <param name="context">Context to initialize.</param> [ClassInitialize] public static void ClassInitialize(TestContext context) { TestClassBase.Initialize(context); } /// <summary> /// Clean up the test class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is intended to validate the successful response returned by CreateItem, GetItem and DeleteItem operations for multiple types of items with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S08_TC01_CreateGetDeleteTypesOfItemsSuccessfully() { Site.Assume.IsTrue(Common.IsRequirementEnabled(19241, this.Site), "Exchange 2007 doesn't support MS-OXWSDLIST"); #region Step 1: Create Items. ItemIdType[] createdItemIds = CreateAllTypesItems(); #endregion #region Step 2: Get items GetItemResponseType getItemResponse = this.CallGetItemOperation(createdItemIds); // Check the operation response. Common.CheckOperationSuccess(getItemResponse, createdItemIds.Length, this.Site); ItemIdType[] getItemIds = Common.GetItemIdsFromInfoResponse(getItemResponse); #endregion #region Step3: Delete the item DeleteItemResponseType deleteItemResponse = this.CallDeleteItemOperation(); // Check the operation response. Common.CheckOperationSuccess(deleteItemResponse, createdItemIds.Length, this.Site); // Clear ExistItemIds for DeleteItem. this.InitializeCollection(); #endregion #region Step 4: Get deleted items getItemResponse = this.CallGetItemOperation(getItemIds); Site.Assert.AreEqual<int>( createdItemIds.Length, getItemResponse.ResponseMessages.Items.GetLength(0), "Expected Item Count: {0}, Actual Item Count: {1}", createdItemIds.Length, getItemResponse.ResponseMessages.Items.GetLength(0)); // Check whether the GetItem operation is executed failed with ErrorItemNotFound response code. foreach (ResponseMessageType responseMessage in getItemResponse.ResponseMessages.Items) { Site.Assert.AreEqual<ResponseClassType>( ResponseClassType.Error, responseMessage.ResponseClass, string.Format( "Get each types of items should succeed! Expected response code: {0}, actual response code: {1}", ResponseCodeType.ErrorItemNotFound, responseMessage.ResponseCode)); } #endregion } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem and CopyItem operations for multiple types of items with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S08_TC02_CopyTypesOfItemsSuccessfully() { Site.Assume.IsTrue(Common.IsRequirementEnabled(19241, this.Site), "Exchange 2007 doesn't support MS-OXWSDLIST"); #region Step 1: Create Items. ItemIdType[] createdItemIds = CreateAllTypesItems(); #endregion #region Step 2: Copy items. CopyItemResponseType copyItemResponse = this.CallCopyItemOperation(DistinguishedFolderIdNameType.drafts, createdItemIds); // Check the operation response. Common.CheckOperationSuccess(copyItemResponse, createdItemIds.Length, this.Site); #endregion this.FindNewItemsInFolder(DistinguishedFolderIdNameType.drafts); } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem and MoveItem operations for multiple types of items with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S08_TC03_MoveTypesOfItemsSuccessfully() { Site.Assume.IsTrue(Common.IsRequirementEnabled(19241, this.Site), "Exchange 2007 doesn't support MS-OXWSDLIST"); #region Step 1: Create Items. ItemIdType[] createdItemIds = CreateAllTypesItems(); #endregion #region Step 2: Move items. // Clear ExistItemIds for MoveItem this.InitializeCollection(); MoveItemResponseType moveItemResponse = this.CallMoveItemOperation(DistinguishedFolderIdNameType.deleteditems, createdItemIds); // Check the operation response. Common.CheckOperationSuccess(moveItemResponse, createdItemIds.Length, this.Site); #endregion this.FindNewItemsInFolder(DistinguishedFolderIdNameType.deleteditems); } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem and UpdateItem operations for multiple types of items with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S08_TC04_UpdateTypesOfItemsSuccessfully() { Site.Assume.IsTrue(Common.IsRequirementEnabled(19241, this.Site), "Exchange 2007 doesn't support MS-OXWSDLIST"); #region Step 1: Create Items. ItemIdType[] createdItemIds = CreateAllTypesItems(); #endregion #region Step 2: Update items. ItemChangeType[] itemChanges = new ItemChangeType[createdItemIds.Length]; // Set the public properties (Subject) which all the seven kinds of operation have. for (int i = 0; i < createdItemIds.Length; i++) { itemChanges[i] = new ItemChangeType(); itemChanges[i].Item = createdItemIds[i]; itemChanges[i].Updates = new ItemChangeDescriptionType[] { new SetItemFieldType() { Item = new PathToUnindexedFieldType() { FieldURI = UnindexedFieldURIType.itemSubject }, Item1 = new ItemType() { Subject = Common.GenerateResourceName( this.Site, TestSuiteHelper.SubjectForUpdateItem) } } }; } UpdateItemResponseType updateItemResponse = this.CallUpdateItemOperation( DistinguishedFolderIdNameType.drafts, true, itemChanges); // Check the operation response. Common.CheckOperationSuccess(updateItemResponse, createdItemIds.Length, this.Site); #endregion } /// <summary> /// This test case is intended to validate the failed response returned by UpdateItem operation with ErrorIncorrectUpdatePropertyCount response code for multiple types of items. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S08_TC05_UpdateTypesOfItemsFailed() { Site.Assume.IsTrue(Common.IsRequirementEnabled(19241, this.Site), "Exchange 2007 doesn't support MS-OXWSDLIST"); #region Step 1: Create Items. ItemIdType[] createdItemIds = CreateAllTypesItems(); #endregion #region Step 2: Update items. // Initialize the change item to update. UpdateItemType updateRequest = new UpdateItemType(); ItemChangeType[] itemChanges = new ItemChangeType[createdItemIds.Length]; // Set two properties (Subject and ReminderMinutesBeforeStart) to update, in order to return an error "ErrorIncorrectUpdatePropertyCount". for (int i = 0; i < createdItemIds.Length; i++) { itemChanges[i] = new ItemChangeType(); itemChanges[i].Item = createdItemIds[i]; itemChanges[i].Updates = new ItemChangeDescriptionType[1]; SetItemFieldType setItem1 = new SetItemFieldType(); setItem1.Item = new PathToUnindexedFieldType() { FieldURI = UnindexedFieldURIType.itemSubject }; setItem1.Item1 = new ContactItemType() { Subject = Common.GenerateResourceName( this.Site, TestSuiteHelper.SubjectForUpdateItem), ReminderMinutesBeforeStart = TestSuiteHelper.ReminderMinutesBeforeStart }; itemChanges[i].Updates[0] = setItem1; } updateRequest.ItemChanges = itemChanges; updateRequest.MessageDispositionSpecified = true; updateRequest.MessageDisposition = MessageDispositionType.SaveOnly; updateRequest.SendMeetingInvitationsOrCancellations = CalendarItemUpdateOperationType.SendToAllAndSaveCopy; updateRequest.SendMeetingInvitationsOrCancellationsSpecified = true; // Call UpdateItem to update the Subject and the ReminderMinutesBeforeStart of the created item simultaneously. UpdateItemResponseType updateItemResponse = this.COREAdapter.UpdateItem(updateRequest); foreach (ResponseMessageType responseMessage in updateItemResponse.ResponseMessages.Items) { // Verify ResponseCode is ErrorIncorrectUpdatePropertyCount. this.VerifyErrorIncorrectUpdatePropertyCount(responseMessage.ResponseCode); } #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.PropertyDescriptorCollection")] namespace System.ComponentModel { /// <summary> /// <para> /// Represents a collection of properties. /// </para> /// </summary> public class PropertyDescriptorCollection : ICollection, IList, IDictionary { /// <summary> /// An empty PropertyDescriptorCollection that can used instead of creating a new one with no items. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields")] public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null, true); private IDictionary _cachedFoundProperties; private bool _cachedIgnoreCase; private PropertyDescriptor[] _properties; private int _propCount = 0; private readonly string[] _namedSort; private readonly IComparer _comparer; private bool _propsOwned; private bool _needSort = false; private bool _readOnly = false; private readonly object _internalSyncObject = new object(); /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptorCollection'/> /// class. /// </para> /// </summary> public PropertyDescriptorCollection(PropertyDescriptor[] properties) { if (properties == null) { _properties = new PropertyDescriptor[0]; _propCount = 0; } else { _properties = properties; _propCount = properties.Length; } _propsOwned = true; } /// <summary> /// Initializes a new instance of a property descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </summary> public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOnly) : this(properties) { _readOnly = readOnly; } private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer) { _propsOwned = false; if (namedSort != null) { _namedSort = (string[])namedSort.Clone(); } _comparer = comparer; _properties = properties; _propCount = propCount; _needSort = true; } /// <summary> /// <para> /// Gets the number /// of property descriptors in the /// collection. /// </para> /// </summary> public int Count { get { return _propCount; } } /// <summary> /// <para>Gets the property with the specified index /// number.</para> /// </summary> public virtual PropertyDescriptor this[int index] { get { if (index >= _propCount) { throw new IndexOutOfRangeException(); } EnsurePropsOwned(); return _properties[index]; } } /// <summary> /// <para>Gets the property with the specified name.</para> /// </summary> public virtual PropertyDescriptor this[string name] { get { return Find(name, false); } } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public int Add(PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_propCount + 1); _properties[_propCount++] = value; return _propCount - 1; } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public void Clear() { if (_readOnly) { throw new NotSupportedException(); } _propCount = 0; _cachedFoundProperties = null; } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public bool Contains(PropertyDescriptor value) { return IndexOf(value) >= 0; } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public void CopyTo(Array array, int index) { EnsurePropsOwned(); Array.Copy(_properties, 0, array, index, Count); } private void EnsurePropsOwned() { if (!_propsOwned) { _propsOwned = true; if (_properties != null) { PropertyDescriptor[] newProps = new PropertyDescriptor[Count]; Array.Copy(_properties, 0, newProps, 0, Count); _properties = newProps; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= _properties.Length) { return; } if (_properties == null || _properties.Length == 0) { _propCount = 0; _properties = new PropertyDescriptor[sizeNeeded]; return; } EnsurePropsOwned(); int newSize = Math.Max(sizeNeeded, _properties.Length * 2); PropertyDescriptor[] newProps = new PropertyDescriptor[newSize]; Array.Copy(_properties, 0, newProps, 0, _propCount); _properties = newProps; } /// <summary> /// <para>Gets the description of the property with the specified name.</para> /// </summary> public virtual PropertyDescriptor Find(string name, bool ignoreCase) { lock (_internalSyncObject) { PropertyDescriptor p = null; if (_cachedFoundProperties == null || _cachedIgnoreCase != ignoreCase) { _cachedIgnoreCase = ignoreCase; if (ignoreCase) { _cachedFoundProperties = new Hashtable(StringComparer.OrdinalIgnoreCase); } else { _cachedFoundProperties = new Hashtable(); } } // first try to find it in the cache // object cached = _cachedFoundProperties[name]; if (cached != null) { return (PropertyDescriptor)cached; } // Now start walking from where we last left off, filling // the cache as we go. // for (int i = 0; i < _propCount; i++) { if (ignoreCase) { if (string.Equals(_properties[i].Name, name, StringComparison.OrdinalIgnoreCase)) { _cachedFoundProperties[name] = _properties[i]; p = _properties[i]; break; } } else { if (_properties[i].Name.Equals(name)) { _cachedFoundProperties[name] = _properties[i]; p = _properties[i]; break; } } } return p; } } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public int IndexOf(PropertyDescriptor value) { return Array.IndexOf(_properties, value, 0, _propCount); } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public void Insert(int index, PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(_propCount + 1); if (index < _propCount) { Array.Copy(_properties, index, _properties, index + 1, _propCount - index); } _properties[index] = value; _propCount++; } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public void Remove(PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } /// <summary> /// <para>[To be supplied.]</para> /// </summary> public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(); } if (index < _propCount - 1) { Array.Copy(_properties, index + 1, _properties, index, _propCount - index - 1); } _properties[_propCount - 1] = null; _propCount--; } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </para> /// </summary> public virtual PropertyDescriptorCollection Sort() { return new PropertyDescriptorCollection(_properties, _propCount, _namedSort, _comparer); } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </summary> public virtual PropertyDescriptorCollection Sort(string[] names) { return new PropertyDescriptorCollection(_properties, _propCount, names, _comparer); } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </summary> public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer) { return new PropertyDescriptorCollection(_properties, _propCount, names, comparer); } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection, using the specified IComparer to compare, /// the PropertyDescriptors contained in the collection. /// </para> /// </summary> public virtual PropertyDescriptorCollection Sort(IComparer comparer) { return new PropertyDescriptorCollection(_properties, _propCount, _namedSort, comparer); } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </summary> protected void InternalSort(string[] names) { if (_properties == null || _properties.Length == 0) { return; } this.InternalSort(_comparer); if (names != null && names.Length > 0) { ArrayList propArrayList = new ArrayList(_properties); int foundCount = 0; int propCount = _properties.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < propCount; j++) { PropertyDescriptor currentProp = (PropertyDescriptor)propArrayList[j]; // Found a matching property. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentProp != null && currentProp.Name.Equals(names[i])) { _properties[foundCount++] = currentProp; propArrayList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < propCount; i++) { if (propArrayList[i] != null) { _properties[foundCount++] = (PropertyDescriptor)propArrayList[i]; } } Debug.Assert(foundCount == propCount, "We did not completely fill our property array"); } } /// <summary> /// <para> /// Sorts the members of this PropertyDescriptorCollection using the specified IComparer. /// </para> /// </summary> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(_properties, sorter); } } /// <summary> /// <para> /// Gets an enumerator for this <see cref='System.ComponentModel.PropertyDescriptorCollection'/>. /// </para> /// </summary> public virtual IEnumerator GetEnumerator() { EnsurePropsOwned(); // we can only return an enumerator on the props we actually have... if (_properties.Length != _propCount) { PropertyDescriptor[] enumProps = new PropertyDescriptor[_propCount]; Array.Copy(_properties, 0, enumProps, 0, _propCount); return enumProps.GetEnumerator(); } return _properties.GetEnumerator(); } /// <internalonly/> bool ICollection.IsSynchronized { get { return false; } } /// <internalonly/> object ICollection.SyncRoot { get { return null; } } /// <internalonly/> void IDictionary.Add(object key, object value) { PropertyDescriptor newProp = value as PropertyDescriptor; if (newProp == null) { throw new ArgumentException(nameof(value)); } Add(newProp); } /// <internalonly/> bool IDictionary.Contains(object key) { if (key is string) { return this[(string)key] != null; } return false; } /// <internalonly/> IDictionaryEnumerator IDictionary.GetEnumerator() { return new PropertyDescriptorEnumerator(this); } /// <internalonly/> bool IDictionary.IsFixedSize { get { return _readOnly; } } /// <internalonly/> bool IDictionary.IsReadOnly { get { return _readOnly; } } /// <internalonly/> object IDictionary.this[object key] { get { if (key is string) { return this[(string)key]; } return null; } set { if (_readOnly) { throw new NotSupportedException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } int index = -1; if (key is int) { index = (int)key; if (index < 0 || index >= _propCount) { throw new IndexOutOfRangeException(); } } else if (key is string) { for (int i = 0; i < _propCount; i++) { if (_properties[i].Name.Equals((string)key)) { index = i; break; } } } else { throw new ArgumentException(nameof(key)); } if (index == -1) { Add((PropertyDescriptor)value); } else { EnsurePropsOwned(); _properties[index] = (PropertyDescriptor)value; if (_cachedFoundProperties != null && key is string) { _cachedFoundProperties[key] = value; } } } } /// <internalonly/> ICollection IDictionary.Keys { get { string[] keys = new string[_propCount]; for (int i = 0; i < _propCount; i++) { keys[i] = _properties[i].Name; } return keys; } } /// <internalonly/> ICollection IDictionary.Values { get { // we can only return an enumerator on the props we actually have... // if (_properties.Length != _propCount) { PropertyDescriptor[] newProps = new PropertyDescriptor[_propCount]; Array.Copy(_properties, 0, newProps, 0, _propCount); return newProps; } else { return (ICollection)_properties.Clone(); } } } /// <internalonly/> void IDictionary.Remove(object key) { if (key is string) { PropertyDescriptor pd = this[(string)key]; if (pd != null) { ((IList)this).Remove(pd); } } } /// <internalonly/> int IList.Add(object value) { return Add((PropertyDescriptor)value); } /// <internalonly/> bool IList.Contains(object value) { return Contains((PropertyDescriptor)value); } /// <internalonly/> int IList.IndexOf(object value) { return IndexOf((PropertyDescriptor)value); } /// <internalonly/> void IList.Insert(int index, object value) { Insert(index, (PropertyDescriptor)value); } /// <internalonly/> bool IList.IsReadOnly { get { return _readOnly; } } /// <internalonly/> bool IList.IsFixedSize { get { return _readOnly; } } /// <internalonly/> void IList.Remove(object value) { Remove((PropertyDescriptor)value); } /// <internalonly/> object IList.this[int index] { get { return this[index]; } set { if (_readOnly) { throw new NotSupportedException(); } if (index >= _propCount) { throw new IndexOutOfRangeException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } EnsurePropsOwned(); _properties[index] = (PropertyDescriptor)value; } } private class PropertyDescriptorEnumerator : IDictionaryEnumerator { private PropertyDescriptorCollection _owner; private int _index = -1; public PropertyDescriptorEnumerator(PropertyDescriptorCollection owner) { _owner = owner; } public object Current { get { return Entry; } } public DictionaryEntry Entry { get { PropertyDescriptor curProp = _owner[_index]; return new DictionaryEntry(curProp.Name, curProp); } } public object Key { get { return _owner[_index].Name; } } public object Value { get { return _owner[_index].Name; } } public bool MoveNext() { if (_index < (_owner.Count - 1)) { _index++; return true; } return false; } public void Reset() { _index = -1; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Xml; using System.Xml.XPath; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Routing; using umbraco; using System.Linq; using umbraco.BusinessLogic; using umbraco.presentation.preview; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : IPublishedContentCache { #region Routes cache private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting); // for INTERNAL, UNIT TESTS use ONLY internal RoutesCache RoutesCache { get { return _routesCache; } } // for INTERNAL, UNIT TESTS use ONLY internal static bool UnitTesting = false; public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null) { if (route == null) throw new ArgumentNullException("route"); // try to get from cache if not previewing var contentId = preview ? 0 : _routesCache.GetNodeId(route); // if found id in cache then get corresponding content // and clear cache if not found - for whatever reason IPublishedContent content = null; if (contentId > 0) { content = GetById(umbracoContext, preview, contentId); if (content == null) _routesCache.ClearNode(contentId); } // still have nothing? actually determine the id hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value); // cache if we have a content and not previewing if (content != null && !preview) { var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/'))); var iscanon = !UnitTesting && !DomainHelper.ExistsDomainInPath(DomainHelper.GetAllDomains(false), content.Path, domainRootNodeId); // and only if this is the canonical url (the one GetUrl would return) if (iscanon) _routesCache.Store(contentId, route); } return content; } public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { // try to get from cache if not previewing var route = preview ? null : _routesCache.GetRoute(contentId); // if found in cache then return if (route != null) return route; // else actually determine the route route = DetermineRouteById(umbracoContext, preview, contentId); // cache if we have a route and not previewing if (route != null && !preview) _routesCache.Store(contentId, route); return route; } IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode) { if (route == null) throw new ArgumentNullException("route"); //the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos)); IEnumerable<XPathVariable> vars; var xpath = CreateXpathQuery(startNodeId, path, hideTopLevelNode, out vars); //check if we can find the node in our xml cache var content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray()); // if hideTopLevelNodePath is true then for url /foo we looked for /*/foo // but maybe that was the url of a non-default top-level node, so we also // have to look for /foo (see note in ApplyHideTopLevelNodeFromPath). if (content == null && hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0) { xpath = CreateXpathQuery(startNodeId, path, false, out vars); content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray()); } return content; } string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { var node = GetById(umbracoContext, preview, contentId); if (node == null) return null; // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting urls in the way var pathParts = new List<string>(); var n = node; var hasDomains = DomainHelper.NodeHasDomains(n.Id); while (!hasDomains && n != null) // n is null at root { // get the url var urlName = n.UrlName; pathParts.Add(urlName); // move to parent node n = n.Parent; hasDomains = n != null && DomainHelper.NodeHasDomains(n.Id); } // no domain, respect HideTopLevelNodeFromPath for legacy purposes if (!hasDomains && global::umbraco.GlobalSettings.HideTopLevelNodeFromPath) ApplyHideTopLevelNodeFromPath(umbracoContext, node, pathParts); // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc var route = (n == null ? "" : n.Id.ToString(CultureInfo.InvariantCulture)) + path; return route; } static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, IPublishedContent node, IList<string> pathParts) { // in theory if hideTopLevelNodeFromPath is true, then there should be only once // top-level node, or else domains should be assigned. but for backward compatibility // we add this check - we look for the document matching "/" and if it's not us, then // we do not hide the top level path // it has to be taken care of in GetByRoute too so if // "/foo" fails (looking for "/*/foo") we try also "/foo". // this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but // that's the way it works pre-4.10 and we try to be backward compat for the time being if (node.Parent == null) { var rootNode = umbracoContext.ContentCache.GetByRoute("/", true); if (rootNode == null) throw new Exception("Failed to get node at /."); if (rootNode.Id == node.Id) // remove only if we're the default node pathParts.RemoveAt(pathParts.Count - 1); } else { pathParts.RemoveAt(pathParts.Count - 1); } } #endregion #region XPath Strings class XPathStringsDefinition { public int Version { get; private set; } public static string Root { get { return "/root"; } } public string RootDocuments { get; private set; } public string DescendantDocumentById { get; private set; } public string ChildDocumentByUrlName { get; private set; } public string ChildDocumentByUrlNameVar { get; private set; } public string RootDocumentWithLowestSortOrder { get; private set; } public XPathStringsDefinition(int version) { Version = version; switch (version) { // legacy XML schema case 0: RootDocuments = "/root/node"; DescendantDocumentById = "//node [@id={0}]"; ChildDocumentByUrlName = "/node [@urlName='{0}']"; ChildDocumentByUrlNameVar = "/node [@urlName=${0}]"; RootDocumentWithLowestSortOrder = "/root/node [not(@sortOrder > ../node/@sortOrder)][1]"; break; // default XML schema as of 4.10 case 1: RootDocuments = "/root/* [@isDoc]"; DescendantDocumentById = "//* [@isDoc and @id={0}]"; ChildDocumentByUrlName = "/* [@isDoc and @urlName='{0}']"; ChildDocumentByUrlNameVar = "/* [@isDoc and @urlName=${0}]"; RootDocumentWithLowestSortOrder = "/root/* [@isDoc and not(@sortOrder > ../* [@isDoc]/@sortOrder)][1]"; break; default: throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version)); } } } static XPathStringsDefinition _xPathStringsValue; static XPathStringsDefinition XPathStrings { get { // in theory XPathStrings should be a static variable that // we should initialize in a static ctor - but then test cases // that switch schemas fail - so cache and refresh when needed, // ie never when running the actual site var version = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? 0 : 1; if (_xPathStringsValue == null || _xPathStringsValue.Version != version) _xPathStringsValue = new XPathStringsDefinition(version); return _xPathStringsValue; } } #endregion #region Converters private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing) { return xmlNode == null ? null : PublishedContentModelFactory.CreateModel(new XmlPublishedContent(xmlNode, isPreviewing)); } private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing) { return xmlNodes.Cast<XmlNode>() .Select(xmlNode => PublishedContentModelFactory.CreateModel(new XmlPublishedContent(xmlNode, isPreviewing))); } #endregion #region Getters public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return null; var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>(); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual bool HasContent(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); if (xml == null) return false; var node = xml.SelectSingleNode(XPathStrings.RootDocuments); return node != null; } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); return xml.CreateNavigator(); } public virtual bool XPathNavigatorIsNavigable { get { return false; } } #endregion #region Legacy Xml static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache = new ConditionalWeakTable<UmbracoContext, PreviewContent>(); private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate; /// <summary> /// Gets/sets the delegate used to retrieve the Xml content, generally the setter is only used for unit tests /// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request /// </summary> /// <remarks> /// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request /// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff /// that when run inside of a unit test fails. /// </remarks> internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate { get { return _xmlDelegate ?? (_xmlDelegate = (context, preview) => { if (preview) { var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () => { if (previewContent.ValidPreviewSet) previewContent.LoadPreviewset(); }); if (previewContent.ValidPreviewSet) return previewContent.XmlContent; } return content.Instance.XmlContent; }); } set { _xmlDelegate = value; } } internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview) { return GetXmlDelegate(umbracoContext, preview); } #endregion #region XPathQuery static readonly char[] SlashChar = new[] { '/' }; protected string CreateXpathQuery(int startNodeId, string path, bool hideTopLevelNodeFromPath, out IEnumerable<XPathVariable> vars) { string xpath; vars = null; if (path == string.Empty || path == "/") { // if url is empty if (startNodeId > 0) { // if in a domain then use the root node of the domain xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId); } else { // if not in a domain - what is the default page? // let's say it is the first one in the tree, if any -- order by sortOrder // but! // umbraco does not consistently guarantee that sortOrder starts with 0 // so the one that we want is the one with the smallest sortOrder // read http://stackoverflow.com/questions/1128745/how-can-i-use-xpath-to-find-the-minimum-value-of-an-attribute-in-a-set-of-elemen // so that one does not work, because min(@sortOrder) maybe 1 // xpath = "/root/*[@isDoc and @sortOrder='0']"; // and we can't use min() because that's XPath 2.0 // that one works xpath = XPathStrings.RootDocumentWithLowestSortOrder; } } else { // if url is not empty, then use it to try lookup a matching page var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries); var xpathBuilder = new StringBuilder(); int partsIndex = 0; List<XPathVariable> varsList = null; if (startNodeId == 0) { if (hideTopLevelNodeFromPath) xpathBuilder.Append(XPathStrings.RootDocuments); // first node is not in the url else xpathBuilder.Append(XPathStringsDefinition.Root); } else { xpathBuilder.AppendFormat(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId); // always "hide top level" when there's a domain } while (partsIndex < urlParts.Length) { var part = urlParts[partsIndex++]; if (part.Contains('\'') || part.Contains('"')) { // use vars, escaping gets ugly pretty quickly varsList = varsList ?? new List<XPathVariable>(); var varName = string.Format("var{0}", partsIndex); varsList.Add(new XPathVariable(varName, part)); xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlNameVar, varName); } else { xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlName, part); } } xpath = xpathBuilder.ToString(); if (varsList != null) vars = varsList.ToArray(); } return xpath; } #endregion #region Fragments public IPublishedContent CreateFragment(string contentTypeAlias, IDictionary<string, object> dataValues, bool isPreviewing, bool managed) { return new PublishedFragment(contentTypeAlias, dataValues, isPreviewing, managed); } #endregion } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Data; using System.Diagnostics; using System.Collections; using System.Data.SqlClient; using TarsimAvlCL; using System.Collections.Generic; namespace TarsimAvlDAL { public class CarClass : DB { public GeoPointList GetStations(int? OrganID) { SqlCommand cmd = new SqlCommand("TarsimAVL_GetStations", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@OrganId", SqlDbType.Int)).Value = OrganID; SqlDataReader dataReader = null; var carlist = new GeoPointList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); ; while (dataReader.Read()) { GeoPoint metadatadb = new GeoPoint(); if (dataReader["PointID"] != DBNull.Value) { metadatadb.FillForObject(dataReader); carlist.Rows.Add(metadatadb); } } dataReader.Close(); ProjectConnection.Close(); return carlist; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public int insert(ClCar c,LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_Car_Insert", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("Img", SqlDbType.NVarChar)).Value = c.Img; cmd.Parameters.Add(new SqlParameter("Code", SqlDbType.NVarChar)).Value = c.Code; cmd.Parameters.Add(new SqlParameter("KhodroTypeId", SqlDbType.Int)).Value = c.KhodroTypeId; cmd.Parameters.Add(new SqlParameter("Tip", SqlDbType.NVarChar)).Value = (c.Tip); cmd.Parameters.Add(new SqlParameter("Model", SqlDbType.NVarChar)).Value = c.Model; cmd.Parameters.Add(new SqlParameter("VIN", SqlDbType.NVarChar)).Value = (c.VIN); cmd.Parameters.Add(new SqlParameter("ShomarePelak", SqlDbType.NVarChar)).Value = (c.ShomarePelak); cmd.Parameters.Add(new SqlParameter("PelakTypeId", SqlDbType.Int)).Value = (c.PelakTypeId); cmd.Parameters.Add(new SqlParameter("RegUser", SqlDbType.Int)).Value = (c.RegUser); cmd.Parameters.Add(new SqlParameter("CreateDate", SqlDbType.SmallDateTime)).Value = (c.CreateDate); cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.Int)).Value = (c.OrganID); cmd.Parameters.Add(new SqlParameter("Organ2ID", SqlDbType.Int)).Value = (c.Organ2ID); cmd.Parameters.Add(new SqlParameter("SimID", SqlDbType.Int)).Value = (c.SimID); cmd.Parameters.Add(new SqlParameter("LineID", SqlDbType.Int)).Value = (c.LineID); SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } public DataSet GetListRport(ClCar c, LogParam logparam) { SqlCommand cmd = new SqlCommand("Rep_Prc_CarGetList", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("Oid", SqlDbType.Int)).Value = c.OrganID; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); try { ProjectConnection.Open(); da.Fill(ds); return ds; } catch (Exception ex) { return null; } finally { ProjectConnection.Close(); } } //--------------------------------------------------------------------------------------------------------- public CLCarList GetList(ClCarFilter c,LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_Car_GetList", ProjectConnection); cmd.CommandType = System.Data.CommandType.StoredProcedure; //cmd.Parameters.Add(new SqlParameter("Img", SqlDbType.NVarChar)).Value = c.ClCar.Img; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("CarIDs", SqlDbType.NVarChar)).Value = (c.ClCar.CarIDs); cmd.Parameters.Add(new SqlParameter("CarID", SqlDbType.Int)).Value = (c.ClCar.CarID); cmd.Parameters.Add(new SqlParameter("Code", SqlDbType.NVarChar)).Value = (c.ClCar.Code); cmd.Parameters.Add(new SqlParameter("KhodroTypeId", SqlDbType.Int)).Value = (c.ClCar.KhodroTypeId); cmd.Parameters.Add(new SqlParameter("Tip", SqlDbType.NVarChar)).Value = (c.ClCar.Tip); cmd.Parameters.Add(new SqlParameter("Model", SqlDbType.NVarChar)).Value = (c.ClCar.Model); cmd.Parameters.Add(new SqlParameter("VIN", SqlDbType.NVarChar)).Value = (c.ClCar.VIN); cmd.Parameters.Add(new SqlParameter("ShomarePelak", SqlDbType.NVarChar)).Value = (c.ClCar.ShomarePelak); cmd.Parameters.Add(new SqlParameter("PelakTypeId", SqlDbType.Int)).Value = (c.ClCar.PelakTypeId); cmd.Parameters.Add(new SqlParameter("RegUser", SqlDbType.Int)).Value = (c.ClCar.RegUser); cmd.Parameters.Add(new SqlParameter("CreateDate", SqlDbType.NVarChar)).Value = (c.ClCar.CreateDate); cmd.Parameters.Add(new SqlParameter("OrganID", SqlDbType.NVarChar)).Value = (c.ClCar.OrganID); cmd.Parameters.Add(new SqlParameter(PAGEINDEX_PARAM, SqlDbType.Int)).Value = c.PageIndex; cmd.Parameters.Add(new SqlParameter(PAGESIZE_PARAM, SqlDbType.Int)).Value = c.PageSize; if (String.IsNullOrEmpty(c.OrderBy)) c.OrderBy = "carid"; cmd.Parameters.Add(new SqlParameter(ORDERBY_PARAM, SqlDbType.NVarChar)).Value = c.OrderBy; cmd.Parameters.Add(new SqlParameter(ORDER_PARAM, SqlDbType.NVarChar)).Value = c.Order; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int); prmResult.Direction = ParameterDirection.Output; cmd.Parameters.Add(prmResult); //DataSet ds = new DataSet(); SqlDataReader dataReader = null; var carlist = new CLCarList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); ; while (dataReader.Read()) { if ((carlist.RowCount == null || carlist.RowCount == 0) && dataReader["ROW_COUNT"] != DBNull.Value) carlist.RowCount = Convert.ToInt32(dataReader["ROW_COUNT"]); ClCar metadatadb = new ClCar(); if (dataReader["CarID"] != DBNull.Value) { //metadatadb.MetaDataID = Convert.ToInt32(dataReader[metadatadb.METADATAID_FIELD]); metadatadb.FillForObject(dataReader); carlist.Rows.Add(metadatadb); } } //da.Fill(ds); dataReader.Close(); ProjectConnection.Close(); return carlist; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if(ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public bool? UpdateCar(ClCar car) { bool flag = false; try { SqlCommand sqlCommand = ProjectConnection.CreateCommand(); sqlCommand.CommandText = "TarsimAVL_Car_Update"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter("@CarID", SqlDbType.Int)).Value = car.CarID; sqlCommand.Parameters.Add(new SqlParameter("@Img", SqlDbType.NVarChar)).Value = car.Img; sqlCommand.Parameters.Add(new SqlParameter("@Code", SqlDbType.NVarChar)).Value = car.Code; sqlCommand.Parameters.Add(new SqlParameter("@KhodroTypeId", SqlDbType.Int)).Value = car.KhodroTypeId; sqlCommand.Parameters.Add(new SqlParameter("@Tip", SqlDbType.NVarChar)).Value = car.Tip; sqlCommand.Parameters.Add(new SqlParameter("@Model", SqlDbType.NVarChar)).Value = car.Model; sqlCommand.Parameters.Add(new SqlParameter("@VIN", SqlDbType.NVarChar)).Value = car.VIN; sqlCommand.Parameters.Add(new SqlParameter("@ShomarePelak", SqlDbType.NVarChar)).Value = car.ShomarePelak; sqlCommand.Parameters.Add(new SqlParameter("@PelakTypeId", SqlDbType.Int)).Value = car.PelakTypeId; sqlCommand.Parameters.Add(new SqlParameter("@RegUser", SqlDbType.Int)).Value = car.RegUser; sqlCommand.Parameters.Add(new SqlParameter("@CreateDate", SqlDbType.DateTime)).Value = car.CreateDate; sqlCommand.Parameters.Add(new SqlParameter("@SimID", SqlDbType.Int)).Value = car.SimID; sqlCommand.Parameters.Add(new SqlParameter("@OrganID", SqlDbType.Int)).Value = car.OrganID; sqlCommand.Parameters.Add(new SqlParameter("@Organ2ID", SqlDbType.Int)).Value = (car.Organ2ID); sqlCommand.Parameters.Add(new SqlParameter("@LineID", SqlDbType.Int)).Value = (car.LineID); ProjectConnection.Open(); int rcc = sqlCommand.ExecuteNonQuery(); if (rcc == 0) return null; ProjectConnection.Close(); flag = true; } catch (Exception ex) { // } finally { if (ProjectConnection.State == ConnectionState.Open) { ProjectConnection.Close(); } } return flag; } public bool DeleteCar(int CarID) { bool flag = false; try { SqlCommand sqlCommand = ProjectConnection.CreateCommand(); sqlCommand.CommandText = "TarsimAVL_Car_Delete"; sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter("@CarID", SqlDbType.Int)).Value = CarID; ProjectConnection.Open(); flag = Convert.ToBoolean(sqlCommand.ExecuteScalar()); ProjectConnection.Close(); return true; } catch (Exception ex) { // } finally { if (ProjectConnection.State == ConnectionState.Open) { ProjectConnection.Close(); } } return flag; } } //--------------------------------------------------------------------------------------------------------- }