Programming AutoCAD With C# - Best Practices [PDF]

  • 0 0 0
  • Gefällt Ihnen dieses papier und der download? Sie können Ihre eigene PDF-Datei in wenigen Minuten kostenlos online veröffentlichen! Anmelden
Datei wird geladen, bitte warten...
Zitiervorschau

Programming AutoCAD With C#: Best Practices Scott McFarlane Senior Software Engineer, Woolpert, Inc.

© 2012 Autodesk

Agenda 

Best Practices  Using Delegates to Reduce Duplicate Code  Using LINQ with the AutoCAD API  Abstraction and Dependency Injection  WPF and the Model-View-ViewModel design pattern

© 2012 Autodesk

Best Practices 

Proven  Standard  Finding a better way  Improving quality  Improving efficiency

© 2012 Autodesk

Topics 

Advanced Language Features 

Generics  Delegates  Lambda Expressions  Extension Methods  LINQ 

Design Patterns  



Abstraction Dependency Injection

Tools 

ReSharper © 2012 Autodesk

Delegates…

© 2012 Autodesk

What is a Delegate? 

A pointer to a function, which can be… 

Assigned to variables  Passed as arguments  Invoked through a variable reference

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

Generic Delegate Classes Action – no parameters, no return value.  Action – one parameter, no return value.  Action – two parameters, no return value.  Action – three parameters, no return value.  Etc… 

    

Func – no parameters, return value of the specified type. Func – one parameter, return value of the specified type. Func – two parameters, return value of the specified type. Func – three parameters, return value of the specified type. Etc… © 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

Using LINQ with the AutoCAD API

© 2012 Autodesk

Using LINQ with the AutoCAD API 

A very basic LINQ example



Could also be written as

© 2012 Autodesk

How Do the Following Declarations Differ?

© 2012 Autodesk

IEnumerable and IEnumerable 

IEnumerable is defined as follows:



IEnumerable extends IEnumerable as follows:

© 2012 Autodesk

IEnumerator and IEnumerator 

IEnumerator is defined as follows:



IEnumerator extends IEnumerator as follows:

© 2012 Autodesk

Some AutoCAD Classes that Implement IEnumerable SymbolTable (base class for all symbol tables)  AttributeCollection  BlockTableRecord  ObjectIdCollection  SelectionSet 

The Current property of the IEnumerator returns an ObjectId.

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

© 2012 Autodesk

Abstraction and Dependency Injection

© 2012 Autodesk

Why is Abstraction Important? 

The Problem  



Classes often contain dependencies on other classes to do their work. If a class makes assumptions about how its dependent classes are implemented, the class becomes difficult to reuse in combination with other components. Such classes are also very difficult to unit test because they cannot be isolated from their dependencies.

© 2012 Autodesk

Why is Abstraction Important? 

The Solution 

Establish a common set of protocols by which classes interact, separately from the classes themselves.  Promotes the use of software design patterns (particularly dependency injection) that result in code that is more testable, extensible, maintainable, scalable, and reusable.

© 2012 Autodesk

Typical Application Component

User Interface

Exception Handler Business Logic

Logger FILE

Component

Data Access

Configuration Web Service Client

© 2012 Autodesk

Typical Application IHostApplication

Host Application

Component IMessageBox

Interface

User Interface

IProgressBar

IExceptionHandler

Exception Handler

Business Logic

Logger ILogger

FILE

Component Interface

Data Access IDataRepository

IConfiguration

Configuration

ISomeWebService

Web Service Client

© 2012 Autodesk

Typical Application Fake IHostApplication Fake IMessageBox

Interface

Fake

IProgressBar

Fake IExceptionHandler Business Logic

ILogger

Fake

Fake Interface

Fake IDataRepository

IConfiguration

Fake Fake ISomeWebService

© 2012 Autodesk

Example 1 public class Example1 { public void DoTheWork() { DataRepository dataRepository = new DataRepository(); Logger logger = new Logger(); logger.Log("Getting the data"); DataSet theData = dataRepository.GetSomeData(); // Do some work with the data... logger.Log("Done.");

} }

© 2012 Autodesk

Example 2 public class Example2 { private readonly IDataRepository _dataRepository; private readonly ILogger _logger; public Example2(IDataRepository dataRepository, ILogger logger) { _dataRepository = dataRepository; _logger = logger; } public void DoTheWork() { _logger.Log("Getting the data"); DataSet theData = _dataRepository.GetSomeData(); // Do some work with the data... _logger.Log("Done."); } }

© 2012 Autodesk

Software Engineering Principles Separation of Concerns – This class is now only responsible for the specific job it was designed to do.  Abstraction – By using interfaces, we have established a set of protocols by which the components interact, separately from the classes themselves.  Inversion of Control – The class has relinquished control of the creation and initialization of its dependencies.  Dependency Injection – This pattern is based on Inversion of Control, and describes the way in which an object obtains references to its dependencies. 

© 2012 Autodesk

Demo 

Block Counter 

Count the number of inserts of each block (by name) in a drawing, and store the results to a database.

© 2012 Autodesk

WPF and the Model-View-ViewModel Pattern

© 2012 Autodesk

What is WPF? 

Windows Presentation Foundation  Next generation UI framework, combining…  3D and Hardware Acceleration (DirectX)  UI Toolbox and Developer Productivity (WinForms)  Powerful Animation Support (Adobe Flash)  Declarative programming and easy deployment (HTML)

© 2012 Autodesk

What is XAML? 

XAML == eXtensible Application Markup Language  A declarative programming language used to construct and initialize .NET objects.  XML Syntax  Tag names are class names  Attributes are properties (and events)  Note: Any .NET class can be used as long as it has a default (parameterless) constructor.  XAML is not necessarily unique to WPF.  With WPF, XAML is used to declaratively define the UI.  Everything you can do with XAML can be done in procedural code (but not the other way around). © 2012 Autodesk

Important XAML Concepts 



Type Converters 



WPF includes many built-in type converters

Markup Extensions

© 2012 Autodesk

Content Controls Derive from System.Windows.Controls.ContentControl  Constrained to contain a single item (Content property)  Three main varieties 

+ Buttons + + + + +

Button RepeatButton ToggleButton CheckBox RadioButton

+ Simple Containers + Label + ToolTip + Frame

+ Containers with a header + Expander + GroupBox + TabItem

© 2012 Autodesk

Items Controls Derive from System.Windows.Controls.ItemsControl  Can contain any number of items (Items property)  ItemsControl 



Selector  ListBox  ListView  ComboBox  TabControl  HeaderedItemsControl  MenuItem, ToolBar, TreeViewItem  StatusBar  TreeView © 2012 Autodesk

Range Controls Derive from System.Windows.Controls.RangeBase  Properties: Value, Minimum, Maximum  Events: ValueChanged  RangeBase 



ScrollBar  ProgressBar  Slider

© 2012 Autodesk

Text and Ink Controls 

TextBox  RichTextBox  PasswordBox  InkCanvas

© 2012 Autodesk

Layout Controls 

Canvas  StackPanel  WrapPanel  DockPanel  Grid

© 2012 Autodesk

Dependency Properties 

A Dependency Property is a class property that depends on some other provider (or providers) to determine its value.  Key features   

Change notification Property Value Inheritance Support for multiple providers



Classes that expose dependency properties must derive from DependencyObject.  You can only bind, animate and style dependency properties.

© 2012 Autodesk

The Model-View-ViewModel Pattern 

Separation of Concerns  Single Responsibility  Evolution of MVVM 

MVC (Model-View-Controller)  MVP (Model-View-Presenter)  PM (Presentation Model)  MVVM (Model-View-ViewModel) 

Developers are lazy 

Development tools must support design patterns

© 2012 Autodesk

The Model-View-ViewModel Pattern 

The View  



The user interface What the user “sees”

The ViewModel 

Defines the state and behavior of the view  Is an abstraction of the view  Exposes the Model such that it is easily consumable by the View.  Has no dependency on the view or any specific UI elements 

The Model 

An abstraction of the data associated with the application  Business logic  Has no dependency on the ViewModel or the View. © 2012 Autodesk

The Model-View-ViewModel Pattern

View

View-Model

Model

© 2012 Autodesk

Why Use MVVM? 

Promotes strong separation of display from state and behavior  ViewModel classes are easily shared/re-used  ViewModel classes are easily unit tested  Changes to the UI have less impact on procedural code

© 2012 Autodesk

How Does WPF Support MVVM? 

User Interface is defined using XAML  



Data Binding Infrastructure  



Can handle more robust UI logic Less procedural code needed No code needed to explicitly update the view Supports input validation

Data Templates    

Defined in the View (XAML) Creates a visual representation of ViewModel objects Can include any number of UI elements Uses data binding on object properties to display property values and/or customize the UI © 2012 Autodesk

How Does WPF Support MVVM? 

Resources  



Data Binding 



A resource can be virtually any .NET object Resources can be shared across multiple UI elements Properties of UI elements can be “bound” to ViewModel properties

Commands  

Allows a view to consume functionality of the ViewModel. Automatically enables or disable associated UI controls based on Command.CanExecute

© 2012 Autodesk

INotifyPropertyChanged Interface

© 2012 Autodesk

Autodesk, AutoCAD* [*if/when mentioned in the pertinent material, followed by an alphabetical list of all other trademarks mentioned in the material] are registered trademarks or trademarks of Autodesk, Inc., and/or its subsidiaries and/or affiliates in the USA and/or other countries. All other brand names, product names, or trademarks belong to their respective holders. Autodesk reserves the right to alter product and services offerings, and specifications and pricing at any time without notice, and is not responsible for typographical or graphical errors that may appear in this document. © 2011 Autodesk, Inc. All rights reserved.

© 2012 Autodesk