/// <summary> /// SuperGridActionList /// </summary> /// <param name="superGrid">Associated SuperGridControl</param> public SuperGridActionList(SuperGridControl superGrid) : base(superGrid) { _SuperGrid = superGrid; _ChangeService = Component.Site.GetService(typeof(IComponentChangeService)) as IComponentChangeService; }
internal ChangeToolStripParentVerb(string text, ToolStripDesigner designer) { this._designer = designer; this._provider = designer.Component.Site; this._host = (IDesignerHost) this._provider.GetService(typeof(IDesignerHost)); this.componentChangeSvc = (IComponentChangeService) this._provider.GetService(typeof(IComponentChangeService)); }
public override void Initialize(IComponent c) { base.Initialize(c); ((NamedComponent) c).Name = c.Site.Name; this.Service = (IComponentChangeService) this.GetService(typeof(IComponentChangeService)); this.Service.ComponentRename += new System.ComponentModel.Design.ComponentRenameEventHandler(this.ComponentRenameEventHandler); }
/// <summary> /// Initialize a new instance of the KryptonSplitContainerActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonSplitContainerActionList(KryptonSplitContainerDesigner owner) : base(owner.Component) { _splitContainer = owner.Component as KryptonSplitContainer; // Assuming we were correctly passed an actual component... if (_splitContainer != null) { // Get access to the actual Orientation propertry PropertyDescriptor orientationProp = TypeDescriptor.GetProperties(_splitContainer)["Orientation"]; // If we succeeded in getting the property if (orientationProp != null) { // Decide on the next action to take given the current setting if ((Orientation)orientationProp.GetValue(_splitContainer) == Orientation.Vertical) _action = "Horizontal splitter orientation"; else _action = "Vertical splitter orientation"; } } // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
public void GenButtons(object sender, EventArgs e) { if (schedule == null) { schedule = this.Component as AjaxSchedule; } if (schedule.ScheduleButtons.Count == 0) { if (host == null) { host = (IDesignerHost)this.GetService(typeof(IDesignerHost)); } if (svcCompChange == null) { svcCompChange = (IComponentChangeService)this.GetService(typeof(IComponentChangeService)); } DesignerTransaction trans = host.CreateTransaction("Generate buttons"); this.addButton(AjaxScheduleButtonType.PreviousYear, "<<"); this.addButton(AjaxScheduleButtonType.Previous, "<"); this.addButton(AjaxScheduleButtonType.NextYear, ">>"); this.addButton(AjaxScheduleButtonType.Next, ">"); this.addButton(AjaxScheduleButtonType.Today, "today"); this.addButton(AjaxScheduleButtonType.Month, "month"); this.addButton(AjaxScheduleButtonType.Week, "week"); this.addButton(AjaxScheduleButtonType.Day, "day"); trans.Commit(); MessageBox.Show("generate buttons successful!"); } }
/// <summary> /// Makes sure local variables are valid. /// </summary> private void CustomInitialize() { if (this._DesignerHost == null) this._DesignerHost = this.GetService(typeof(IDesignerHost)) as IDesignerHost; if (this._ComponentChangeService == null) this._ComponentChangeService = this._DesignerHost.GetService(typeof(IComponentChangeService)) as IComponentChangeService; }
public fmEasilyReportDesigner(IReport rpt, IDesignerHost designerHost) { InitializeComponent(); designReport = rpt; tempReport = rpt.Copy(); componentChangeService = designerHost.GetService(typeof(IComponentChangeService)) as IComponentChangeService; }
public override void Initialize(System.ComponentModel.IComponent component) { base.Initialize(component); this._changeService = (IComponentChangeService)this.GetService(typeof(IComponentChangeService)); this._changeService.ComponentRemoving += new ComponentEventHandler(OnRemoving); this.Verbs.Add(new DesignerVerb("Add TabControl", new EventHandler(OnAddTabControl))); this.Verbs.Add(new DesignerVerb("Remove TabControl", new EventHandler(OnRemoveTabControl))); }
public override void Initialize(IComponent component) { base.Initialize(component); changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // Update your designer verb whenever ComponentChanged event occurs. if (changeService != null) changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); }
/// <summary> /// Initialize a new instance of the KryptonWrapLabelActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonWrapLabelActionList(KryptonWrapLabelDesigner owner) : base(owner.Component) { // Remember the label instance _wrapLabel = owner.Component as KryptonWrapLabel; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonNumericUpDownActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonNumericUpDownActionList(KryptonNumericUpDownDesigner owner) : base(owner.Component) { // Remember the text box instance _numericUpDown = owner.Component as KryptonNumericUpDown; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonContextMenuActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonContextMenuActionList(KryptonContextMenuDesigner owner) : base(owner.Component) { // Remember the context menu instance _contextMenu = owner.Component as KryptonContextMenu; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonBreadCrumbActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonBreadCrumbActionList(KryptonBreadCrumbDesigner owner) : base(owner.Component) { // Remember the bread crumb control instance _breadCrumb = owner.Component as KryptonBreadCrumb; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonTreeViewActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonTreeViewActionList(KryptonTreeViewDesigner owner) : base(owner.Component) { // Remember the tree view instance _treeView = owner.Component as KryptonTreeView; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonGalleryActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonGalleryActionList(KryptonGalleryDesigner owner) : base(owner.Component) { // Remember the gallery instance _gallery = (KryptonGallery)owner.Component; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonHeaderGroupActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonHeaderGroupActionList(KryptonHeaderGroupDesigner owner) : base(owner.Component) { // Remember the panel instance _headerGroup = owner.Component as KryptonHeaderGroup; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonWorkspaceActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonWorkspaceActionList(KryptonWorkspaceDesigner owner) : base(owner.Component) { // Remember designer and actual component instance being designed _workspace = (KryptonWorkspace)owner.Component; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonMaskedTextBoxActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonMaskedTextBoxActionList(KryptonMaskedTextBoxDesigner owner) : base(owner.Component) { // Remember the text box instance _maskedTextBox = owner.Component as KryptonMaskedTextBox; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonSeparatorActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonSeparatorActionList(KryptonSeparatorDesigner owner) : base(owner.Component) { // Remember the link label instance _separator = owner.Component as KryptonSeparator; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
/// <summary> /// Initialize a new instance of the KryptonRadioButtonActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonRadioButtonActionList(KryptonRadioButtonDesigner owner) : base(owner.Component) { // Remember the radio button instance _radioButton = owner.Component as KryptonRadioButton; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
public override void Exec() { //System.Reflection.Assembly ass = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("System.Management.Automation")); System.Reflection.Assembly ass = System.Reflection.Assembly.Load("System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); //System.Reflection.Assembly ass = System.Reflection.Assembly.LoadWithPartialName("System.Management.Automation"); if (ass == null) { MessageBox.Show("PowerShell has not been detected. You need to download and install PowerShell from the Microsoft website in order to use this feature." , "BIDS Helper PowerShell Window" , MessageBoxButtons.OK , MessageBoxIcon.Stop); return; } try { ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); ApplicationObject.StatusBar.Progress(true, "Launching Powershell...", 0, 1); this.changesvc = (IComponentChangeService)currentDB.Site.GetService(typeof(IComponentChangeService)); //int iErrorCnt = 0; EnvDTE80.Windows2 toolWins; EnvDTE.Window toolWin; object objTemp = null; toolWins = (Windows2)ApplicationObject.Windows; toolWin = toolWins.CreateToolWindow2(AddInInstance , typeof(BIDSHelper.SSAS.PowerShellControl).Assembly.Location , typeof(BIDSHelper.SSAS.PowerShellControl).FullName , currentDB.Name + ": PowerShell Window", "{" + typeof(BIDSHelper.SSAS.PowerShellControl).GUID.ToString() + "}" , ref objTemp); BIDSHelper.SSAS.PowerShellControl ctrl = (SSAS.PowerShellControl)objTemp; ctrl.CurrentDB = currentDB; ctrl.ToolWindows = toolWins; EnvDTE.Properties prop = this.ApplicationObject.get_Properties("FontsAndColors", "TextEditor"); ctrl.SetFont((string)prop.Item("FontFamily").Value, (float)Convert.ToDouble(prop.Item("FontSize").Value)); //setting IsFloating and Linkable to false makes this window tabbed toolWin.IsFloating = false; toolWin.Linkable = false; toolWin.Visible = true; this.changesvc.OnComponentChanging(this.currentDB, null); this.changesvc.OnComponentChanged(this.currentDB, null, null, null); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); ApplicationObject.StatusBar.Progress(false, "Launching Powershell...", 2, 2); } }
/// <summary> /// Initialize a new instance of the KryptonGroupBoxDesigner class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonGroupBoxActionList(KryptonGroupBoxDesigner owner) : base(owner.Component) { // Remember the control instance _groupBox = owner.Component as KryptonGroupBox; // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
protected override void Dispose(bool disposing) { if (this.Service != null) { this.Service.ComponentRename -= new System.ComponentModel.Design.ComponentRenameEventHandler(this.ComponentRenameEventHandler); this.Service = null; } base.Dispose(disposing); }
// The constructor associates the control to the smart tag action list. public KRBTabControlActionList(KrbTabControl control) : base(control) { _linkedControl = control; _host = (IDesignerHost)GetService(typeof(IDesignerHost)); _changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); _designerService = (DesignerActionUIService)GetService(typeof(DesignerActionUIService)); AutoShow = true; // When this control will be added to the design area, the smart tag panel will open automatically. }
public SmartTagTransactions(string transactionname,DesignerActionList list,Control ctrl) { this.actionList = list; this.ctrl = ctrl; host = (IDesignerHost)this.actionList.GetService(typeof(IDesignerHost)); this.transaction = host.CreateTransaction(transactionname); changeService = (IComponentChangeService)this.actionList.GetService(typeof(IComponentChangeService)); changeService.OnComponentChanging(ctrl,null); }
public override void Initialize(IComponent component) { base.Initialize(component); if (component.Site != null) { changeService = component.Site.GetService(typeof(IComponentChangeService)) as IComponentChangeService; changeService.ComponentRename += OnComponentRename; } }
public FABaseDesigner() { changeService = null; designerVerbs = new DesignerVerbCollection(); ShowAbout = new DesignerVerb("About Farsi Libraries", OnShowAbout); ShowAbout.Checked = false; designerVerbs.Add(ShowAbout); Designers.Add(this); }
/// <summary> /// Initialize a new instance of the KryptonNavigatorActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonNavigatorActionList(KryptonNavigatorDesigner owner) : base(owner.Component) { // Remember designer and actual component instance being designed _designer = owner; _navigator = (KryptonNavigator)owner.Component; // Cache service used to notify when a property has changed _serviceComponentChange = (IComponentChangeService)GetService(typeof(IComponentChangeService)); _serviceDesignerAction = (DesignerActionUIService)GetService(typeof(DesignerActionUIService)); }
internal StandardMenuStripVerb(string text, ToolStripDesigner designer) { this._designer = designer; this._provider = designer.Component.Site; this._host = (IDesignerHost) this._provider.GetService(typeof(IDesignerHost)); this.componentChangeSvc = (IComponentChangeService) this._provider.GetService(typeof(IComponentChangeService)); if (text == null) { text = System.Design.SR.GetString("ToolStripDesignerStandardItemsVerb"); } }
/// <summary> /// Initializes the designer with the specified component. /// </summary> /// <param name="component">The IComponent to associate the designer with.</param> public override void Initialize(IComponent component) { // Let base class do standard stuff base.Initialize(component); // Cast to correct type _dateTimePicker = component as KryptonDataGridViewDateTimePickerColumn; // Get access to the design services _changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
private bool EditMenuItemsChangeCallback(object context) { bool changed = false; PopupMenu oControl = (PopupMenu)Component; IServiceProvider site = oControl.Site; IComponentChangeService changeService = null; try { MenuItemsEditorForm oEditorForm = new MenuItemsEditorForm(oControl); if (oEditorForm.ShowDialog() == DialogResult.OK) { changed = true; } } finally { if (changed && changeService != null) { changeService.OnComponentChanged(oControl, null, null, null); } } return(changed); }
public virtual void AddStandardItems() { if (this.Navigator.Site == null) { this.commandBarRowElement = new CommandBarRowElement(); this.Rows.Add(this.commandBarRowElement); } else { this.designerHost = this.Navigator.Site.GetService(typeof(IDesignerHost)) as IDesignerHost; this.changeService = this.Navigator.Site.GetService(typeof(IComponentChangeService)) as IComponentChangeService; this.commandBarRowElement = (CommandBarRowElement)this.designerHost.CreateComponent(typeof(CommandBarRowElement), this.Navigator.Name + "RowElement"); this.changeService.OnComponentChanging((object)this.Navigator.Site.Component, (MemberDescriptor)null); this.Rows.Add(this.commandBarRowElement); this.changeService.OnComponentChanged((object)this.Navigator.Site.Component, (MemberDescriptor)null, (object)null, (object)null); } this.CreateFirstTopStripElementChildElements(); this.CreateSecondBottomStripElementChildElements(); if (!this.attachedEvents) { this.AttachEvents(); } this.ElementTree.ApplyThemeToElementTree(); }
internal virtual void OnPropertyChanged(Ole32.DispatchID dispid) { try { ISite site = Host.Site; if (site != null) { IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (changeService != null) { try { changeService.OnComponentChanging(Host, null); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } // Now notify the change service that the change was successful. // changeService.OnComponentChanged(Host, null, null, null); } } } catch (Exception t) { Debug.Fail(t.ToString()); throw; } }
/// <summary> /// Initialize a new instance of the KryptonSplitContainerActionList class. /// </summary> /// <param name="owner">Designer that owns this action list instance.</param> public KryptonSplitContainerActionList(KryptonSplitContainerDesigner owner) : base(owner.Component) { _splitContainer = owner.Component as KryptonSplitContainer; // Assuming we were correctly passed an actual component... if (_splitContainer != null) { // Get access to the actual Orientation property PropertyDescriptor orientationProp = TypeDescriptor.GetProperties(_splitContainer)["Orientation"]; // If we succeeded in getting the property if (orientationProp != null) { // Decide on the next action to take given the current setting _action = (Orientation)orientationProp.GetValue(_splitContainer) == Orientation.Vertical ? "Horizontal splitter orientation" : "Vertical splitter orientation"; } } // Cache service used to notify when a property has changed _service = (IComponentChangeService)GetService(typeof(IComponentChangeService)); }
internal static void SetValue(IComponent component, string propertyName, object value) { PropertyDescriptor propertyDescriptor = GetPropertyDescriptor(component, propertyName); IComponentChangeService svc = GetChangeService(component); IDesignerHost host = GetDesignerHost(component); DesignerTransaction txn = host.CreateTransaction(); try { svc.OnComponentChanging(component, propertyDescriptor); propertyDescriptor.SetValue(component, value); svc.OnComponentChanged(component, propertyDescriptor, null, null); txn.Commit(); txn = null; } finally { if (txn != null) { txn.Cancel(); } } }
public ComponentChangeDispatcher(IServiceProvider serviceProvider, object component, PropertyDescriptor propertyDescriptor) { this.serviceProvider = serviceProvider; this.component = component; this.property = propertyDescriptor; IComponentChangeService service = serviceProvider.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (service != null) { try { this.newValue = this.oldValue = propertyDescriptor.GetValue(component); propertyDescriptor.AddValueChanged(component, new EventHandler(this.OnValueChanged)); service.OnComponentChanging(component, propertyDescriptor); } catch (CheckoutException exception) { if (exception != CheckoutException.Canceled) { throw exception; } } } }
/// <summary> /// Initializes the designer with the specified component. /// </summary> /// <param name="component">The IComponent to associate the designer with.</param> public override void Initialize(IComponent component) { Debug.Assert(component != null); // Validate the parameter reference if (component == null) { throw new ArgumentNullException("component"); } // Let base class do standard stuff base.Initialize(component); // Cast to correct type _ribbonRadioButton = (KryptonRibbonGroupRadioButton)component; _ribbonRadioButton.DesignTimeContextMenu += new MouseEventHandler(OnContextMenu); // Get access to the services _designerHost = (IDesignerHost)GetService(typeof(IDesignerHost)); _changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService)); // We need to know when we are being removed/changed _changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); }
HRESULT IPropertyNotifySink.OnChanged(DispatchID dispid) { // Some controls fire OnChanged() notifications when getting values of some properties. // To prevent this kind of recursion, we check to see if we are already inside a OnChanged() call. if (host.NoComponentChangeEvents != 0) { return(HRESULT.S_OK); } host.NoComponentChangeEvents++; try { AxPropertyDescriptor prop = null; Debug.WriteLineIf(AxHTraceSwitch.TraceVerbose, "in OnChanged"); if (dispid != DispatchID.UNKNOWN) { prop = host.GetPropertyDescriptorFromDispid(dispid); if (prop != null) { prop.OnValueChanged(host); if (!prop.SettingValue) { prop.UpdateTypeConverterAndTypeEditor(true); } } } else { // update them all for DISPID_UNKNOWN. PropertyDescriptorCollection props = ((ICustomTypeDescriptor)host).GetProperties(); foreach (PropertyDescriptor p in props) { prop = p as AxPropertyDescriptor; if (prop != null && !prop.SettingValue) { prop.UpdateTypeConverterAndTypeEditor(true); } } } ISite site = host.Site; if (site != null) { IComponentChangeService changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (changeService != null) { try { changeService.OnComponentChanging(host, prop); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return(HRESULT.S_OK); } throw; } // Now notify the change service that the change was successful. // changeService.OnComponentChanged(host, prop, null, (prop?.GetValue(host))); } } } catch (Exception t) { Debug.Fail(t.ToString()); throw; } finally { host.NoComponentChangeEvents--; } return(HRESULT.S_OK); }
public override void Exec() { try { UIHierarchy solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer; UIHierarchyItem hierItem = ((UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0)); ProjectItem pi = (ProjectItem)hierItem.Object; Window win = pi.Document.ActiveWindow; IDesignerHost designer = (IDesignerHost)pi.Document.ActiveWindow.Object; Package package = null; ConnectionManager conn = GetSelectedConnectionManager(designer, out package); BIDSHelper.SSIS.FixedWidthColumnsForm form = new BIDSHelper.SSIS.FixedWidthColumnsForm(); if (conn != null && conn.Properties["Format"].GetValue(conn).ToString() == "FixedWidth") { //hiding properties for ragged right form.dataGridView1.Height = form.dataGridView1.Height + 50 + 26; form.dataGridView1.Top -= 50; form.label1.Height -= 50; form.cboRaggedRightDelimiter.Visible = false; form.lblRaggedRight.Visible = false; } DialogResult dialogResult = form.ShowDialog(); if (dialogResult == DialogResult.OK) { #if KATMAI || DENALI || SQL2014 wrap.IDTSConnectionManagerFlatFile100 ff = conn.InnerObject as wrap.IDTSConnectionManagerFlatFile100; DtsConvert.GetExtendedInterface(conn); #else wrap.IDTSConnectionManagerFlatFile90 ff = conn.InnerObject as wrap.IDTSConnectionManagerFlatFile90; DtsConvert.ToConnectionManager90(conn); #endif while (ff.Columns.Count > 0) { ff.Columns.Remove(0); } List <string> listUsedNames = new List <string>(); //JCW - Added counter to identify the last column int columnCount = 1; foreach (DataGridViewRow row in form.dataGridView1.Rows) { string sName = row.Cells[0].Value.ToString().Trim(); string sOriginalName = sName; int i = 1; while (listUsedNames.Contains(sName)) //find a unique name for the column { sName = sOriginalName + (++i); } listUsedNames.Add(sName); #if KATMAI || DENALI || SQL2014 wrap.IDTSConnectionManagerFlatFileColumn100 col = ff.Columns.Add(); wrap.IDTSName100 name = col as wrap.IDTSName100; #else wrap.IDTSConnectionManagerFlatFileColumn90 col = ff.Columns.Add(); wrap.IDTSName90 name = col as wrap.IDTSName90; #endif name.Name = sName; col.MaximumWidth = int.Parse(row.Cells[1].Value.ToString()); col.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR; if (columnCount == form.dataGridView1.Rows.Count && form.cboRaggedRightDelimiter.Text != "[None]") { col.ColumnWidth = 0; col.ColumnType = "Delimited"; col.ColumnDelimiter = DecodeDelimiter(form.cboRaggedRightDelimiter.Text); } else { col.ColumnWidth = int.Parse(row.Cells[1].Value.ToString()); col.ColumnType = "FixedWidth"; } columnCount++; } //mark package object as dirty IComponentChangeService changesvc = (IComponentChangeService)designer.GetService(typeof(IComponentChangeService)); changesvc.OnComponentChanging(package, null); changesvc.OnComponentChanged(package, null, null, null); //marks the package designer as dirty SSISHelpers.MarkPackageDirty(package); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
void UnloadDesigner() { LoggingService.Debug("FormsDesigner unloading, setting ActiveDesignSurface to null"); designSurfaceManager.ActiveDesignSurface = null; bool savedIsDirty = (this.DesignerCodeFile == null) ? false : this.DesignerCodeFile.IsDirty; this.UserControl = this.pleaseWaitLabel; Application.DoEvents(); if (this.DesignerCodeFile != null) { this.DesignerCodeFile.IsDirty = savedIsDirty; } // We cannot dispose the design surface now because of SD2-451: // When the switch to the source view was triggered by a double-click on an event // in the PropertyPad, "InvalidOperationException: The container cannot be disposed // at design time" is thrown. // This is solved by calling dispose after the double-click event has been processed. if (designSurface != null) { designSurface.Loading -= this.DesignerLoading; designSurface.Loaded -= this.DesignerLoaded; designSurface.Flushed -= this.DesignerFlushed; designSurface.Unloading -= this.DesignerUnloading; IComponentChangeService componentChangeService = designSurface.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (componentChangeService != null) { componentChangeService.ComponentChanged -= ComponentChanged; componentChangeService.ComponentAdded -= ComponentListChanged; componentChangeService.ComponentRemoved -= ComponentListChanged; componentChangeService.ComponentRename -= ComponentListChanged; } if (this.Host != null) { this.Host.TransactionClosed -= TransactionClose; } ISelectionService selectionService = designSurface.GetService(typeof(ISelectionService)) as ISelectionService; if (selectionService != null) { selectionService.SelectionChanged -= SelectionChangedHandler; } if (disposing) { designSurface.Dispose(); } else { this.Control.BeginInvoke(new MethodInvoker(designSurface.Dispose)); } designSurface = null; } this.typeResolutionService = null; this.loader = null; foreach (KeyValuePair <Type, TypeDescriptionProvider> entry in this.addedTypeDescriptionProviders) { TypeDescriptor.RemoveProvider(entry.Value, entry.Key); } this.addedTypeDescriptionProviders.Clear(); }
/// <summary> /// Creates a new tab order control that displays the tab order /// UI for a form. /// </summary> public TabOrder(IDesignerHost host) { this.host = host; // Determine a font for us to use. // IUIService uisvc = (IUIService)host.GetService(typeof(IUIService)); if (uisvc != null) { tabFont = (Font)uisvc.Styles["DialogFont"]; } else { tabFont = DefaultFont; } tabFont = new Font(tabFont, FontStyle.Bold); // And compute the proper highlight dimensions. // selSize = DesignerUtils.GetAdornmentDimensions(AdornmentType.GrabHandle).Width; // Colors and brushes... // drawString = new StringBuilder(12); highlightTextBrush = new SolidBrush(SystemColors.HighlightText); highlightPen = new Pen(SystemColors.Highlight); // The decimal separator // NumberFormatInfo formatInfo = (NumberFormatInfo)CultureInfo.CurrentCulture.GetFormat(typeof(NumberFormatInfo)); if (formatInfo != null) { decimalSep = formatInfo.NumberDecimalSeparator; } else { decimalSep = "."; } tabProperties = new Hashtable(); // Set up a NULL brush so we never try to invalidate the control. This is // more efficient for what we're doing // SetStyle(ControlStyles.Opaque, true); // We're an overlay on top of the form // IOverlayService os = (IOverlayService)host.GetService(typeof(IOverlayService)); Debug.Assert(os != null, "No overlay service -- tab order UI cannot be shown"); if (os != null) { os.PushOverlay(this); } // Push a help keyword so the help system knows we're in place. // IHelpService hs = (IHelpService)host.GetService(typeof(IHelpService)); if (hs != null) { hs.AddContextAttribute("Keyword", "TabOrderView", HelpKeywordType.FilterKeyword); } commands = new MenuCommand[] { new MenuCommand(new EventHandler(OnKeyCancel), MenuCommands.KeyCancel), new MenuCommand(new EventHandler(OnKeyDefault), MenuCommands.KeyDefaultAction), new MenuCommand(new EventHandler(OnKeyPrevious), MenuCommands.KeyMoveUp), new MenuCommand(new EventHandler(OnKeyNext), MenuCommands.KeyMoveDown), new MenuCommand(new EventHandler(OnKeyPrevious), MenuCommands.KeyMoveLeft), new MenuCommand(new EventHandler(OnKeyNext), MenuCommands.KeyMoveRight), new MenuCommand(new EventHandler(OnKeyNext), MenuCommands.KeySelectNext), new MenuCommand(new EventHandler(OnKeyPrevious), MenuCommands.KeySelectPrevious), }; newCommands = new MenuCommand[] { new MenuCommand(new EventHandler(OnKeyDefault), MenuCommands.KeyTabOrderSelect), }; IMenuCommandService mcs = (IMenuCommandService)host.GetService(typeof(IMenuCommandService)); if (mcs != null) { foreach (MenuCommand mc in newCommands) { mcs.AddCommand(mc); } } // We also override keyboard, menu and mouse handlers. Our override relies on the // above array of menu commands, so this must come after we initialize the array. // IEventHandlerService ehs = (IEventHandlerService)host.GetService(typeof(IEventHandlerService)); if (ehs != null) { ehs.PushHandler(this); } // We sync add, remove and change events so we remain in sync with any nastiness that the // form may pull on us. // IComponentChangeService cs = (IComponentChangeService)host.GetService(typeof(IComponentChangeService)); if (cs != null) { cs.ComponentAdded += new ComponentEventHandler(OnComponentAddRemove); cs.ComponentRemoved += new ComponentEventHandler(OnComponentAddRemove); cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); } }
// OLE DragDrop virtual methods /// <summary> /// OnDragDrop can be overridden so that a Behavior can specify its own Drag/Drop rules. /// </summary> public override void OnDragDrop(Glyph g, DragEventArgs e) { ToolStripItem currentDropItem = ToolStripDesigner.s_dragItem; // Ensure that the list item index is contained in the data. if (e.Data is ToolStripItemDataObject && currentDropItem != null) { ToolStripItemDataObject data = (ToolStripItemDataObject)e.Data; // Get the PrimarySelection before the Drag operation... ToolStripItem selectedItem = data.PrimarySelection; IDesignerHost designerHost = (IDesignerHost)currentDropItem.Site.GetService(typeof(IDesignerHost)); Debug.Assert(designerHost != null, "Invalid DesignerHost"); //Do DragDrop only if currentDropItem has changed. if (currentDropItem != selectedItem && designerHost != null) { ArrayList components = data.DragComponents; ToolStrip parentToolStrip = currentDropItem.GetCurrentParent() as ToolStrip; int primaryIndex = -1; string transDesc; bool copy = (e.Effect == DragDropEffects.Copy); if (components.Count == 1) { string name = TypeDescriptor.GetComponentName(components[0]); if (name == null || name.Length == 0) { name = components[0].GetType().Name; } transDesc = string.Format(copy ? SR.BehaviorServiceCopyControl : SR.BehaviorServiceMoveControl, name); } else { transDesc = string.Format(copy ? SR.BehaviorServiceCopyControls : SR.BehaviorServiceMoveControls, components.Count); } DesignerTransaction designerTransaction = designerHost.CreateTransaction(transDesc); try { IComponentChangeService changeSvc = (IComponentChangeService)currentDropItem.Site.GetService(typeof(IComponentChangeService)); if (changeSvc != null) { if (parentToolStrip is ToolStripDropDown dropDown) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]); } else { changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]); } } // If we are copying, then we want to make a copy of the components we are dragging if (copy) { // Remember the primary selection if we had one if (selectedItem != null) { primaryIndex = components.IndexOf(selectedItem); } ToolStripKeyboardHandlingService keyboardHandlingService = GetKeyBoardHandlingService(selectedItem); if (keyboardHandlingService != null) { keyboardHandlingService.CopyInProgress = true; } components = DesignerUtils.CopyDragObjects(components, currentDropItem.Site) as ArrayList; if (keyboardHandlingService != null) { keyboardHandlingService.CopyInProgress = false; } if (primaryIndex != -1) { selectedItem = components[primaryIndex] as ToolStripItem; } } if (e.Effect == DragDropEffects.Move || copy) { ISelectionService selSvc = GetSelectionService(currentDropItem); if (selSvc != null) { // Insert the item. if (parentToolStrip is ToolStripOverflow) { parentToolStrip = (((ToolStripOverflow)parentToolStrip).OwnerItem).Owner; } int indexOfItemUnderMouseToDrop = parentToolStrip.Items.IndexOf(ToolStripDesigner.s_dragItem); if (indexOfItemUnderMouseToDrop != -1) { int indexOfPrimarySelection = 0; if (selectedItem != null) { indexOfPrimarySelection = parentToolStrip.Items.IndexOf(selectedItem); } if (indexOfPrimarySelection != -1 && indexOfItemUnderMouseToDrop > indexOfPrimarySelection) { indexOfItemUnderMouseToDrop--; } foreach (ToolStripItem item in components) { parentToolStrip.Items.Insert(indexOfItemUnderMouseToDrop, item); } } selSvc.SetSelectedComponents(new IComponent[] { selectedItem }, SelectionTypes.Primary | SelectionTypes.Replace); } } if (changeSvc != null) { ToolStripDropDown dropDown = parentToolStrip as ToolStripDropDown; if (dropDown != null) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null); } else { changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null); } //fire extra changing/changed events. if (copy) { if (dropDown != null) { ToolStripItem ownerItem = dropDown.OwnerItem; changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]); changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null); } else { changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]); changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null); } } } //If Parent is DropDown... we have to manage the Glyphs .... foreach (ToolStripItem item in components) { if (item is ToolStripDropDownItem) { if (designerHost.GetDesigner(item) is ToolStripMenuItemDesigner itemDesigner) { itemDesigner.InitializeDropDown(); } } if (item.GetCurrentParent() is ToolStripDropDown dropDown && !(dropDown is ToolStripOverflow)) { if (dropDown.OwnerItem is ToolStripDropDownItem ownerItem) { if (designerHost.GetDesigner(ownerItem) is ToolStripMenuItemDesigner ownerDesigner) { ownerDesigner.InitializeBodyGlyphsForItems(false, ownerItem); ownerDesigner.InitializeBodyGlyphsForItems(true, ownerItem); } } } } // Refresh on SelectionManager... BehaviorService bSvc = GetBehaviorService(currentDropItem); if (bSvc != null) { bSvc.SyncSelection(); } } catch (Exception ex) { if (designerTransaction != null) { designerTransaction.Cancel(); designerTransaction = null; } if (ClientUtils.IsCriticalException(ex)) { throw; } } finally { if (designerTransaction != null) { designerTransaction.Commit(); designerTransaction = null; } } } } }
void LoadDesigner() { LoggingService.Info("Form Designer: BEGIN INITIALIZE"); DefaultServiceContainer serviceContainer = new DefaultServiceContainer(); serviceContainer.AddService(typeof(System.Windows.Forms.Design.IUIService), new UIService()); serviceContainer.AddService(typeof(System.Drawing.Design.IToolboxService), ToolboxProvider.ToolboxService); serviceContainer.AddService(typeof(IHelpService), new HelpService()); serviceContainer.AddService(typeof(System.Drawing.Design.IPropertyValueUIService), new PropertyValueUIService()); serviceContainer.AddService(typeof(System.ComponentModel.Design.IResourceService), new DesignerResourceService(this.resourceStore)); AmbientProperties ambientProperties = new AmbientProperties(); serviceContainer.AddService(typeof(AmbientProperties), ambientProperties); this.typeResolutionService = new TypeResolutionService(this.PrimaryFileName); serviceContainer.AddService(typeof(ITypeResolutionService), this.typeResolutionService); serviceContainer.AddService(typeof(DesignerOptionService), new SharpDevelopDesignerOptionService()); serviceContainer.AddService(typeof(ITypeDiscoveryService), new TypeDiscoveryService()); serviceContainer.AddService(typeof(MemberRelationshipService), new DefaultMemberRelationshipService()); serviceContainer.AddService(typeof(ProjectResourceService), new ProjectResourceService(ParserService.GetParseInformation(this.DesignerCodeFile.FileName).MostRecentCompilationUnit.ProjectContent)); // Provide the ImageResourceEditor for all Image and Icon properties this.addedTypeDescriptionProviders.Add(typeof(Image), TypeDescriptor.AddAttributes(typeof(Image), new EditorAttribute(typeof(ImageResourceEditor), typeof(System.Drawing.Design.UITypeEditor)))); this.addedTypeDescriptionProviders.Add(typeof(Icon), TypeDescriptor.AddAttributes(typeof(Icon), new EditorAttribute(typeof(ImageResourceEditor), typeof(System.Drawing.Design.UITypeEditor)))); if (generator.CodeDomProvider != null) { serviceContainer.AddService(typeof(System.CodeDom.Compiler.CodeDomProvider), generator.CodeDomProvider); } designSurface = CreateDesignSurface(serviceContainer); designSurface.Loading += this.DesignerLoading; designSurface.Loaded += this.DesignerLoaded; designSurface.Flushed += this.DesignerFlushed; designSurface.Unloading += this.DesignerUnloading; serviceContainer.AddService(typeof(System.ComponentModel.Design.IMenuCommandService), new ICSharpCode.FormsDesigner.Services.MenuCommandService(this.Control, designSurface)); ICSharpCode.FormsDesigner.Services.EventBindingService eventBindingService = new ICSharpCode.FormsDesigner.Services.EventBindingService(this, designSurface); serviceContainer.AddService(typeof(System.ComponentModel.Design.IEventBindingService), eventBindingService); this.loader = loaderProvider.CreateLoader(generator); designSurface.BeginLoad(this.loader); if (!designSurface.IsLoaded) { throw new FormsDesignerLoadException(FormatLoadErrors(designSurface)); } undoEngine = new FormsDesignerUndoEngine(Host); serviceContainer.AddService(typeof(UndoEngine), undoEngine); IComponentChangeService componentChangeService = (IComponentChangeService)designSurface.GetService(typeof(IComponentChangeService)); componentChangeService.ComponentChanged += ComponentChanged; componentChangeService.ComponentAdded += ComponentListChanged; componentChangeService.ComponentRemoved += ComponentListChanged; componentChangeService.ComponentRename += ComponentListChanged; this.Host.TransactionClosed += TransactionClose; ISelectionService selectionService = (ISelectionService)designSurface.GetService(typeof(ISelectionService)); selectionService.SelectionChanged += SelectionChangedHandler; if (IsTabOrderMode) // fixes SD2-1015 { tabOrderMode = false; // let ShowTabOrder call the designer command again ShowTabOrder(); } UpdatePropertyPad(); hasUnmergedChanges = false; LoggingService.Info("Form Designer: END INITIALIZE"); }
/// <summary> /// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// </summary> public override void SetValue(object component, object value) { // Argument, state checking. Is it ok to set this event? if (IsReadOnly) { Exception ex = new InvalidOperationException(string.Format(SR.EventBindingServiceEventReadOnly, Name)); ex.HelpLink = SR.EventBindingServiceEventReadOnly; throw ex; } if (value != null && !(value is string)) { Exception ex = new ArgumentException(string.Format(SR.EventBindingServiceBadArgType, Name, typeof(string).Name)); ex.HelpLink = SR.EventBindingServiceBadArgType; throw ex; } string name = (string)value; if (name != null && name.Length == 0) { name = null; } // Obtain the site for the component. Note that this can be a site // to a parent component if we can get to the reference service. ISite site = null; if (component is IComponent) { site = ((IComponent)component).Site; } if (site is null && (_eventSvc._provider.GetService(typeof(IReferenceService)) is IReferenceService rs)) { IComponent baseComponent = rs.GetComponent(component); if (baseComponent != null) { site = baseComponent.Site; } } if (site is null) { Exception ex = new InvalidOperationException(SR.EventBindingServiceNoSite); ex.HelpLink = SR.EventBindingServiceNoSite; throw ex; } // The dictionary service is where we store the actual event method name. if (!(site.GetService(typeof(IDictionaryService)) is IDictionaryService ds)) { Exception ex = new InvalidOperationException(string.Format(SR.EventBindingServiceMissingService, typeof(IDictionaryService).Name)); ex.HelpLink = SR.EventBindingServiceMissingService; throw ex; } // Get the old method name, ensure that they are different, and then continue. ReferenceEventClosure key = new ReferenceEventClosure(component, this); string oldName = (string)ds.GetValue(key); if (object.ReferenceEquals(oldName, name)) { return; } if (oldName != null && name != null && oldName.Equals(name)) { return; } // Before we continue our work, ensure that the name is actually valid. if (name != null) { _eventSvc.ValidateMethodName(name); } // If there is a designer host, create a transaction so there is a // nice name for this change. We don't want a name like // "Change property 'Click', because to users, this isn't a property. DesignerTransaction trans = null; if (site.GetService(typeof(IDesignerHost)) is IDesignerHost host) { trans = host.CreateTransaction(string.Format(SR.EventBindingServiceSetValue, site.Name, name)); } try { // Ok, the names are different. Fire a changing event to make // sure it's OK to perform the change. IComponentChangeService change = site.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (change != null) { try { change.OnComponentChanging(component, this); change.OnComponentChanging(component, Event); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } // Less chance of success of adding a new method name, so // don't release the old name until we verify that adding // the new one actually succeeded. if (name != null) { _eventSvc.UseMethod((IComponent)component, Event, name); } if (oldName != null) { _eventSvc.FreeMethod((IComponent)component, Event, oldName); } ds.SetValue(key, name); if (change != null) { change.OnComponentChanged(component, Event, null, null); change.OnComponentChanged(component, this, oldName, name); } OnValueChanged(component, EventArgs.Empty); if (trans != null) { trans.Commit(); } } finally { if (trans != null) { ((IDisposable)trans).Dispose(); } } }
public override bool EditComponent(ITypeDescriptorContext context, object component, IWin32Window owner) { DeluxeTree oControl = (DeluxeTree)component; IServiceProvider site = oControl.Site; IComponentChangeService changeService = null; DesignerTransaction transaction = null; bool changed = false; try { if (site != null) { IDesignerHost designerHost = (IDesignerHost)site.GetService(typeof(IDesignerHost)); transaction = designerHost.CreateTransaction("BuildMenu"); changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (changeService != null) { try { changeService.OnComponentChanging(component, null); } catch (CheckoutException ex) { if (ex == CheckoutException.Canceled) { return(false); } throw ex; } } } try { DeluxeTreeItemsEditorForm oEditorForm = new DeluxeTreeItemsEditorForm(oControl); if (oEditorForm.ShowDialog(owner) == DialogResult.OK) { changed = true; } } finally { if (changed && changeService != null) { changeService.OnComponentChanged(oControl, null, null, null); } } } finally { if (transaction != null) { if (changed) { transaction.Commit(); } else { transaction.Cancel(); } } } return(changed); }
// Settings paths taken from the example at: // http://msdn2.microsoft.com/en-us/library/system.componentmodel.design.idesigneroptionservice.aspx // public override void Initialize(IComponent component) { base.Initialize(component); this.Control.AllowDrop = true; // Initialize the default values of the Design-Time properties. // _defaultDrawGrid = true; _defaultSnapToGrid = true; _defaultGridSize = new Size(8, 8); // If the parent Control of the designed one has a ParentDesigner then inherit the values // from it's designer. // if (this.Control.Parent != null) { ParentControlDesigner parentDesigner = GetParentControlDesignerOf(Control.Parent); if (parentDesigner != null) { _defaultDrawGrid = (bool)GetValue(parentDesigner.Component, "DrawGrid"); _defaultSnapToGrid = (bool)GetValue(parentDesigner.Component, "SnapToGrid"); _defaultGridSize = (Size)GetValue(parentDesigner.Component, "GridSize"); } } else { // Else retrieve them through the IDesignerOptionService (if available) // IDesignerOptionService options = GetService(typeof(IDesignerOptionService)) as IDesignerOptionService; if (options != null) { object value = null; value = options.GetOptionValue(@"WindowsFormsDesigner\General", "DrawGrid"); if (value is bool) { _defaultDrawGrid = (bool)value; } value = options.GetOptionValue(@"WindowsFormsDesigner\General", "SnapToGrid"); if (value is bool) { _defaultSnapToGrid = (bool)value; } value = options.GetOptionValue(@"WindowsFormsDesigner\General", "GridSize"); if (value is Size) { _defaultGridSize = (Size)value; } } } IComponentChangeService componentChangeSvc = GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (componentChangeSvc != null) { componentChangeSvc.ComponentRemoving += new ComponentEventHandler(OnComponentRemoving); componentChangeSvc.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); } // At the end set whatever we've managed to get // _drawGrid = _defaultDrawGrid; _snapToGrid = _defaultSnapToGrid; _gridSize = _defaultGridSize; }
void CreateDesigner(bool New, string XmlCode) { ModUi.ResetEventHandlers(); //Create a new DesignSurface ModDesignSurface MDS = new ModDesignSurface(); MDS.SetUpSelectionService(); MDS.BeginLoad(typeof(Form)); IDH = (IDesignerHost)MDS.GetService(typeof(IDesignerHost)); try { IDH.RemoveService(typeof(ITypeDescriptorFilterService)); }catch {} try { IDH.RemoveService(typeof(IToolboxService)); }catch {} try { IDH.RemoveService(typeof(PropertyGrid)); }catch { } //Read XML and update the Form control if (!New) { ModCodeAndControlHolder Code = ModUiTools.XmlToCode(XmlCode, (Form)IDH.RootComponent); } //Panel P = (Panel)IDH.CreateComponent(typeof(Panel)); //P.Location = ModUiTools.GetLocationDefinition(20, 20); //P.Size = ModUiTools.GetSizeDefinition(100, 100); //Button B = (Button)IDH.CreateComponent(typeof(Button), "TestButton"); //B.Text = "123"; //P.Controls.Add(B); //P.Parent = (Form)IDH.RootComponent; try { this.BaseSplit.Panel2.Controls.RemoveAt(0); } catch { } Control C = MDS.View as Control; C.Parent = this.BaseSplit.Panel2; C.Dock = DockStyle.Fill; IDH.AddService(typeof(ITypeDescriptorFilterService), new CustomFilterService()); ModToolBox TB = new ModToolBox(); TB.Parent = this.ToolboxTab; TB.Dock = DockStyle.Fill; IDH.AddService(typeof(IToolboxService), TB); PropertyGrid PG = new PropertyGrid(); PG.Parent = this.PropertiesPropertySubTab; PG.Dock = DockStyle.Fill; IDH.AddService(typeof(PropertyGrid), PG); // Use ComponentChangeService to announce changing of the // Form's Controls collection */ IComponentChangeService ICC = (IComponentChangeService)IDH.GetService(typeof(IComponentChangeService)); ICC.OnComponentChanging(IDH.RootComponent, TypeDescriptor.GetProperties(IDH.RootComponent)["Controls"]); }
void SetAllEstimatedCounts(ToolBarButton button) { //grab the objects I need before the user has a chance to flip to another active window Project proj = ApplicationObject.ActiveWindow.Project; Window window = ApplicationObject.ActiveWindow; Cube cube = (Cube)this.ApplicationObject.ActiveWindow.ProjectItem.Object; IDesignerHost designer = (IDesignerHost)ApplicationObject.ActiveWindow.Object; if (MessageBox.Show("Updating all estimated counts with exact counts for all partitions and dimensions\r\ncould take an extremely long time.\r\n\r\nAre you sure you want to continue?", "BIDS Helper - Update All Estimated Counts", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } button.ImageIndex = button.Parent.ImageList.Images.IndexOfKey(STOP_ICON_KEY); //change to a stop icon to allow the user to cancel Application.DoEvents(); try { using (WaitCursor cursor1 = new WaitCursor()) { ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationGeneral); IComponentChangeService changesvc = (IComponentChangeService)designer.GetService(typeof(IComponentChangeService)); changesvc.OnComponentChanging(cube, null); System.Collections.Generic.List <string> errors = new System.Collections.Generic.List <string>(); int iProgress = 0; foreach (MeasureGroup mg in cube.MeasureGroups) { ApplicationObject.StatusBar.Progress(true, "Setting Estimated Counts on Measure Group: " + mg.Name, ++iProgress, cube.MeasureGroups.Count + cube.Parent.Dimensions.Count); if (mg.Partitions.Count > 0) { foreach (Partition p in mg.Partitions) { p.EstimatedRows = 0; } foreach (AggregationDesign aggd in mg.AggregationDesigns) { //make sure each measure group dimension and attribute is in each agg design... fixes issue 21220 foreach (MeasureGroupDimension mgd in mg.Dimensions) { if (mgd is RegularMeasureGroupDimension) { if (!aggd.Dimensions.Contains(mgd.CubeDimensionID)) { aggd.Dimensions.Add(mgd.CubeDimensionID); } AggregationDesignDimension aggdd = aggd.Dimensions[mgd.CubeDimensionID]; foreach (DimensionAttribute da in mgd.Dimension.Attributes) { if (da.AttributeHierarchyEnabled && mgd.CubeDimension.Attributes[da.ID].AttributeHierarchyEnabled && !aggdd.Attributes.Contains(da.ID)) { aggdd.Attributes.Add(da.ID); } } } } foreach (AggregationDesignDimension aggdim in aggd.Dimensions) { foreach (AggregationDesignAttribute attr in aggdim.Attributes) { try { attr.EstimatedCount = 0; attr.Attribute.EstimatedCount = 0; } catch { } } } foreach (MeasureGroupDimension mgd in mg.Dimensions) { if (mgd is RegularMeasureGroupDimension) { RegularMeasureGroupDimension dim = (RegularMeasureGroupDimension)mgd; foreach (Partition p in mg.Partitions) { if (p.AggregationDesignID == aggd.ID) { try { SetEstimatedCountsOnPartitionThreadInfo info = new SetEstimatedCountsOnPartitionThreadInfo(); info.instance = this; info.aggDesign = aggd; info.measureGroupDimension = dim; info.partition = p; //run as a separate thread so that the main app stays responsive (so you can click the cancel button) System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(StartSetEstimatedCountsOnPartition), info); while (!info.done) { System.Threading.Thread.Sleep(100); Application.DoEvents(); //keeps main app responsive if (CheckCancelled()) { return; } } errors.AddRange(info.errors); } catch (Exception ex) { errors.Add("BIDS Helper error setting estimated counts on partition " + p.Name + " of measure group " + mg.Name + ": " + ex.Message); } } } } } } //now fill in the count on partitions without agg designs foreach (Partition p in mg.Partitions) { if (p.AggregationDesign == null) { try { SetEstimatedCountsOnPartitionThreadInfo info = new SetEstimatedCountsOnPartitionThreadInfo(); info.instance = this; info.partition = p; //run as a separate thread so that the main app stays responsive (so you can click the cancel button) System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(StartSetEstimatedCountsOnPartition), info); while (!info.done) { System.Threading.Thread.Sleep(100); Application.DoEvents(); //keeps main app responsive if (CheckCancelled()) { return; } } errors.AddRange(info.errors); } catch (Exception ex) { errors.Add("BIDS Helper error setting estimated counts on partition " + p.Name + " of measure group " + mg.Name + ": " + ex.Message); } } } long iMeasureGroupRowsCount = 0; foreach (Partition p in mg.Partitions) { iMeasureGroupRowsCount += p.EstimatedRows; } mg.EstimatedRows = iMeasureGroupRowsCount; } } changesvc.OnComponentChanged(cube, null, null, null); //marks the cube designer as dirty foreach (ProjectItem pi in proj.ProjectItems) { try { if (!(pi.Object is Dimension)) { continue; } } catch { continue; //doing the above seems to blow up on certain objects because of threading? this fixes the problem } Dimension dim = (Dimension)pi.Object; ApplicationObject.StatusBar.Progress(true, "Setting Estimated Counts on Dimension: " + dim.Name, ++iProgress, cube.MeasureGroups.Count + cube.Parent.Dimensions.Count); //open but don't show the dimension designer so you can get at the change service so you can mark it dirty bool bIsOpen = pi.get_IsOpen(EnvDTE.Constants.vsViewKindDesigner); Window win = null; if (bIsOpen) { foreach (Window w in ApplicationObject.Windows) { if (w.ProjectItem != null && w.ProjectItem.Document != null && w.ProjectItem.Document.FullName == pi.Document.FullName) { win = w; break; } } } if (win == null) { win = pi.Open(EnvDTE.Constants.vsViewKindDesigner); if (!bIsOpen) { win.Visible = false; } } designer = (IDesignerHost)win.Object; changesvc = (IComponentChangeService)designer.GetService(typeof(IComponentChangeService)); changesvc.OnComponentChanging(dim, null); if (dim.DataSource != null) { try { DataSourceConnection openedDataSourceConnection = DSVUtilities.GetOpenedDataSourceConnection(dim.DataSource); foreach (DimensionAttribute attr in dim.Attributes) { SetEstimatedCountsOnDimensionThreadInfo info = new SetEstimatedCountsOnDimensionThreadInfo(); info.instance = this; info.attribute = attr; info.connection = openedDataSourceConnection; //run as a separate thread so that the main app stays responsive (so you can click the cancel button) System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(StartSetEstimatedCountsOnDimension), info); while (!info.done) { System.Threading.Thread.Sleep(100); Application.DoEvents(); //keeps main app responsive if (CheckCancelled()) { return; } } errors.AddRange(info.errors); } } catch (Exception ex) { errors.Add("BIDS Helper error setting estimated counts on dimension " + dim.Name + ": " + ex.Message); } } changesvc.OnComponentChanged(dim, null, null, null); } AddErrorsToVSErrorList(window, errors.ToArray()); } } finally { try { button.ImageIndex = button.Parent.ImageList.Images.IndexOfKey(SET_ESTIMATED_COUNTS_ICON_KEY); ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationGeneral); ApplicationObject.StatusBar.Progress(false, "", 1, 1); } catch { } } }
private void LoadDesigner(Stream stream) { LoggingService.Info("Form Designer: BEGIN INITIALIZE"); defaultServiceContainer = new DefaultServiceContainer(); defaultServiceContainer.AddService(typeof(System.Windows.Forms.Design.IUIService), new UIService()); defaultServiceContainer.AddService(typeof(IToolboxService), new ToolboxService()); defaultServiceContainer.AddService(typeof(IHelpService), new HelpService()); this.designSurface = CreateDesignSurface(defaultServiceContainer); designSurface.Loading += this.DesignerLoading; designSurface.Loaded += this.DesignerLoaded; designSurface.Flushed += this.DesignerFlushed; designSurface.Unloading += this.DesingerUnloading; AmbientProperties ambientProperties = new AmbientProperties(); defaultServiceContainer.AddService(typeof(AmbientProperties), ambientProperties); defaultServiceContainer.AddService(typeof(ITypeResolutionService), new TypeResolutionService()); defaultServiceContainer.AddService(typeof(ITypeDiscoveryService), new TypeDiscoveryService()); defaultServiceContainer.AddService(typeof(System.ComponentModel.Design.IMenuCommandService), new MenuCommandService(panel, this.designSurface)); defaultServiceContainer.AddService(typeof(MemberRelationshipService), new DefaultMemberRelationshipService()); //need this to resolve the filename and manipulate //ReportSettings in ReportDefinitionDeserializer.LoadObjectFromXmlDocument //if the filename in ReportSettings is different from load location defaultServiceContainer.AddService(typeof(OpenedFile), base.PrimaryFile); DesignerOptionService dos = new System.Windows.Forms.Design.WindowsFormsDesignerOptionService(); dos.Options.Properties.Find("UseSmartTags", true).SetValue(dos, true); dos.Options.Properties.Find("ShowGrid", true).SetValue(dos, false); dos.Options.Properties.Find("UseSnapLines", true).SetValue(dos, true); defaultServiceContainer.AddService(typeof(DesignerOptionService), dos); this.loader = new ReportDesignerLoader(generator, stream); this.designSurface.BeginLoad(this.loader); if (!designSurface.IsLoaded) { throw new FormsDesignerLoadException(FormatLoadErrors(designSurface)); } defaultServiceContainer.AddService(typeof(System.ComponentModel.Design.Serialization.INameCreationService), new NameCreationService()); ISelectionService selectionService = (ISelectionService)this.designSurface.GetService(typeof(ISelectionService)); selectionService.SelectionChanged += SelectionChangedHandler; undoEngine = new ReportDesignerUndoEngine(Host); IComponentChangeService componentChangeService = (IComponentChangeService)this.designSurface.GetService(typeof(IComponentChangeService)); componentChangeService.ComponentChanged += OnComponentChanged; componentChangeService.ComponentAdded += OnComponentListChanged; componentChangeService.ComponentRemoved += OnComponentListChanged; componentChangeService.ComponentRename += OnComponentListChanged; this.Host.TransactionClosed += TransactionClose; UpdatePropertyPad(); hasUnmergedChanges = false; LoggingService.Info("Form Designer: END INITIALIZE"); }
public override void SetValue(object component, object value) { if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Raise the OnComponentChanging event changeService.OnComponentChanging(component, this); // Save the old value object oldValue = GetValue(component); try { WorkflowParameterBindingCollection parameters = GetParameters(component); if (parameters != null) { if (value == null) { // Remove the binding from the ParameterBindings collection parameters.Remove(this.Name); } else { // Add the binding to the ParameterBindings collection WorkflowParameterBinding binding = null; if (parameters.Contains(this.Name)) { binding = parameters[this.Name]; } else { binding = new WorkflowParameterBinding(this.Name); parameters.Add(binding); } // Set the binding value on the ParameterBindings collection correspondent binding item if (value is ActivityBind) { binding.SetBinding(WorkflowParameterBinding.ValueProperty, value as ActivityBind); } else { binding.SetValue(WorkflowParameterBinding.ValueProperty, value); } } } // Raise the OnValueChanged event OnValueChanged(component, EventArgs.Empty); } catch (Exception) { value = oldValue; throw; } finally { if (changeService != null) { // Raise the OnComponentChanged event changeService.OnComponentChanged(component, this, oldValue, value); } } } }
// Called by the host when we load a document. protected override void PerformLoad(IDesignerSerializationManager designerSerializationManager) { this.host = this.LoaderHost; if (host == null) { throw new ArgumentNullException("BasicHostLoader.BeginLoad: Invalid designerLoaderHost."); } // The loader will put error messages in here. ArrayList errors = new ArrayList(); bool successful = true; string baseClassName; // If no filename was passed in, just create a form and be done with it. If a file name // was passed, read it. if (fileName == null) { host.CreateComponent(rootComponentType); baseClassName = rootComponentType.Name; //if (rootComponentType == typeof(Form)) //{ // host.CreateComponent(typeof(Form)); // baseClassName = "Form1"; //} //else if (rootComponentType == typeof(UserControl)) //{ // host.CreateComponent(typeof(UserControl)); // baseClassName = "UserControl1"; //} //else if (rootComponentType == typeof(Component)) //{ // host.CreateComponent(typeof(Component)); // baseClassName = "Component1"; //} //else //{ // throw new Exception("Undefined Host Type: " + rootComponentType.ToString()); //} } else { baseClassName = ReadFile(fileName, errors, out xmlDocument); } // Now that we are done with the load work, we need to begin to listen to events. // Listening to event notifications is how a designer "Loader" can also be used // to save data. If we wanted to integrate this loader with source code control, // we would listen to the "ing" events as well as the "ed" events. IComponentChangeService cs = host.GetService(typeof(IComponentChangeService)) as IComponentChangeService; if (cs != null) { cs.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); cs.ComponentAdded += new ComponentEventHandler(OnComponentAddedRemoved); cs.ComponentRemoved += new ComponentEventHandler(OnComponentAddedRemoved); } // Let the host know we are done loading. host.EndLoad(baseClassName, successful, errors); // We've just loaded a document, so you can bet we need to flush changes. dirty = true; unsaved = false; }
/// <summary> /// Adds inherited components to the <see cref="InheritanceService"/>. /// </summary> protected virtual void AddInheritedComponents(Type type, IComponent component, IContainer container) { // We get out now if this component type is not assignable from IComponent. We only walk down to the component level. if (type is null || !typeof(IComponent).IsAssignableFrom(type)) { return; } Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Searching for inherited components on '" + type.FullName + "'."); Debug.Indent(); ISite site = component.Site; IComponentChangeService cs = null; INameCreationService ncs = null; if (site is not null) { ncs = (INameCreationService)site.GetService(typeof(INameCreationService)); cs = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (cs is not null) { cs.ComponentAdding += new ComponentEventHandler(OnComponentAdding); } } try { while (type != typeof(object)) { Type reflect = TypeDescriptor.GetReflectionType(type); FieldInfo[] fields = reflect.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic); Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found " + fields.Length.ToString(CultureInfo.InvariantCulture) + " fields."); for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; string name = field.Name; // Get out now if this field is not assignable from IComponent. Type reflectionType = GetReflectionTypeFromTypeHelper(field.FieldType); if (!GetReflectionTypeFromTypeHelper(typeof(IComponent)).IsAssignableFrom(reflectionType)) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Not IComponent"); continue; } // Now check the attributes of the field and get out if it isn't something that can be inherited. Debug.Assert(!field.IsStatic, "Instance binding shouldn't have found this field"); // If the value of the field is null, then don't mess with it. If it wasn't assigned when our base class was created then we can't really use it. object value = field.GetValue(component); if (value is null) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...skipping " + name + ": Contains NULL"); continue; } // We've been fine up to this point looking at the field. Now, however, we must check to see if this field has an AccessedThroughPropertyAttribute on it. If it does, then we must look for the property and use its name and visibility for the remainder of the scan. Should any of this bail we just use the field. MemberInfo member = field; object[] fieldAttrs = field.GetCustomAttributes(typeof(AccessedThroughPropertyAttribute), false); if (fieldAttrs is not null && fieldAttrs.Length > 0) { Debug.Assert(fieldAttrs.Length == 1, "Non-inheritable attribute has more than one copy"); Debug.Assert(fieldAttrs[0] is AccessedThroughPropertyAttribute, "Reflection bug: GetCustomAttributes(type) didn't discriminate by type"); AccessedThroughPropertyAttribute propAttr = (AccessedThroughPropertyAttribute)fieldAttrs[0]; PropertyInfo fieldProp = reflect.GetProperty(propAttr.PropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Debug.Assert(fieldProp is not null, "Field declared with AccessedThroughPropertyAttribute has no associated property"); Debug.Assert(fieldProp.PropertyType == field.FieldType, "Field declared with AccessedThroughPropertyAttribute is associated with a property with a different return type."); if (fieldProp is not null && fieldProp.PropertyType == field.FieldType) { // If the property cannot be read, it is useless to us. if (!fieldProp.CanRead) { continue; } // We never access the set for the property, so we can concentrate on just the get method. member = fieldProp.GetGetMethod(true); Debug.Assert(member is not null, "GetGetMethod for property didn't return a method, but CanRead is true"); name = propAttr.PropertyName; } } // Add a user hook to add or remove members. The default hook here ignores all inherited private members. bool ignoreMember = IgnoreInheritedMember(member, component); // We now have an inherited member. Gather some information about it and then add it to our list. We must always add to our list, but we may not want to add it to the container. That is up to the IgnoreInheritedMember method. We add here because there are components in the world that, when sited, add their children to the container too. That's fine, but we want to make sure we account for them in the inheritance service too. Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "...found inherited member '" + name + "'"); Debug.Indent(); Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Type: " + field.FieldType.FullName); InheritanceAttribute attr; Debug.Assert(value is IComponent, "Value of inherited field is not IComponent. How did this value get into the datatype?"); bool privateInherited = false; if (ignoreMember) { // If we are ignoring this member, then always mark it as private. The designer doesn't want it; we only do this in case some other component adds this guy to the container. privateInherited = true; } else { if (member is FieldInfo fi) { privateInherited = fi.IsPrivate | fi.IsAssembly; } else if (member is MethodInfo mi) { privateInherited = mi.IsPrivate | mi.IsAssembly; } } if (privateInherited) { attr = InheritanceAttribute.InheritedReadOnly; Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Private"); } else { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Inheritance: Public"); attr = InheritanceAttribute.Inherited; } bool notPresent = (_inheritedComponents[value] is null); _inheritedComponents[value] = attr; if (!ignoreMember && notPresent) { Debug.WriteLineIf(s_inheritanceServiceSwitch.TraceVerbose, "Adding " + name + " to container."); try { _addingComponent = (IComponent)value; _addingAttribute = attr; // Lets make sure this is a valid name if (ncs is null || ncs.IsValidName(name)) { try { container.Add((IComponent)value, name); } catch { // We do not always control the base components, and there could be a lot of rogue base components. If there are exceptions when adding them, lets just ignore and continue. } } } finally { _addingComponent = null; _addingAttribute = null; } } Debug.Unindent(); } type = type.BaseType; } } finally { if (cs is not null) { cs.ComponentAdding -= new ComponentEventHandler(OnComponentAdding); } Debug.Unindent(); } }
private void buttonOK_Click(object sender, EventArgs e) { if (this.InvokeRequired) { //important to show the notification on the main thread of BIDS this.BeginInvoke(new MethodInvoker(delegate() { buttonOK_Click(sender, e); })); } else { try { EnvDTE.Window w = projItem.Open(BIDSViewKinds.Designer); //opens the designer IDesignerHost designer = (IDesignerHost)w.Object; IComponentChangeService changesvc = (IComponentChangeService)designer.GetService(typeof(IComponentChangeService)); changesvc.OnComponentChanging(this.cloneCube, null); dirtiedDimensions = new List <Microsoft.AnalysisServices.Dimension>(); //enable attributes foreach (TreeNode nodeDimension in treeViewAggregation.Nodes) { foreach (TreeNode nodeAttribute in nodeDimension.Nodes) { if (!nodeAttribute.Checked) { CubeAttribute ca = (CubeAttribute)nodeAttribute.Tag; ca.AttributeHierarchyOptimizedState = OptimizationType.FullyOptimized; //if you're trying to enable indexes, make sure the dimension hierarchy is optimized, since you can't make the cube attribute optimized if the dimension attribute isn't if (ca.Attribute.AttributeHierarchyOptimizedState == OptimizationType.NotOptimized) { if (!dirtiedDimensions.Contains(ca.Attribute.Parent)) { foreach (EnvDTE.ProjectItem pi in projItem.ContainingProject.ProjectItems) { if (!(pi.Object is Microsoft.AnalysisServices.Dimension)) { continue; } if ((Microsoft.AnalysisServices.Dimension)pi.Object != ca.Attribute.Parent) { continue; } bool bIsOpen = pi.get_IsOpen(EnvDTE.Constants.vsViewKindDesigner); EnvDTE.Window win = null; if (bIsOpen) { foreach (EnvDTE.Window w2 in projItem.DTE.Windows) { if (w2.ProjectItem != null && w2.ProjectItem.Document != null && w2.ProjectItem.Document.FullName == pi.Document.FullName) { win = w2; break; } } } if (win == null) { win = pi.Open(EnvDTE.Constants.vsViewKindDesigner); if (!bIsOpen) { win.Visible = false; } } IDesignerHost dimdesigner = (IDesignerHost)win.Object; IComponentChangeService dimchangesvc = (IComponentChangeService)dimdesigner.GetService(typeof(IComponentChangeService)); dimchangesvc.OnComponentChanging(ca.Attribute.Parent, null); //perform the update ca.Attribute.AttributeHierarchyOptimizedState = OptimizationType.FullyOptimized; dimchangesvc.OnComponentChanged(ca.Attribute.Parent, null, null, null); //marks the dimension designer as dirty } dirtiedDimensions.Add(ca.Attribute.Parent); } else { ca.Attribute.AttributeHierarchyOptimizedState = OptimizationType.FullyOptimized; } } } else { CubeAttribute ca = (CubeAttribute)nodeAttribute.Tag; ca.AttributeHierarchyOptimizedState = OptimizationType.NotOptimized; //if you're trying to disable indexes, make sure the hierarchy isn't set to optimized foreach (CubeHierarchy ch in ca.Parent.Hierarchies) { foreach (Microsoft.AnalysisServices.Level l in ch.Hierarchy.Levels) { if (l.SourceAttributeID == ca.AttributeID && ch.Enabled) { ch.OptimizedState = OptimizationType.NotOptimized; } } } } } } changesvc.OnComponentChanged(this.cloneCube, null, null, null); //marks the cube designer as dirty this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { if (!string.IsNullOrEmpty(ex.Message)) { MessageBox.Show("Error saving: " + ex.Message); } } } }
/// <summary> /// Demand populates the _references variable. /// </summary> private void EnsureReferences() { // If the references are null, create them for the first time and connect up our events to listen to changes to the container. Otherwise, check to see if the added or removed lists contain anything for us to sync up. if (_references == null) { if (_provider == null) { throw new ObjectDisposedException("IReferenceService"); } IComponentChangeService cs = _provider.GetService(typeof(IComponentChangeService)) as IComponentChangeService; Debug.Assert(cs != null, "Reference service relies on IComponentChangeService"); if (cs != null) { cs.ComponentAdded += new ComponentEventHandler(OnComponentAdded); cs.ComponentRemoved += new ComponentEventHandler(OnComponentRemoved); cs.ComponentRename += new ComponentRenameEventHandler(OnComponentRename); } if (!(_provider.GetService(typeof(IContainer)) is IContainer container)) { Debug.Fail("Reference service cannot operate without IContainer"); throw new InvalidOperationException(); } _references = new ArrayList(container.Components.Count); foreach (IComponent component in container.Components) { CreateReferences(component); } } else if (!_populating) { _populating = true; try { if (_addedComponents != null && _addedComponents.Count > 0) { // There is a possibility that this component already exists. If it does, just remove it first and then re-add it. foreach (IComponent ic in _addedComponents) { RemoveReferences(ic); CreateReferences(ic); } _addedComponents.Clear(); } if (_removedComponents != null && _removedComponents.Count > 0) { foreach (IComponent ic in _removedComponents) { RemoveReferences(ic); } _removedComponents.Clear(); } } finally { _populating = false; } } }
/// <summary> /// Set the new binding for an event /// </summary> /// <param name="component"></param> /// <param name="value"></param> public override void SetValue(object component, object value) { DependencyObject dependencyObject = component as DependencyObject; String eventHandlerName = value as String; if (dependencyObject == null || _eventProperty == null) { return; } //is an event handler already defined for this event? String currentHandlerName = String.Empty; if (dependencyObject.IsBindingSet(_eventProperty)) { currentHandlerName = dependencyObject.GetBinding(_eventProperty).Path; } //the handler name is the same so just get out now if (eventHandlerName == currentHandlerName) { return; } IDesignerHost designerHost = _serviceProvider.GetService( typeof(IDesignerHost)) as IDesignerHost; //use the IComponentChangeService to notify the //designer of the change IComponentChangeService changeService = _serviceProvider.GetService( typeof(IComponentChangeService)) as IComponentChangeService; if (changeService != null) { //notify that the component is changing changeService.OnComponentChanging( component, _eventDescriptor); } //set or remove the binding String bindingName = String.Empty; if (eventHandlerName == null || eventHandlerName == "[Clear]") { //remove the old binding dependencyObject.RemoveProperty(_eventProperty); } else { //Add a new ActivityBind object to the component ActivityBind bind = new ActivityBind( ((Activity)designerHost.RootComponent).Name, eventHandlerName); dependencyObject.SetBinding(_eventProperty, bind); } if (changeService != null) { //notify that the component has changed changeService.OnComponentChanged( component, _eventDescriptor, currentHandlerName, bindingName); } }
/// <summary> /// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// </summary> public override void SetValue(object component, object value) { Debug.WriteLine($"[{Name}]: SetValue({component?.GetType().Name ?? "(null)"}, {value?.GetType().Name ?? "(null)"})"); if (component != null) { ISite site = GetSite(component); object oldValue = null; object invokee = GetInvocationTarget(_componentClass, component); if (!IsReadOnly) { IComponentChangeService changeService = null; // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events if (changeService != null) { oldValue = GetMethodValue.Invoke(invokee, null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } try { try { SetMethodValue.Invoke(invokee, new object[] { value }); OnValueChanged(invokee, EventArgs.Empty); } catch (Exception t) { // Give ourselves a chance to unwind properly before rethrowing the exception. // value = oldValue; // If there was a problem setting the controls property then we get: // ArgumentException (from properties set method) // ==> Becomes inner exception of TargetInvocationException // ==> caught here if (t is TargetInvocationException && t.InnerException != null) { // Propagate the original exception up throw t.InnerException; } else { throw; } } } finally { // Now notify the change service that the change was successful. changeService?.OnComponentChanged(component, this, oldValue, value); } } } }
/// <summary> /// This adds the delegate value as a listener to when this event is fired /// by the component, invoking the addOnXXX method. /// </summary> public override void AddEventHandler(object component, Delegate value) { FillMethods(); if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } if (changeService != null) { try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } changeService.OnComponentChanging(component, this); } bool shadowed = false; if (site != null && site.DesignMode) { // Events are final, so just check the class if (EventType != value.GetType()) { throw new ArgumentException(SR.Format(SR.ErrorInvalidEventHandler, Name)); } IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService)); if (dict != null) { Delegate eventdesc = (Delegate)dict.GetValue(this); eventdesc = Delegate.Combine(eventdesc, value); dict.SetValue(this, eventdesc); shadowed = true; } } if (!shadowed) { _addMethod.Invoke(component, new[] { value }); } // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, this, null, value); } } }
/// Edits the specified value using the specified provider within the specified context. public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if (provider == null) { return(value); } IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc == null) { return(value); } DataGridViewCellStyle dgvCellStyle = context.Instance as DataGridViewCellStyle; ListControl listControl = context.Instance as ListControl; Debug.Assert(listControl != null || dgvCellStyle != null, "this editor is used for the DataGridViewCellStyle::Format and the ListControl::FormatString properties"); Application.SetHighDpiMode(HighDpiMode.SystemAware); if (_formatStringDialog == null) { _formatStringDialog = new FormatStringDialog(context); } if (listControl != null) { _formatStringDialog.ListControl = listControl; } else { _formatStringDialog.DataGridViewCellStyle = dgvCellStyle; } IComponentChangeService changeSvc = (IComponentChangeService)provider.GetService(typeof(IComponentChangeService)); if (changeSvc != null) { if (dgvCellStyle != null) { changeSvc.OnComponentChanging(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["Format"]); changeSvc.OnComponentChanging(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["NullValue"]); changeSvc.OnComponentChanging(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["FormatProvider"]); } else { changeSvc.OnComponentChanging(listControl, TypeDescriptor.GetProperties(listControl)["FormatString"]); changeSvc.OnComponentChanging(listControl, TypeDescriptor.GetProperties(listControl)["FormatInfo"]); } } edSvc.ShowDialog(_formatStringDialog); _formatStringDialog.End(); if (!_formatStringDialog.Dirty) { return(value); } // since the bindings may have changed, the properties listed in the properties window need to be refreshed TypeDescriptor.Refresh(context.Instance); if (changeSvc != null) { if (dgvCellStyle != null) { changeSvc.OnComponentChanged(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["Format"], null, null); changeSvc.OnComponentChanged(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["NullValue"], null, null); changeSvc.OnComponentChanged(dgvCellStyle, TypeDescriptor.GetProperties(dgvCellStyle)["FormatProvider"], null, null); } else { changeSvc.OnComponentChanged(listControl, TypeDescriptor.GetProperties(listControl)["FormatString"], null, null); changeSvc.OnComponentChanged(listControl, TypeDescriptor.GetProperties(listControl)["FormatInfo"], null, null); } } return(value); }
/// <summary> /// this method is called when dragging a TabStrip off the toolbox. /// </summary> /// <param name="host"></param> /// <returns></returns> protected override IComponent[] CreateComponentsCore(IDesignerHost host) { IComponent[] components = base.CreateComponentsCore(host); Control parentControl = null; ControlDesigner parentControlDesigner = null; TabStrip tabStrip = null; IComponentChangeService changeSvc = (IComponentChangeService)host.GetService(typeof(IComponentChangeService)); // fish out the parent we're adding the TabStrip to. if (components.Length > 0 && components[0] is TabStrip) { tabStrip = components[0] as TabStrip; ITreeDesigner tabStripDesigner = host.GetDesigner(tabStrip) as ITreeDesigner; parentControlDesigner = tabStripDesigner.Parent as ControlDesigner; if (parentControlDesigner != null) { parentControl = parentControlDesigner.Control; } } // Create a ControlSwitcher on the same parent. if (host != null) { TabPageSwitcher controlSwitcher = null; DesignerTransaction t = null; try { try { t = host.CreateTransaction("add tabswitcher"); } catch (CheckoutException ex) { if (ex == CheckoutException.Canceled) { return(components); } throw ex; } // create a TabPageSwitcher and add it to the same parent as the TabStrip MemberDescriptor controlsMember = TypeDescriptor.GetProperties(parentControlDesigner)["Controls"]; controlSwitcher = host.CreateComponent(typeof(TabPageSwitcher)) as TabPageSwitcher; if (changeSvc != null) { changeSvc.OnComponentChanging(parentControl, controlsMember); changeSvc.OnComponentChanged(parentControl, controlsMember, null, null); } // specify default values for our TabStrip Dictionary <string, object> propertyValues = new Dictionary <string, object>(); propertyValues["Location"] = new Point(tabStrip.Left, tabStrip.Bottom + 3); propertyValues["TabStrip"] = tabStrip; // set the property values SetProperties(controlSwitcher, propertyValues, host); } finally { if (t != null) { t.Commit(); } } // add the TabPageSwitcher to the list of components that we've created if (controlSwitcher != null) { IComponent[] newComponents = new IComponent[components.Length + 1]; Array.Copy(components, newComponents, components.Length); newComponents[newComponents.Length - 1] = controlSwitcher; return(newComponents); } } return(components); }
/// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. public override void SetValue(object component, object value) { // Argument, state checking. Is it ok to set this event? // if (IsReadOnly) { Exception ex = new InvalidOperationException("Tried to set a read only event."); throw ex; } if (value != null && !(value is string)) { Exception ex = new ArgumentException("Cannot set to value " + value.ToString() + "."); throw ex; } string name = (string)value; if (name != null && name.Length == 0) { name = null; } // Obtain the site for the component. Note that this can be a site // to a parent component if we can get to the reference service. // ISite site = null; if (component is IComponent) { site = ((IComponent)component).Site; } if (site == null) { IReferenceService rs = _eventSvc._provider.GetService(typeof(IReferenceService)) as IReferenceService; if (rs != null) { IComponent baseComponent = rs.GetComponent(component); if (baseComponent != null) { site = baseComponent.Site; } } } if (site == null) { Exception ex = new InvalidOperationException("There is no site for component " + component.ToString() + "."); throw ex; } // The dictionary service is where we store the actual event method name. // IDictionaryService ds = (IDictionaryService)site.GetService(typeof(IDictionaryService)); if (ds == null) { Exception ex = new InvalidOperationException("Cannot find IDictionaryService"); throw ex; } // Get the old method name, ensure that they are different, and then continue. // ReferenceEventClosure key = new ReferenceEventClosure(component, this); string oldName = (string)ds.GetValue(key); if (object.ReferenceEquals(oldName, name)) { return; } if (oldName != null && name != null && oldName.Equals(name)) { return; } // Before we continue our work, ensure that the name is // actually valid. // if (name != null) { _eventSvc.ValidateMethodName(name); } // Ok, the names are different. Fire a changing event to make // sure it's OK to perform the change. // IComponentChangeService change = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); if (change != null) { try { change.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } // Less chance of success of adding a new method name, so // don't release the old name until we verify that adding // the new one actually succeeded. // if (name != null) { _eventSvc.UseMethod(component, _eventDesc, name); } if (oldName != null) { _eventSvc.FreeMethod(component, _eventDesc, oldName); } ds.SetValue(key, name); if (change != null) { change.OnComponentChanged(component, this, oldName, name); } OnValueChanged(component, EventArgs.Empty); }