Update Reference Sources to .NET Framework 4.6.1
[mono.git] / mcs / class / referencesource / System.Workflow.ComponentModel / AuthoringOM / Design / Dialogs / TypeBrowserDialog.cs
1 namespace System.Workflow.ComponentModel.Design
2 {
3     using System;
4     using System.IO;
5     using System.Drawing;
6     using System.Resources;
7     using System.Diagnostics;
8     using System.Collections;
9     using System.Collections.Generic;
10     using System.Windows.Forms;
11     using System.ComponentModel;
12     using System.ComponentModel.Design;
13     using System.Reflection;
14     using System.Collections.Specialized;
15     using System.Windows.Forms.Design;
16     using System.Drawing.Design;
17     using System.Workflow.ComponentModel.Design;
18     using System.Workflow.ComponentModel.Compiler;
19     using System.Workflow.Interop;
20     using System.Text;
21     using System.Globalization;
22     using Microsoft.Win32;
23     using System.Security.Permissions;
24     using System.Diagnostics.CodeAnalysis;
25
26     [Obsolete("The System.Workflow.* types are deprecated.  Instead, please use the new types from System.Activities.*")]
27     public sealed class TypeBrowserDialog : Form, ISite
28     {
29         private static ResourceManager ResMgr;
30
31         private IServiceProvider serviceProvider;
32         private TypeProvider localTypeProvider;
33         private ImageList artifactImages;
34         private string selectedTypeName;
35         private IntPtr bitmapSortUp;
36         private IntPtr bitmapSortDown;
37         private HelpTextWindow helpTextWindow;
38         private ITypeFilterProvider typeFilterProvider;
39         private bool sortListViewAscending;
40         private bool refreshTreeView;
41         private bool refreshTypeTextBox;
42         private string lastComboboxValue = null;
43         private Type selectedType = null;
44         private GenericParameters genericParameters = new GenericParameters();
45
46         #region Designer Generated Variables
47
48         private System.Windows.Forms.Button buttonCancel;
49         private System.Windows.Forms.Button buttonOK;
50         private System.Windows.Forms.TextBox helpTextHolder;
51         private System.Windows.Forms.TabControl tabControl;
52         private TabPage typeTabPage;
53         private TabPage advancedTabPage;
54         private TextBox typeTextBox;
55         private Button buttonBrowse;
56         private PropertyGrid genericParametersPropertyGrid;
57         private TableLayoutPanel okCancelTableLayoutPanel;
58         private TableLayoutPanel typeNameTableLayoutPanel;
59         private TextBox artifactLabel;
60         private SplitContainer typeSplitContainer;
61         private TreeView artifactTreeView;
62         private ListView artifactListView;
63         private ColumnHeader typeName;
64         private ColumnHeader fullyQualifiedName;
65         private Label typeNameLabel;
66         #endregion
67
68         #region Construction and Destruction
69         static TypeBrowserDialog()
70         {
71             TypeBrowserDialog.ResMgr = new ResourceManager("System.Workflow.ComponentModel.Design.ArtifactReference", System.Reflection.Assembly.GetExecutingAssembly());
72         }
73
74         public TypeBrowserDialog(IServiceProvider serviceProvider, ITypeFilterProvider filterProvider, string selectedTypeName, TypeProvider typeProvider)
75         {
76             if (serviceProvider == null)
77                 throw new ArgumentNullException("serviceProvider");
78
79             this.localTypeProvider = typeProvider;
80             this.serviceProvider = serviceProvider;
81             // Load assemblies specified in the registry
82             Helpers.AddTypeProviderAssembliesFromRegistry(this.localTypeProvider, serviceProvider);
83
84             InitializeDialog(serviceProvider, filterProvider, selectedTypeName);
85
86             this.buttonBrowse.Visible = true;
87             this.buttonBrowse.Enabled = true;
88             this.buttonBrowse.BringToFront();
89         }
90
91         public TypeBrowserDialog(IServiceProvider serviceProvider, ITypeFilterProvider filterProvider, string selectedTypeName)
92         {
93             if (serviceProvider == null)
94                 throw new ArgumentNullException("serviceProvider");
95
96             InitializeDialog(serviceProvider, filterProvider, selectedTypeName);
97         }
98
99         internal void InitializeDialog(IServiceProvider serviceProvider, ITypeFilterProvider filterProvider, string selectedTypeName)
100         {
101             this.serviceProvider = serviceProvider;
102             this.sortListViewAscending = true;
103             this.refreshTreeView = false;
104             this.refreshTypeTextBox = false;
105             this.selectedTypeName = selectedTypeName;
106             this.typeFilterProvider = filterProvider;
107
108             IDesignerHost designerHost = this.serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
109             WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
110             if (designerHost == null || designerHost.RootComponent == null || loader == null || loader.InDebugMode)
111                 throw new Exception(DR.GetString(DR.Error_WorkflowNotLoaded));
112
113             InitializeComponent();
114             CustomInitializeComponent();
115
116             this.genericParametersPropertyGrid.Site = new DummySite(this.serviceProvider);
117         }
118
119         protected override void Dispose(bool disposing)
120         {
121             base.Dispose(disposing);
122         }
123         #endregion
124
125         #region Designer Generated Code
126         /// <summary>
127         /// Required method for Designer support - do not modify
128         /// the contents of this method with the code editor OR WITH THE DESIGNER.
129         /// </summary>
130         private void InitializeComponent()
131         {
132             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TypeBrowserDialog));
133             this.buttonCancel = new System.Windows.Forms.Button();
134             this.helpTextHolder = new System.Windows.Forms.TextBox();
135             this.buttonOK = new System.Windows.Forms.Button();
136             this.tabControl = new System.Windows.Forms.TabControl();
137             this.typeTabPage = new System.Windows.Forms.TabPage();
138             this.typeSplitContainer = new System.Windows.Forms.SplitContainer();
139             this.artifactTreeView = new System.Windows.Forms.TreeView();
140             this.artifactListView = new System.Windows.Forms.ListView();
141             this.typeName = new System.Windows.Forms.ColumnHeader();
142             this.fullyQualifiedName = new System.Windows.Forms.ColumnHeader();
143             this.advancedTabPage = new System.Windows.Forms.TabPage();
144             this.genericParametersPropertyGrid = new System.Windows.Forms.PropertyGrid();
145             this.buttonBrowse = new System.Windows.Forms.Button();
146             this.typeTextBox = new System.Windows.Forms.TextBox();
147             this.typeNameLabel = new System.Windows.Forms.Label();
148             this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
149             this.typeNameTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
150             this.artifactLabel = new System.Windows.Forms.TextBox();
151             this.tabControl.SuspendLayout();
152             this.typeTabPage.SuspendLayout();
153             this.typeSplitContainer.Panel1.SuspendLayout();
154             this.typeSplitContainer.Panel2.SuspendLayout();
155             this.typeSplitContainer.SuspendLayout();
156             this.advancedTabPage.SuspendLayout();
157             this.okCancelTableLayoutPanel.SuspendLayout();
158             this.typeNameTableLayoutPanel.SuspendLayout();
159             this.SuspendLayout();
160             // 
161             // buttonCancel
162             // 
163             resources.ApplyResources(this.buttonCancel, "buttonCancel");
164             this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
165             this.buttonCancel.Name = "buttonCancel";
166             // 
167             // helpTextHolder
168             // 
169             resources.ApplyResources(this.helpTextHolder, "helpTextHolder");
170             this.helpTextHolder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
171             this.helpTextHolder.Name = "helpTextHolder";
172             this.helpTextHolder.ReadOnly = true;
173             // 
174             // buttonOK
175             // 
176             resources.ApplyResources(this.buttonOK, "buttonOK");
177             this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
178             this.buttonOK.Name = "buttonOK";
179             this.buttonOK.Click += new System.EventHandler(this.OkButtonClicked);
180             // 
181             // tabControl
182             // 
183             resources.ApplyResources(this.tabControl, "tabControl");
184             this.tabControl.Controls.Add(this.typeTabPage);
185             this.tabControl.Controls.Add(this.advancedTabPage);
186             this.tabControl.Name = "tabControl";
187             this.tabControl.SelectedIndex = 0;
188             // 
189             // typeTabPage
190             // 
191             this.typeTabPage.BackColor = System.Drawing.Color.Transparent;
192             this.typeTabPage.Controls.Add(this.typeSplitContainer);
193             resources.ApplyResources(this.typeTabPage, "typeTabPage");
194             this.typeTabPage.Name = "typeTabPage";
195             // 
196             // typeSplitContainer
197             // 
198             this.typeSplitContainer.BackColor = System.Drawing.Color.Transparent;
199             resources.ApplyResources(this.typeSplitContainer, "typeSplitContainer");
200             this.typeSplitContainer.Name = "typeSplitContainer";
201             // 
202             // typeSplitContainer.Panel1
203             // 
204             this.typeSplitContainer.Panel1.Controls.Add(this.artifactTreeView);
205             // 
206             // typeSplitContainer.Panel2
207             // 
208             this.typeSplitContainer.Panel2.Controls.Add(this.artifactListView);
209             this.typeSplitContainer.TabStop = false;
210             // 
211             // artifactTreeView
212             // 
213             this.artifactTreeView.BackColor = System.Drawing.SystemColors.Window;
214             resources.ApplyResources(this.artifactTreeView, "artifactTreeView");
215             this.artifactTreeView.ItemHeight = 16;
216             this.artifactTreeView.Name = "artifactTreeView";
217             this.artifactTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.OnTreeSelectionChange);
218             this.artifactTreeView.GotFocus += new System.EventHandler(this.OnTreeViewGotFocus);
219             // 
220             // artifactListView
221             // 
222             this.artifactListView.AllowColumnReorder = true;
223             this.artifactListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
224             this.typeName,
225             this.fullyQualifiedName});
226             resources.ApplyResources(this.artifactListView, "artifactListView");
227             this.artifactListView.Name = "artifactListView";
228             this.artifactListView.UseCompatibleStateImageBehavior = false;
229             this.artifactListView.View = System.Windows.Forms.View.Details;
230             this.artifactListView.SelectedIndexChanged += new System.EventHandler(this.OnListViewSelectedIndexChanged);
231             this.artifactListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.OnListViewColumnClick);
232             // 
233             // typeName
234             // 
235             resources.ApplyResources(this.typeName, "typeName");
236             // 
237             // fullyQualifiedName
238             // 
239             resources.ApplyResources(this.fullyQualifiedName, "fullyQualifiedName");
240             // 
241             // advancedTabPage
242             // 
243             this.advancedTabPage.BackColor = System.Drawing.Color.Transparent;
244             this.advancedTabPage.Controls.Add(this.genericParametersPropertyGrid);
245             resources.ApplyResources(this.advancedTabPage, "advancedTabPage");
246             this.advancedTabPage.Name = "advancedTabPage";
247             // 
248             // genericParametersPropertyGrid
249             // 
250             resources.ApplyResources(this.genericParametersPropertyGrid, "genericParametersPropertyGrid");
251             this.genericParametersPropertyGrid.Name = "genericParametersPropertyGrid";
252             this.genericParametersPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.Categorized;
253             this.genericParametersPropertyGrid.ToolbarVisible = false;
254             // 
255             // buttonBrowse
256             // 
257             resources.ApplyResources(this.buttonBrowse, "buttonBrowse");
258             this.buttonBrowse.Name = "buttonBrowse";
259             this.buttonBrowse.Click += new System.EventHandler(this.OnButtonBrowse_Click);
260             // 
261             // typeTextBox
262             // 
263             resources.ApplyResources(this.typeTextBox, "typeTextBox");
264             this.typeTextBox.Name = "typeTextBox";
265             this.typeTextBox.TextChanged += new System.EventHandler(this.OnTypeTextBoxTextChanged);
266             // 
267             // typeNameLabel
268             // 
269             resources.ApplyResources(this.typeNameLabel, "typeNameLabel");
270             this.typeNameLabel.Name = "typeNameLabel";
271             // 
272             // okCancelTableLayoutPanel
273             // 
274             resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel");
275             this.okCancelTableLayoutPanel.Controls.Add(this.buttonOK, 0, 0);
276             this.okCancelTableLayoutPanel.Controls.Add(this.buttonCancel, 1, 0);
277             this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel";
278             // 
279             // typeNameTableLayoutPanel
280             // 
281             resources.ApplyResources(this.typeNameTableLayoutPanel, "typeNameTableLayoutPanel");
282             this.typeNameTableLayoutPanel.Controls.Add(this.typeNameLabel, 0, 0);
283             this.typeNameTableLayoutPanel.Controls.Add(this.typeTextBox, 1, 0);
284             this.typeNameTableLayoutPanel.Name = "typeNameTableLayoutPanel";
285             // 
286             // artifactLabel
287             // 
288             this.artifactLabel.BorderStyle = System.Windows.Forms.BorderStyle.None;
289             this.artifactLabel.CausesValidation = false;
290             resources.ApplyResources(this.artifactLabel, "artifactLabel");
291             this.artifactLabel.Name = "artifactLabel";
292             this.artifactLabel.ReadOnly = true;
293             this.artifactLabel.TabStop = false;
294             // 
295             // TypeBrowserDialog
296             // 
297             this.AcceptButton = this.buttonOK;
298             resources.ApplyResources(this, "$this");
299             this.CancelButton = this.buttonCancel;
300             this.Controls.Add(this.artifactLabel);
301             this.Controls.Add(this.typeNameTableLayoutPanel);
302             this.Controls.Add(this.okCancelTableLayoutPanel);
303             this.Controls.Add(this.buttonBrowse);
304             this.Controls.Add(this.helpTextHolder);
305             this.Controls.Add(this.tabControl);
306             this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
307             this.HelpButton = true;
308             this.MaximizeBox = false;
309             this.MinimizeBox = false;
310             this.Name = "TypeBrowserDialog";
311             this.ShowInTaskbar = false;
312             this.HelpButtonClicked += new System.ComponentModel.CancelEventHandler(this.TypeBrowserDialog_HelpButtonClicked);
313             this.tabControl.ResumeLayout(false);
314             this.typeTabPage.ResumeLayout(false);
315             this.typeSplitContainer.Panel1.ResumeLayout(false);
316             this.typeSplitContainer.Panel2.ResumeLayout(false);
317             this.typeSplitContainer.ResumeLayout(false);
318             this.advancedTabPage.ResumeLayout(false);
319             this.okCancelTableLayoutPanel.ResumeLayout(false);
320             this.okCancelTableLayoutPanel.PerformLayout();
321             this.typeNameTableLayoutPanel.ResumeLayout(false);
322             this.typeNameTableLayoutPanel.PerformLayout();
323             this.ResumeLayout(false);
324             this.PerformLayout();
325
326         }
327         #endregion
328
329         #region Properties and Methods
330         public Type SelectedType
331         {
332             get
333             {
334                 return this.selectedType;
335             }
336         }
337         #endregion
338
339         List<Type> GetTargetFrameworkTypes(ITypeProvider currentTypeProvider)
340         {
341             IExtendedUIService2 extendedUIService = (IExtendedUIService2)this.serviceProvider.GetService(typeof(IExtendedUIService2));
342             List<Type> targetFrameworkTypes = new List<Type>();
343             if (currentTypeProvider != null)
344             {
345                 if (extendedUIService != null)
346                 {
347                     List<Assembly> runtimeAssemblies = new List<Assembly>(currentTypeProvider.ReferencedAssemblies);
348                     foreach (Assembly runtimeAssembly in runtimeAssemblies)
349                     {
350                         Assembly reflectionContextAssembly = extendedUIService.GetReflectionAssembly(runtimeAssembly.GetName());
351                         if (reflectionContextAssembly != null)
352                         {
353                             foreach (Type type in reflectionContextAssembly.GetTypes())
354                             {
355                                 if (type.IsPublic)
356                                 {
357                                     targetFrameworkTypes.Add(type);
358                                 }
359                             }
360                         }
361                     }
362
363                     // add design time types from type provider to the list 
364                     // and design time types are only for the current user assemblies.
365                     foreach (Type type in currentTypeProvider.GetTypes())
366                     {
367                         if (type.Assembly == null)
368                         {
369                             targetFrameworkTypes.Add(type);
370                         }
371                     }
372                     
373                 }
374                 else
375                 {
376                     //if extendedUIService is null fall back to the type provider.
377                     targetFrameworkTypes.AddRange(currentTypeProvider.GetTypes());
378                 }
379             }
380             return targetFrameworkTypes;
381         }
382
383         #region Events and overrides
384         protected override void OnLoad(EventArgs e)
385         {
386             //Call base class's load
387             base.OnLoad(e);
388
389             Cursor.Current = Cursors.WaitCursor;
390
391             try
392             {
393                 // add current project node
394                 TreeNode currentProjectNode = null;
395                 if (this.localTypeProvider == null)
396                     currentProjectNode = this.artifactTreeView.Nodes.Add(SR.CurrentProject, SR.GetString(SR.CurrentProject), 2, 2);
397
398                 // add references node
399                 TreeNode assembliesNode = this.artifactTreeView.Nodes.Add(SR.ReferencedAssemblies, SR.GetString(SR.ReferencedAssemblies), 2, 2);
400
401                 ITypeProvider typeProvider = this.TypeProvider;
402
403                 AutoCompleteStringCollection autoCompleteStringCollection = new AutoCompleteStringCollection();
404                 this.UpdateTreeView(GetTargetFrameworkTypes(this.TypeProvider).ToArray(), autoCompleteStringCollection);
405
406                 //Select the root node to show all the types.
407                 assembliesNode.Expand();
408                 TreeNode selectNode = (currentProjectNode == null) ? assembliesNode : currentProjectNode;
409                 this.artifactTreeView.SelectedNode = selectNode;
410                 TreeSelectionChanged(selectNode);
411                 selectNode.EnsureVisible();
412
413                 this.typeTextBox.AutoCompleteMode = AutoCompleteMode.Suggest;
414                 this.typeTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
415                 this.typeTextBox.AutoCompleteCustomSource = autoCompleteStringCollection;
416
417                 // now look for selected type
418                 if (this.selectedTypeName != null)
419                 {
420                     Type actualType = typeProvider.GetType(this.selectedTypeName);
421                     if (actualType != null)
422                         this.typeTextBox.Text = GetSimpleTypeFullName(actualType);
423                 }
424             }
425             catch (FileNotFoundException)
426             {
427                 //Eat the fnf exception from missing dependencies and let the UI load.
428             }
429             finally
430             {
431                 Cursor.Current = Cursors.Default;
432             }
433
434             //Update the state of the controls on the form
435             UpdateControlState();
436             this.typeTextBox.Select();
437         }
438
439         private void UpdateTreeView(Type[] types, AutoCompleteStringCollection autoCompleteStringCollection)
440         {
441             TreeNode assembliesNode = this.artifactTreeView.Nodes[SR.ReferencedAssemblies];
442             Hashtable assemblyNodes = new Hashtable();
443             IExtendedUIService2 extendedUIService = (IExtendedUIService2)this.serviceProvider.GetService(typeof(IExtendedUIService2));
444             foreach (Type type in types)
445             {
446                 if (this.typeFilterProvider != null && !this.typeFilterProvider.CanFilterType(extendedUIService != null ? extendedUIService.GetRuntimeType(type) : type, false))
447                     continue;
448
449                 if (autoCompleteStringCollection.Contains(type.FullName))
450                     continue;
451
452                 autoCompleteStringCollection.Add(type.FullName);
453
454                 TreeNode node = null;
455                 if (type.Assembly != null)
456                 {
457                     node = assemblyNodes[type.Assembly] as TreeNode;
458                     if (node == null)
459                     {
460                         node = new TreeNode(type.Assembly.GetName().Name, 3, 3);
461                         node.Tag = type.Assembly;
462                         assembliesNode.Nodes.Add(node);
463                         assemblyNodes[type.Assembly] = node;
464                     }
465                 }
466                 else
467                 {
468                     node = this.artifactTreeView.Nodes[SR.CurrentProject];
469                 }
470
471                 if (type.Namespace != null && type.Namespace.Length > 0)
472                 {
473                     bool found = false;
474                     string namespaceName = type.Namespace;
475                     foreach (TreeNode nsNode in node.Nodes)
476                     {
477                         if (nsNode.Text == namespaceName)
478                         {
479                             found = true;
480                             break;
481                         }
482                     }
483                     if (!found)
484                     {
485                         TreeNode nsNode = new TreeNode(namespaceName, 49, 49);
486                         node.Nodes.Add(nsNode);
487                     }
488                 }
489             }
490         }
491
492         protected override void OnClosing(CancelEventArgs e)
493         {
494             base.OnClosing(e);
495
496             //Destroy the bitmaps used to show the sorting order
497             if (IntPtr.Zero != this.bitmapSortUp)
498                 NativeMethods.DeleteObject(this.bitmapSortUp);
499
500             if (IntPtr.Zero != this.bitmapSortDown)
501                 NativeMethods.DeleteObject(this.bitmapSortDown);
502         }
503
504         protected override void OnPaint(PaintEventArgs paintArgs)
505         {
506             base.OnPaint(paintArgs);
507
508             ///Draw the top devider line
509             Rectangle lineRectangle = new Rectangle(this.ClientRectangle.Left, this.artifactLabel.Bottom + ((this.typeNameTableLayoutPanel.Top + this.typeTextBox.Top - this.artifactLabel.Bottom) / 2), this.ClientRectangle.Width, 1);
510             paintArgs.Graphics.DrawLine(SystemPens.ControlDark, lineRectangle.Left, lineRectangle.Bottom, lineRectangle.Right, lineRectangle.Bottom);
511             paintArgs.Graphics.DrawLine(SystemPens.ControlLightLight, lineRectangle.Left, lineRectangle.Bottom + 1, lineRectangle.Right, lineRectangle.Bottom + 1);
512
513             ///Draw the bottom devider line
514             lineRectangle = new Rectangle(this.ClientRectangle.Left, this.helpTextHolder.Bottom + ((this.okCancelTableLayoutPanel.Top + this.buttonOK.Top - this.helpTextHolder.Bottom) / 2), this.ClientRectangle.Width, 1);
515             paintArgs.Graphics.DrawLine(SystemPens.ControlDark, lineRectangle.Left, lineRectangle.Bottom, lineRectangle.Right, lineRectangle.Bottom);
516             paintArgs.Graphics.DrawLine(SystemPens.ControlLightLight, lineRectangle.Left, lineRectangle.Bottom + 1, lineRectangle.Right, lineRectangle.Bottom + 1);
517
518             //Draw help text border
519             paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, this.helpTextHolder.Left - 1, this.helpTextHolder.Top - 1, this.helpTextHolder.Left - 1, this.helpTextHolder.Bottom);
520             paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, this.helpTextHolder.Left - 1, this.helpTextHolder.Bottom, this.helpTextHolder.Right, this.helpTextHolder.Bottom);
521             paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, this.helpTextHolder.Right, this.helpTextHolder.Bottom, this.helpTextHolder.Right, this.helpTextHolder.Top - 1);
522             paintArgs.Graphics.DrawLine(SystemPens.WindowFrame, this.helpTextHolder.Right, this.helpTextHolder.Top - 1, this.helpTextHolder.Left - 1, this.helpTextHolder.Top - 1);
523         }
524
525         protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
526         {
527             if (keyData == Keys.Enter)
528             {
529                 if (this.lastComboboxValue != this.typeTextBox.Text)
530                 {
531                     this.lastComboboxValue = this.typeTextBox.Text;
532                     this.typeTextBox.Text = string.Empty;
533                     this.typeTextBox.Text = this.lastComboboxValue;
534                     this.typeTextBox.SelectionStart = this.typeTextBox.Text.Length;
535                     return true;
536                 }
537             }
538             return base.ProcessCmdKey(ref msg, keyData);
539         }
540
541         private void OkButtonClicked(object sender, System.EventArgs e)
542         {
543             try
544             {
545                 ITypeProvider typeProvider = this.TypeProvider;
546                 Type type = typeProvider.GetType(this.typeTextBox.Text);
547                 if ((type != null) && (this.typeFilterProvider == null || this.typeFilterProvider.CanFilterType(type, false)))
548                 {
549                     this.selectedTypeName = type.AssemblyQualifiedName;
550                     this.selectedType = type;
551                     DialogResult = DialogResult.OK;
552                 }
553                 else
554                 {
555                     DialogResult = DialogResult.None;
556                 }
557             }
558             catch (Exception ex)
559             {
560                 DesignerHelpers.ShowError(this.serviceProvider, ex);
561             }
562         }
563
564         private void OnTreeSelectionChange(object sender, TreeViewEventArgs e)
565         {
566             TreeSelectionChanged(e.Node);
567         }
568
569         private void OnTreeViewGotFocus(object sender, EventArgs e)
570         {
571             //We always ignore the first set focus as treeview is first in the tab order
572             //We need to refresh the list contents based on tree selection whenever focus changes from listview to treeview
573             if (this.refreshTreeView)
574             {
575                 this.refreshTreeView = false;
576                 if (this.artifactTreeView.SelectedNode != null)
577                     TreeSelectionChanged(this.artifactTreeView.SelectedNode);
578             }
579         }
580
581         private void OnListViewSelectedIndexChanged(object sender, EventArgs e)
582         {
583             try
584             {
585                 if ((!this.refreshTypeTextBox) && (this.artifactListView.SelectedItems.Count > 0))
586                     this.typeTextBox.Text = (this.artifactListView.SelectedItems[0].Tag as Type).FullName;
587
588                 if (this.artifactListView.SelectedItems.Count > 0)
589                     this.artifactListView.SelectedItems[0].EnsureVisible();
590
591                 //Update the namespace selection in tree based on listview selection
592                 if (!this.artifactListView.Focused || this.artifactListView.SelectedItems.Count == 0)
593                     return;
594
595                 Type type = this.artifactListView.SelectedItems[0].Tag as Type;
596                 if (type != null)
597                     ListSelectionChanged(type);
598             }
599             catch (Exception ex)
600             {
601                 DesignerHelpers.ShowError(this.serviceProvider, ex);
602             }
603         }
604
605         private void OnListViewMouseDown(object sender, MouseEventArgs mouseArgs)
606         {
607             //Close the dialog on double click
608             if (mouseArgs.Clicks > 1 && 
609             this.artifactListView.SelectedItems.Count > 0 && 
610             this.artifactListView.SelectedItems[0].Tag is Type &&
611             this.buttonOK.Enabled == true)
612                 OkButtonClicked(this.buttonOK, EventArgs.Empty);
613         }
614
615         private void OnListViewColumnClick(object sender, ColumnClickEventArgs e)
616         {
617             //Sort the items in listview
618             this.sortListViewAscending = !this.sortListViewAscending;
619             SortListViewItems(e.Column);
620         }
621
622         private void TypeBrowserDialog_HelpButtonClicked(object sender, CancelEventArgs e)
623         {
624             e.Cancel = true;
625             GetHelp();
626         }
627
628         protected override void OnHelpRequested(HelpEventArgs e)
629         {
630             e.Handled = true;
631             GetHelp();
632         }
633
634         private void GetHelp()
635         {
636             DesignerHelpers.ShowHelpFromKeyword(this.serviceProvider, typeof(TypeBrowserDialog).FullName + ".UI");
637         }
638
639         private void OnTypeTextBoxSelectedIndexChanged(object sender, EventArgs e)
640         {
641             OnTypeTextBoxTextChanged(sender, e);
642         }
643
644         private void OnTypeTextBoxTextChanged(object sender, EventArgs e)
645         {
646             try
647             {
648                 if (this.refreshTypeTextBox)
649                     return;
650                 this.refreshTypeTextBox = true;
651                 ITypeProvider typeProvider = this.TypeProvider;
652                 Type actualType = typeProvider.GetType(this.typeTextBox.Text);
653
654                 if (actualType != null)
655                 {
656                     this.lastComboboxValue = this.typeTextBox.Text;
657
658                     Type baseType = null;
659                     ParameterData[] parameterDataArray = null;
660                     int[] arrayRanks = null;
661
662                     GetTypeParts(actualType, out baseType, out parameterDataArray, out arrayRanks);
663                     this.genericParameters.Parameters = parameterDataArray != null ? parameterDataArray : new ParameterData[0];
664                     this.genericParametersPropertyGrid.Refresh();
665
666                     ListSelectionChanged(baseType);
667
668                     this.genericParametersPropertyGrid.Enabled = baseType.IsGenericTypeDefinition;
669
670                     foreach (ListViewItem lvItem in this.artifactListView.Items)
671                     {
672                         Type type = lvItem.Tag as Type;
673                         if (type != null && (type.FullName.Equals(baseType.FullName)))
674                         {
675                             if (!lvItem.Selected)
676                                 lvItem.Selected = true;
677                             break;
678                         }
679                         else
680                             lvItem.Selected = false;
681                     }
682                 }
683                 else
684                 {
685                     if (this.artifactListView.SelectedItems.Count != 0)
686                         this.artifactListView.SelectedItems[0].Selected = false;
687
688                     this.genericParameters.Parameters = new ParameterData[0];
689                     this.genericParametersPropertyGrid.Enabled = false;
690                 }
691
692                 //Update the state of the controls on the form
693                 UpdateControlState();
694
695                 this.refreshTypeTextBox = false;
696             }
697             catch (Exception ex)
698             {
699                 DesignerHelpers.ShowError(this.serviceProvider, ex);
700             }
701         }
702
703         private void OnButtonBrowse_Click(object Sender, EventArgs e)
704         {
705             OpenFileDialog fileDialog = new OpenFileDialog();
706             fileDialog.Title = DR.GetString(DR.OpenfileDialogTitle);
707             fileDialog.AddExtension = true;
708             fileDialog.DefaultExt = "dll";
709             fileDialog.CheckFileExists = true;
710             fileDialog.CheckPathExists = true;
711             fileDialog.DereferenceLinks = true;
712             fileDialog.ValidateNames = true;
713             fileDialog.Filter = DR.GetString(DR.PackageAssemblyReferenceFilter);
714             fileDialog.RestoreDirectory = false;
715             if (fileDialog.ShowDialog(this) == DialogResult.OK)
716             {
717                 //this is an inline delegate who'll be handling the type loader event
718                 EventHandler typeLoadErrorsChangedHandler = delegate(object sender, EventArgs ea)
719                 {
720                     Exception exception = null;
721                     if (this.localTypeProvider.TypeLoadErrors.ContainsKey(fileDialog.FileName))
722                         exception = this.localTypeProvider.TypeLoadErrors[fileDialog.FileName];
723
724                     if (exception != null)
725                     {
726                         string errorMessage = (exception is ReflectionTypeLoadException || (exception.InnerException != null && exception.InnerException is ReflectionTypeLoadException)) ? DR.GetString(DR.TypeBrowser_UnableToLoadOneOrMoreTypes) : DR.GetString(DR.TypeBrowser_ProblemsLoadingAssembly);
727                         errorMessage = string.Format(CultureInfo.CurrentCulture, errorMessage, new object[] { fileDialog.FileName });
728                         DesignerHelpers.ShowError(this.serviceProvider, errorMessage);
729                     }
730                 };
731
732                 try
733                 {
734                     ITypeProviderCreator typeProviderCreator = this.serviceProvider.GetService(typeof(ITypeProviderCreator)) as ITypeProviderCreator;
735                     if (typeProviderCreator != null)
736                         this.localTypeProvider.AddAssembly(typeProviderCreator.GetTransientAssembly(AssemblyName.GetAssemblyName(fileDialog.FileName)));
737                     else
738                         this.localTypeProvider.AddAssemblyReference(fileDialog.FileName);
739
740                     Helpers.UpdateTypeProviderAssembliesRegistry(fileDialog.FileName);
741                     this.localTypeProvider.TypeLoadErrorsChanged += typeLoadErrorsChangedHandler;
742
743                     UpdateTreeView(GetTargetFrameworkTypes(this.localTypeProvider).ToArray(), this.typeTextBox.AutoCompleteCustomSource);
744                 }
745                 catch (FileNotFoundException fnf)
746                 {
747                     DesignerHelpers.ShowError(this.serviceProvider, fnf.Message);
748                 }
749                 catch (BadImageFormatException)
750                 {
751                     DesignerHelpers.ShowError(this.serviceProvider, SR.GetString(SR.Error_AssemblyBadImage, fileDialog.FileName));
752                 }
753                 catch (FileLoadException)
754                 {
755                     DesignerHelpers.ShowError(this.serviceProvider, SR.GetString(SR.Error_AssemblyBadImage, fileDialog.FileName));
756                 }
757                 catch (Exception ex)
758                 {
759                     DesignerHelpers.ShowError(this.serviceProvider, SR.GetString(SR.Error_AddAssemblyRef, fileDialog.FileName, ex.Message));
760                 }
761                 finally
762                 {
763                     this.localTypeProvider.TypeLoadErrorsChanged -= typeLoadErrorsChangedHandler;
764                 }
765             }
766         }
767
768         #endregion
769
770         #region Helpers
771
772         private void CustomInitializeComponent()
773         {
774             this.SuspendLayout();
775             this.artifactTreeView.Sorted = true;
776
777             //Load the bitmap
778             Bitmap bitmap = TypeBrowserDialog.ResMgr.GetObject("IDB_SORTUP") as Bitmap;
779             this.bitmapSortUp = bitmap.GetHbitmap();
780
781             bitmap = TypeBrowserDialog.ResMgr.GetObject("IDB_SORTDOWN") as Bitmap;
782             this.bitmapSortDown = bitmap.GetHbitmap();
783
784             //Create imagelist for tree and list
785             this.artifactImages = new ImageList();
786             this.artifactImages.TransparentColor = Color.FromArgb(0, 255, 0);
787             this.artifactImages.Images.AddStrip((Image)TypeBrowserDialog.ResMgr.GetObject("IDB_ARTIFACTIMAGES"));
788
789             //DO NOT CHANGE THE CREATION SEQUENCE OF FOLLOWING CONTROLS
790
791             //Set the listview style
792             this.artifactListView.Dock = DockStyle.Fill;
793             this.artifactListView.FullRowSelect = true;
794             this.artifactListView.HideSelection = false;
795             this.artifactListView.MultiSelect = false;
796             this.artifactListView.SmallImageList = this.artifactImages;
797             this.artifactListView.MouseDown += new MouseEventHandler(OnListViewMouseDown);
798
799             //Set the treeview styles
800             this.artifactTreeView.HideSelection = false;
801             this.artifactTreeView.ImageList = this.artifactImages;
802             //DO NOT CHANGE THE CREATION SEQUENCE OF ABOVE CONTROLS
803
804             //Change the HelpText holder to a Rich Edit Control
805             this.helpTextHolder.Visible = false;
806             this.helpTextWindow = new HelpTextWindow();
807             this.helpTextWindow.Parent = this;
808             this.helpTextWindow.Location = new Point(this.helpTextHolder.Location.X + 3, this.helpTextHolder.Location.Y + 3);
809             this.helpTextWindow.Size = new Size(this.helpTextHolder.Size.Width - 6, this.helpTextHolder.Size.Height - 6);
810
811             //Set the text based on the browsed type
812             if (this.typeFilterProvider != null)
813                 this.artifactLabel.Text = this.typeFilterProvider.FilterDescription;
814
815             //Set dialog fonts
816             IUIService uisvc = (IUIService)this.serviceProvider.GetService(typeof(IUIService));
817             if (uisvc != null)
818                 this.Font = (Font)uisvc.Styles["DialogFont"];
819
820             //Set the font for the artifact label
821             this.artifactLabel.Font = new Font(this.Font.Name, this.Font.SizeInPoints, FontStyle.Bold);
822
823             this.genericParametersPropertyGrid.SelectedObject = this.genericParameters;
824             this.genericParametersPropertyGrid.Site = this;
825             this.genericParametersPropertyGrid.PropertyValueChanged += new PropertyValueChangedEventHandler(GenericParameterChanged);
826             this.ResumeLayout(false);
827         }
828
829         private void TreeSelectionChanged(TreeNode treeNode)
830         {
831             try
832             {
833                 if (this.artifactListView.Focused)
834                     return;
835
836                 this.artifactListView.Items.Clear();
837                 this.artifactListView.ListViewItemSorter = null;
838
839                 string namespaceToFilter = null;
840                 ArrayList selectedAssemblies = new ArrayList();
841
842                 if (treeNode == this.artifactTreeView.Nodes[SR.CurrentProject])
843                 {
844                     // current project node
845                     // do nothing
846                 }
847                 else if (treeNode == this.artifactTreeView.Nodes[SR.ReferencedAssemblies])
848                 {
849                     // assemblies node
850                     foreach (TreeNode treeNode2 in treeNode.Nodes)
851                         selectedAssemblies.Add(treeNode2.Tag);
852                 }
853                 else if (treeNode.Tag is Assembly)
854                 {
855                     selectedAssemblies.Add(treeNode.Tag);
856                 }
857                 else
858                 {
859                     if (treeNode.Parent.Tag != null)
860                         selectedAssemblies.Add(treeNode.Parent.Tag);
861                     namespaceToFilter = treeNode.Text;
862                 }
863
864                 ITypeProvider typeProvider = this.TypeProvider;
865                 IExtendedUIService2 extendedUIService = (IExtendedUIService2)this.serviceProvider.GetService(typeof(IExtendedUIService2));
866                 foreach (Type type in GetTargetFrameworkTypes(typeProvider))
867                 {
868                     try
869                     {
870                         object[] attributes = type.GetCustomAttributes(typeof(ObsoleteAttribute), false);
871                         if ((attributes != null) && attributes.Length > 0)
872                             continue;
873                     }
874                     catch (Exception e)
875                     {
876                         Debug.WriteLine("Count not retrieve attributes from type:" + e.Message);
877                     }
878
879                     if ((namespaceToFilter == null || type.Namespace == namespaceToFilter) && ((selectedAssemblies.Count == 0 && type.Assembly == null) || selectedAssemblies.Contains(type.Assembly)) && (this.typeFilterProvider == null || this.typeFilterProvider.CanFilterType(extendedUIService != null ? extendedUIService.GetRuntimeType(type) : type, false)))
880                     {
881                         ListViewItem listItem = new ListViewItem();
882
883                         listItem.Text = type.Name;
884                         listItem.SubItems.Add(type.FullName);
885                         listItem.Tag = type;
886                         listItem.ImageIndex = 0;
887                         this.artifactListView.Items.Add(listItem);
888                     }
889                 }
890                 SortListViewItems(0);
891                 this.artifactListView.SelectedIndices.Clear();
892
893                 //Select first type by default
894                 if (this.artifactListView.Items.Count > 0)
895                     this.artifactListView.Items[0].Selected = true;
896             }
897             catch (Exception ex)
898             {
899                 DesignerHelpers.ShowError(this.serviceProvider, ex);
900             }
901
902         }
903
904         private void GenericParameterChanged(object sender, PropertyValueChangedEventArgs e)
905         {
906             bool fullyConfigured = true;
907             foreach (ParameterData parameterData in this.genericParameters.Parameters)
908             {
909                 if (parameterData.Type == null)
910                 {
911                     fullyConfigured = false;
912                     break;
913                 }
914             }
915             if (fullyConfigured)
916                 UpdateTypeTextBox();
917         }
918
919         private void ListSelectionChanged(Type selectedType)
920         {
921             if (this.artifactTreeView.Focused)
922                 return;
923
924             string typeName = selectedType.FullName;
925             string assemblyName = string.Empty;
926             if (selectedType.Assembly != null)
927                 assemblyName = selectedType.Assembly.GetName().Name;
928
929             TreeNode selectedAssemblyNode = null;
930             if (assemblyName.Length == 0)
931             {
932                 selectedAssemblyNode = this.artifactTreeView.Nodes[SR.CurrentProject];
933             }
934             else
935             {
936                 TreeNode assembliesNode = this.artifactTreeView.Nodes[SR.ReferencedAssemblies];
937                 foreach (TreeNode assemblyNode in assembliesNode.Nodes)
938                 {
939                     Assembly assembly = assemblyNode.Tag as Assembly;
940                     if (assembly.FullName == assemblyName ||
941                         assembly.GetName().Name == assemblyName)
942                     {
943                         selectedAssemblyNode = assemblyNode;
944                         break;
945                     }
946                 }
947             }
948
949             TreeNode selectedNsNode = null;
950             if (selectedAssemblyNode != null)
951             {
952                 string nsName = string.Empty;
953                 int lastIndexOfDot = typeName.LastIndexOf('.');
954                 if (lastIndexOfDot != -1)
955                     nsName = typeName.Substring(0, lastIndexOfDot);
956
957                 if (nsName.Length > 0)
958                 {
959                     foreach (TreeNode nsNode in selectedAssemblyNode.Nodes)
960                     {
961                         if (nsNode.Text == nsName)
962                         {
963                             selectedNsNode = nsNode;
964                             break;
965                         }
966                     }
967                 }
968             }
969
970             TreeNode selectedNode = selectedNsNode;
971             if (selectedNode == null)
972                 selectedNode = selectedAssemblyNode;
973
974             if (selectedNode != null && this.artifactTreeView.CanFocus) 
975             {
976                 this.artifactTreeView.SelectedNode = selectedNode;
977                 selectedNode.EnsureVisible();
978             }
979         }
980
981         private void SortListViewItems(int columnIndex)
982         {
983             if (columnIndex < 0 || columnIndex >= this.artifactListView.Columns.Count)
984                 return;
985
986             ListItemComparer listItemComparer = new ListItemComparer((columnIndex == 0) ? true : false, this.sortListViewAscending);
987             this.artifactListView.ListViewItemSorter = listItemComparer;
988
989             if (this.artifactListView.SelectedItems.Count > 0)
990                 this.artifactListView.SelectedItems[0].EnsureVisible();
991
992             //Update the bitmap for the sorted column
993             IntPtr headerWindow = NativeMethods.ListView_GetHeader(this.artifactListView.Handle);
994             NativeMethods.HDITEM headerItem = new NativeMethods.HDITEM();
995             headerItem.mask = NativeMethods.HDI_FORMAT | NativeMethods.HDI_BITMAP;
996             for (int i = 0; i < this.artifactListView.Columns.Count; i++)
997             {
998                 if (NativeMethods.Header_GetItem(headerWindow, i, headerItem))
999                 {
1000                     headerItem.fmt &= ~(NativeMethods.HDF_BITMAP | NativeMethods.HDF_BITMAP_ON_RIGHT);
1001                     headerItem.hbm = IntPtr.Zero;
1002                     NativeMethods.Header_SetItem(headerWindow, i, headerItem);
1003                 }
1004             }
1005
1006             if (NativeMethods.Header_GetItem(headerWindow, columnIndex, headerItem))
1007             {
1008                 headerItem.mask = NativeMethods.HDI_FORMAT | NativeMethods.HDI_BITMAP;
1009                 headerItem.fmt |= NativeMethods.HDF_BITMAP | NativeMethods.HDF_BITMAP_ON_RIGHT;
1010                 headerItem.hbm = (this.sortListViewAscending) ? this.bitmapSortUp : this.bitmapSortDown;
1011                 NativeMethods.Header_SetItem(headerWindow, columnIndex, headerItem);
1012             }
1013         }
1014
1015         private void UpdateControlState()
1016         {
1017             ITypeProvider typeProvider = this.TypeProvider;
1018             Type selectedType = null;
1019
1020             selectedType = typeProvider.GetType(this.typeTextBox.Text);
1021             if ((null != selectedType) && (this.typeFilterProvider == null || (this.typeFilterProvider.CanFilterType(selectedType, false))) && !selectedType.IsGenericTypeDefinition)
1022             {
1023                 this.buttonOK.Enabled = true;
1024                 this.AcceptButton = this.buttonOK;
1025             }
1026             else
1027             {
1028                 this.buttonOK.Enabled = false;
1029                 this.AcceptButton = null;
1030             }
1031
1032             this.helpTextWindow.UpdateHelpText(selectedType);
1033         }
1034
1035         private void UpdateTypeTextBox()
1036         {
1037             string typeName = String.Empty;
1038
1039             if (this.artifactListView.SelectedItems.Count > 0)
1040             {
1041                 Type type = this.artifactListView.SelectedItems[0].Tag as Type;
1042                 typeName = type.FullName;
1043                 bool appendParameteres = true;
1044                 string parameters = string.Empty;
1045                 if ((type.IsGenericType) && (this.genericParameters.Parameters.Length > 0))
1046                 {
1047                     parameters = "[";
1048                     int index = 0;
1049                     foreach (ParameterData parameterData in this.genericParameters.Parameters)
1050                     {
1051                         parameters += "[";
1052                         index++;
1053                         Type parameterType = parameterData.Type;
1054                         if (parameterType != null)
1055                         {
1056                             parameters += parameterType.FullName;
1057                         }
1058                         else
1059                         {
1060                             appendParameteres = false;
1061                             break;
1062                         }
1063
1064                         parameters += "]";
1065                         if (index < this.genericParameters.Parameters.Length)
1066                             parameters += ",";
1067                     }
1068                     parameters += "]";
1069                 }
1070                 if (appendParameteres)
1071                     typeName += parameters;
1072
1073             }
1074             this.typeTextBox.Text = typeName;
1075         }
1076
1077         private void GetTypeParts(Type type, out Type baseType, out ParameterData[] parameterDataArray, out int[] arrayRanks)
1078         {
1079             baseType = null;
1080             parameterDataArray = null;
1081             arrayRanks = null;
1082
1083             if (type.IsArray == true)
1084             {
1085                 ArrayList arrayRankList = new ArrayList();
1086                 GetTypeParts(type.GetElementType(), out baseType, out parameterDataArray, out arrayRanks);
1087                 if (arrayRanks != null)
1088                     arrayRankList.AddRange(arrayRanks);
1089                 arrayRankList.Add(type.GetArrayRank());
1090                 arrayRanks = (int[])arrayRankList.ToArray(typeof(int));
1091             }
1092             else if (type.IsGenericType)
1093             {
1094                 Type unboundedType = null;
1095                 Type boundedType = null;
1096
1097                 if (type.ContainsGenericParameters)
1098                 {
1099                     boundedType = null;
1100                     unboundedType = type.UnderlyingSystemType;
1101                 }
1102                 else
1103                 {
1104                     boundedType = type;
1105                     unboundedType = type.GetGenericTypeDefinition().UnderlyingSystemType;
1106                 }
1107                 ArrayList parameterDataList = new ArrayList();
1108                 for (int loop = 0; loop < unboundedType.GetGenericArguments().Length; loop++)
1109                 {
1110                     ParameterData parameterData = new ParameterData();
1111                     parameterData.ParameterType = unboundedType.GetGenericArguments()[loop];
1112                     if (boundedType != null)
1113                         parameterData.Type = type.GetGenericArguments()[loop];
1114                     parameterDataList.Add(parameterData);
1115                 }
1116                 parameterDataArray = (ParameterData[])parameterDataList.ToArray(typeof(ParameterData));
1117                 baseType = unboundedType;
1118             }
1119             else
1120             {
1121                 baseType = type;
1122             }
1123         }
1124
1125         private string GetSimpleTypeFullName(Type type)
1126         {
1127             StringBuilder typeName = new StringBuilder(type.FullName);
1128             Stack<Type> types = new Stack<Type>();
1129             types.Push(type);
1130
1131             while (types.Count > 0)
1132             {
1133                 type = types.Pop();
1134
1135                 while (type.IsArray)
1136                     type = type.GetElementType();
1137
1138                 if (type.IsGenericType && !type.IsGenericTypeDefinition)
1139                 {
1140                     foreach (Type parameterType in type.GetGenericArguments())
1141                     {
1142                         typeName.Replace("[" + parameterType.AssemblyQualifiedName + "]", parameterType.FullName);
1143                         types.Push(parameterType);
1144                     }
1145                 }
1146             }
1147
1148             return typeName.ToString();
1149         }
1150
1151         private ITypeProvider TypeProvider
1152         {
1153             get
1154             {
1155                 ITypeProvider typeProvider = this.localTypeProvider as ITypeProvider;
1156                 if (typeProvider == null)
1157                     typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider));
1158
1159                 if (typeProvider == null)
1160                     throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
1161
1162                 return typeProvider;
1163             }
1164         }
1165         #endregion
1166
1167         #region Class ListItemComparer
1168         private sealed class ListItemComparer : IComparer
1169         {
1170             private bool compareTypeName;
1171             private bool ascending;
1172             internal ListItemComparer(bool compareTypeName, bool ascending)
1173             {
1174                 this.compareTypeName = compareTypeName;
1175                 this.ascending = ascending;
1176             }
1177             
1178             
1179             [SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.Compare(System.String,System.String)", Justification = "This is not a security issue because this is a design time class")]
1180             public int Compare(object first, object second)
1181             {
1182                 int result = 0;
1183                 if (this.compareTypeName)
1184                     result = string.Compare(((ListViewItem)first).Text, ((ListViewItem)second).Text);
1185                 else
1186                     result = string.Compare(((ListViewItem)first).SubItems[1].Text, ((ListViewItem)second).SubItems[1].Text);
1187                 return ((this.ascending) ? 1 * result : -1 * result);
1188             }
1189         }
1190         #endregion
1191
1192         #region Class HelpTextWindow
1193         private sealed class HelpTextWindow : RichTextBox
1194         {
1195             internal HelpTextWindow()
1196             {
1197                 this.TabStop = false;
1198                 this.BorderStyle = BorderStyle.None;
1199                 this.ReadOnly = true;
1200                 this.BackColor = SystemColors.Control;
1201                 this.Multiline = true;
1202                 this.ScrollBars = RichTextBoxScrollBars.Both;
1203                 this.Cursor = Cursors.Default;
1204             }
1205
1206             protected override void WndProc(ref Message msg)
1207             {
1208                 const int WM_MOUSEFIRST = 0x0200;
1209                 const int WM_MOUSELAST = 0x020D;
1210                 if (msg.Msg >= WM_MOUSEFIRST && msg.Msg <= WM_MOUSELAST)
1211                     return;
1212                 else
1213                     base.WndProc(ref msg);
1214             }
1215
1216             internal void UpdateHelpText(Type selectedType)
1217             {
1218                 using (Font helpFontBold = new Font(this.Font.FontFamily, this.Font.SizeInPoints, FontStyle.Bold))
1219                 {
1220                     this.Clear();
1221
1222                     if (null != selectedType)
1223                     {
1224                         string[] keywords = new string[3];
1225                         keywords[0] = selectedType.Name;
1226                         try
1227                         {
1228                             keywords[1] = (selectedType.Namespace != null && selectedType.Namespace.Length > 0) ? selectedType.Namespace : TypeBrowserDialog.ResMgr.GetString("IDS_GLOBALNS");
1229                         }
1230                         catch (NullReferenceException)
1231                         {
1232                             // Work around: for some reason RuntimeType.Namespace throws exception for array of generic
1233                             //       Remove the try-catch when the bug is fixed.
1234                         }
1235                         keywords[1] = "{" + keywords[1] + "}";
1236                         keywords[2] = (selectedType.Assembly != null) ? selectedType.Assembly.GetName().FullName : "<Current Project>";
1237
1238                         Color[] keywordColors = new Color[3];
1239                         keywordColors[0] = Color.DarkRed;
1240                         keywordColors[1] = Color.Green;
1241                         keywordColors[2] = Color.Blue;
1242
1243                         this.Text = TypeBrowserDialog.ResMgr.GetString("IDS_SELECTEDTYPE") + " " + keywords[0] + " " +
1244                         TypeBrowserDialog.ResMgr.GetString("IDS_MEMBEROF") + " " + keywords[1] + "\r\n" +
1245                         TypeBrowserDialog.ResMgr.GetString("IDS_CONTAINEDINASM") + " " + keywords[2];
1246
1247                         int nStartSearch = 0;
1248                         for (int i = 0; i < keywords.GetLength(0); i++)
1249                         {
1250                             int nPrevStart = nStartSearch;
1251                             nStartSearch = this.Find(keywords[i], nStartSearch, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord);
1252                             this.SelectionColor = keywordColors[i];
1253                             this.SelectionFont = helpFontBold;
1254                             nStartSearch += keywords[i].Length;
1255                         }
1256                     }
1257                     else
1258                     {
1259                         this.Text = TypeBrowserDialog.ResMgr.GetString("IDS_NOTYPESSELECTED");
1260                         this.SelectionStart = 0;
1261                         this.SelectionLength = this.Text.Length;
1262                         this.SelectionColor = Color.DarkRed;
1263                         this.SelectionFont = helpFontBold;
1264                     }
1265                 }
1266             }
1267         }
1268         #endregion
1269
1270         #region ISite Members
1271
1272         IComponent System.ComponentModel.ISite.Component
1273         {
1274             get
1275             {
1276                 return null;
1277             }
1278         }
1279         bool System.ComponentModel.ISite.DesignMode
1280         {
1281             get
1282             {
1283                 return true;
1284             }
1285         }
1286         string System.ComponentModel.ISite.Name
1287         {
1288             get
1289             {
1290                 return "";
1291             }
1292             set
1293             {
1294             }
1295         }
1296         IContainer System.ComponentModel.ISite.Container
1297         {
1298             get
1299             {
1300                 return null;
1301             }
1302         }
1303
1304         #endregion
1305
1306         #region IServiceProvider Members
1307
1308         object System.IServiceProvider.GetService(Type serviceType)
1309         {
1310             object service = null;
1311
1312             if (serviceType == typeof(ITypeProvider))
1313                 service = this.TypeProvider;
1314
1315             return service;
1316         }
1317
1318         #endregion
1319
1320         #region Class ParameterData
1321         [TypeConverter(typeof(ParamaeterDataConverter))]
1322         [Editor(typeof(TypeBrowserEditor), typeof(UITypeEditor))]
1323         private sealed class ParameterData : ITypeFilterProvider
1324         {
1325             private Type parameterType;
1326             private Type type;
1327
1328             public Type Type
1329             {
1330                 get
1331                 {
1332                     return type;
1333                 }
1334
1335                 set
1336                 {
1337                     type = value;
1338                 }
1339             }
1340
1341             public Type ParameterType
1342             {
1343                 get
1344                 {
1345                     return this.parameterType;
1346                 }
1347
1348                 set
1349                 {
1350                     this.parameterType = value;
1351                 }
1352             }
1353
1354             #region ITypeFilterProvider Members
1355             public bool CanFilterType(Type type, bool throwOnError)
1356             {
1357                 bool validType = true;
1358
1359                 if ((type.IsByRef) || (!System.Workflow.ComponentModel.Compiler.TypeProvider.IsAssignable(this.parameterType.BaseType, type)))
1360                     validType = false;
1361
1362                 if (throwOnError && !validType)
1363                     throw new Exception(SR.GetString(SR.Error_ArgumentTypeNotMatchParameter));
1364
1365                 return validType;
1366             }
1367
1368             public string FilterDescription
1369             {
1370                 get
1371                 {
1372                     return SR.GetString(SR.FilterDescription_GenericArgument, this.parameterType.Name);
1373                 }
1374             }
1375             #endregion
1376         }
1377         #endregion
1378
1379         #region Class GenericParameters
1380
1381         [TypeConverter(typeof(GenericParametersConverter))]
1382         private class GenericParameters
1383         {
1384             private ParameterData[] parameters = new ParameterData[0];
1385
1386             public ParameterData[] Parameters
1387             {
1388                 get
1389                 {
1390                     return parameters;
1391                 }
1392                 set
1393                 {
1394                     this.parameters = value;
1395                 }
1396             }
1397         }
1398
1399         #endregion
1400
1401         #region Class GenericParametersConverter
1402
1403         private class GenericParametersConverter : TypeConverter
1404         {
1405             public override bool GetPropertiesSupported(ITypeDescriptorContext context)
1406             {
1407                 return true;
1408             }
1409
1410             public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
1411             {
1412                 PropertyDescriptorCollection newProps = new PropertyDescriptorCollection(null);
1413                 GenericParameters genericParameters = value as GenericParameters;
1414
1415                 foreach (ParameterData parameterData in genericParameters.Parameters)
1416                     newProps.Add(new ParameterDataPropertyDescriptor(context, TypeDescriptor.CreateProperty(typeof(GenericParameters), parameterData.ParameterType.Name, typeof(ParameterData))));
1417
1418                 return newProps;
1419             }
1420
1421         }
1422
1423         #endregion
1424
1425         #region Class ParamaeterDataConverter
1426
1427         private class ParamaeterDataConverter : TypeConverter
1428         {
1429             public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
1430             {
1431                 if (sourceType == typeof(string))
1432                     return true;
1433                 return base.CanConvertFrom(context, sourceType);
1434             }
1435             public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
1436             {
1437                 if (destinationType == typeof(string))
1438                     return true;
1439                 return base.CanConvertTo(context, destinationType);
1440             }
1441
1442             public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
1443             {
1444                 if (value == null) 
1445                     return new ParameterData();
1446                 else if (value is string)
1447                 {
1448                     ParameterData parameterData = new ParameterData();
1449
1450                     if ((string)value != string.Empty)
1451                     {
1452                         ITypeProvider typeProvider = context.GetService(typeof(ITypeProvider)) as ITypeProvider;
1453                         parameterData.Type = typeProvider.GetType(value as string, true);
1454                     }
1455                     return parameterData;
1456                 }
1457
1458                 return base.ConvertFrom(context, culture, value);
1459             }
1460
1461             public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
1462             {
1463                 if (destinationType == typeof(string))
1464                 {
1465                     ParameterData parameterData = value as ParameterData;
1466                     if (parameterData.Type != null)
1467                         return (parameterData.Type.AssemblyQualifiedName);
1468                     else
1469                         return string.Empty;
1470                 }
1471                 else
1472                     if (destinationType == null)
1473                         return string.Empty;
1474
1475                 return base.ConvertTo(context, culture, value, destinationType);
1476             }
1477
1478         }
1479
1480         #endregion
1481
1482         #region Class ParameterDataPropertyDescriptor
1483
1484         private class ParameterDataPropertyDescriptor : PropertyDescriptor
1485         {
1486             private PropertyDescriptor realPropertyDescriptor = null;
1487             private IServiceProvider serviceProvider = null;
1488
1489             internal ParameterDataPropertyDescriptor(IServiceProvider serviceProvider, PropertyDescriptor desc)
1490                 : base(desc, null)
1491             {
1492                 this.realPropertyDescriptor = desc;
1493                 this.serviceProvider = serviceProvider;
1494             }
1495             public override string Category
1496             {
1497                 get
1498                 {
1499                     return SR.GetString(SR.GenericParameters);
1500                 }
1501             }
1502             public override AttributeCollection Attributes
1503             {
1504                 get
1505                 {
1506                     return this.realPropertyDescriptor.Attributes;
1507                 }
1508             }
1509             public override TypeConverter Converter
1510             {
1511                 get
1512                 {
1513                     return this.realPropertyDescriptor.Converter;
1514                 }
1515             }
1516             public override string Description
1517             {
1518                 get
1519                 {
1520                     return this.realPropertyDescriptor.Description;
1521                 }
1522             }
1523             public override Type ComponentType
1524             {
1525                 get
1526                 {
1527                     return this.realPropertyDescriptor.ComponentType;
1528                 }
1529             }
1530             public override Type PropertyType
1531             {
1532                 get
1533                 {
1534                     return this.realPropertyDescriptor.PropertyType;
1535                 }
1536             }
1537             public override bool IsReadOnly
1538             {
1539                 get
1540                 {
1541                     return false;
1542                 }
1543             }
1544             public override void ResetValue(object component)
1545             {
1546                 this.realPropertyDescriptor.ResetValue(component);
1547             }
1548             public override bool CanResetValue(object component)
1549             {
1550                 return this.realPropertyDescriptor.CanResetValue(component);
1551             }
1552             public override bool ShouldSerializeValue(object component)
1553             {
1554                 return this.realPropertyDescriptor.ShouldSerializeValue(component);
1555             }
1556             public override object GetValue(object component)
1557             {
1558                 GenericParameters genericParameters = component as GenericParameters;
1559                 foreach (ParameterData parameterData in genericParameters.Parameters)
1560                 {
1561                     if (parameterData.ParameterType.Name == this.Name)
1562                         return parameterData;
1563                 }
1564
1565                 return null;
1566             }
1567             public override void SetValue(object component, object value)
1568             {
1569                 GenericParameters genericParameters = component as GenericParameters;
1570                 foreach (ParameterData parameterData in genericParameters.Parameters)
1571                 {
1572                     if (parameterData.ParameterType.Name == this.Name)
1573                     {
1574                         parameterData.Type = ((ParameterData)value).Type;
1575                         break;
1576                     }
1577                 }
1578             }
1579         }
1580
1581         #endregion
1582
1583         private class DummySite : ISite
1584         {
1585             private IServiceProvider serviceProvider;
1586
1587             internal DummySite(IServiceProvider serviceProvider)
1588             {
1589                 this.serviceProvider = serviceProvider;
1590             }
1591
1592             public IComponent Component { get { return null; } }
1593             public IContainer Container { get { return null; } }
1594             public bool DesignMode { get { return true; } }
1595             public string Name { get { return string.Empty; } set { } }
1596             public object GetService(Type type) { return this.serviceProvider.GetService(type); }
1597         }
1598     }
1599
1600 }