Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 1 of 10
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Visual Studio 2012 [This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.] Dynamic objects expose members such as properties and methods at run time, instead of in at compile time. This enables you to create objects to work with structures that do not match a static type or format. For example, you can use a dynamic object to reference the HTML Document Object Model (DOM), which can contain any combination of valid HTML markup elements and attributes. Because each HTML document is unique, the members for a particular HTML document are determined at run time. A common method to reference an attribute of an HTML element is to pass the name of the attribute to the GetProperty method of the element. To reference the id attribute of the HTML element <di v i d=" Di v 1" >, you first obtain a reference to the <di v> element, and then use di vEl em ent . Get Pr oper t y( " i d" ) . If you use a dynamic object, you can reference the id attribute as di v El em ent . i d . Dynamic objects also provide convenient access to dynamic languages such as IronPython and IronRuby. You can use a dynamic object to refer to a dynamic script that is interpreted at run time. You reference a dynamic object by using late binding. In C#, you specify the type of a late-bound object as dynamic. In Visual Basic, you specify the type of a late-bound object as Object. For more information, see dynamic (C# Reference)1 and Early and Late Binding (Visual Basic)2. You can create custom dynamic objects by using the classes in the System.Dynamic3 namespace. For example, you can create an ExpandoObject4 and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject5 class. You can then override the members of the DynamicObject5 class to provide run-time dynamic functionality. In this walkthrough you will perform the following tasks: Create a custom object that dynamically exposes the contents of a text file as properties of an object. Create a project that uses an IronPython library.
Prerequisites
You need IronPython 2.6.1 for .NET 4.0 to complete this walkthrough. You can download IronPython 2.6.1 for .NET 4.0 from CodePlex6. Note Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 2 of 10
Settings7.
6. The custom dynamic object uses an enum to determine the search criteria. Before the class statement, add the following enum definition. C#
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 3 of 10
7. Update the class statement to inherit the DynamicObject class, as shown in the following code example. C#
8. Add the following code to the ReadOnlyFile class to define a private field for the file path and a constructor for the ReadOnlyFile class. C#
// Store the path to the file and the initial line count value. private string p_filePath; // Public constructor. Verify that file exists and store the path in // the private variable. public ReadOnlyFile(string filePath) { if (!File.Exists(filePath)) { throw new Exception("File path does not exist."); } } p_filePath = filePath;
9. Add the following GetPropertyValue method to the ReadOnlyFile class. The GetPropertyValue method takes, as input, search criteria and returns the lines from a text file that match that search criteria. The dynamic methods provided by the ReadOnlyFile class call the GetPropertyValue method to retrieve their respective results. C#
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 4 of 10
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 5 of 10
10. After the GetPropertyValue method, add the following code to override the
TryGetMember9 method of the DynamicObject5 class. The TryGetMember9 method is called when a member of a dynamic class is requested and no arguments are specified. The binder argument contains information about the referenced member, and the result argument references the result returned for the specified member. The TryGetMember9 method returns a Boolean value that returns true if the requested member exists; otherwise it returns false. C#
// Implement the TryGetMember method of the DynamicObject class for dynamic member calls. public override bool TryGetMember(GetMemberBinder binder, out object result) { result = GetPropertyValue(binder.Name); return result == null ? false : true; }
11. After the TryGetMember method, add the following code to override the TryInvokeMember10 method of the DynamicObject5 class. The TryInvokeMember10 method is called when a member of a dynamic class is requested with arguments. The binder argument contains information about the referenced member, and the result argument references the result returned for the specified member. The args argument contains an array of the arguments that are passed to the member. The TryInvokeMember10 method returns a Boolean value that returns true if the requested member exists; otherwise it returns false. The custom version of the TryInvokeMember method expects the first argument to be a value from the StringSearchOption enum that you defined in a previous step. The TryInvokeMember method expects the second argument to be a Boolean value. If one or both arguments are valid values, they are passed to the GetPropertyValue method to retrieve the results. C#
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 6 of 10
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 7 of 10
dynamic rFile = new ReadOnlyFile(@"..\..\TextFile1.txt"); foreach (string line in rFile.Customer) { Console.WriteLine(line); } Console.WriteLine("----------------------------"); foreach (string line in rFile.Customer(StringSearchOption.Contains, true)) { Console.WriteLine(line); }
3. Save the file and press CTRL+F5 to build and run the application.
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 8 of 10
selected. Select Console Application in the Templates pane. In the Name box, type DynamicIronPythonSample, and then click OK. The new project is created. 3. If you are using Visual Basic, right-click the DynamicIronPythonSample project and then click Properties. Click the References tab. Click the Add button. If you are using Visual C#, in Solution Explorer, right-click the References folder and then click Add Reference. 4. On the Browse tab, browse to the folder where the IronPython libraries are installed. For example, C:\Program Files\IronPython 2.6 for .NET 4.0. Select the IronPython.dll, IronPython.Modules.dll, Microsoft.Scripting.dll, and Microsoft.Dynamic.dll libraries. Click OK. 5. If you are using Visual Basic, edit the Module1.vb file. If you are using Visual C#, edit the Program.cs file. 6. At the top of the file, add the following code to import the Microsoft.Scripting.Hosting and IronPython.Hosting namespaces from the IronPython libraries. C#
7. In the Main method, add the following code to create a new Microsoft.Scripting.Hosting.ScriptRuntime object to host the IronPython libraries. The ScriptRuntime object loads the IronPython library module random.py. C#
// Set the current directory to the IronPython libraries. System.IO.Directory.SetCurrentDirectory( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\IronPython 2.6 for .NET 4.0\Lib"); // Create an instance of the random.py IronPython library. Console.WriteLine("Loading random.py"); ScriptRuntime py = Python.CreateRuntime(); dynamic random = py.UseFile("random.py"); Console.WriteLine("random.py loaded.");
8. After the code to load the random.py module, add the following code to create an array of integers. The array is passed to the shuffle method of the random.py module, which randomly sorts the values in the array. C#
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 9 of 10
9. Save the file and press CTRL+F5 to build and run the application.
See Also
Reference System.Dynamic3 System.Dynamic.DynamicObject5 dynamic (C# Reference)1 Concepts Walkthroughs for Features Added in Visual Studio 2010 (C# and Visual Basic) 11 Early and Late Binding (Visual Basic)2 Other Resources Implementing Dynamic Interfaces (external blog) 12
Links Table
1
http://msdn.microsoft.com/en-us/library/dd264741(v=vs.110)
2http://msdn.microsoft.com/en-us/library/0tcf61s1(v=vs.110) 3
http://msdn.microsoft.com/en-us/library/system.dynamic(v=vs.110)
4http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110) 5
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject(v=vs.110)
6http://go.microsoft.com/fwlink/?LinkId=187223 7
http://msdn.microsoft.com/en-us/library/zbhkx167(v=vs.110)
8http://msdn.microsoft.com/en-us/library/system.io(v=vs.110) 9
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012
Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)
Page 10 of 10
(v=vs.110)
10
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvokemember (v=vs.110)
11http://msdn.microsoft.com/en-us/library/ee378529(v=vs.110) 12
http://go.microsoft.com/fwlink/?LinkId=230895
Community Content
2012 Microsoft. All rights reserved.
http://msdn.microsoft.com/en-us/library/ee461504(d=printer,v=vs.110)
5/25/2012