0% found this document useful (0 votes)
521 views

Programming AutoCAD With C# - Best Practices

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
521 views

Programming AutoCAD With C# - Best Practices

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

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<T> – one parameter, no return value.
 Action<T1, T2> – two parameters, no return value.
 Action<T1, T2, T3> – three parameters, no return value.
 Etc…

 Func<TResult> – no parameters, return value of the specified type.


 Func<T, TResult> – one parameter, return value of the specified type.
 Func<T1, T2, TResult> – two parameters, return value of the specified type.
 Func<T1, T2, T3, TResult> – 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<T>

 IEnumerable is defined as follows:

 IEnumerable<T> extends IEnumerable as follows:

© 2012 Autodesk
IEnumerator and IEnumerator<T>

 IEnumerator is defined as follows:

 IEnumerator<T> 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
Host
Application
IHostApplication
Component
Interface IMessageBox User
Interface
IProgressBar

Exception
Handler
IExceptionHandler

Business Logic

Logger
ILogger
FILE

Component
Interface

Data Access
IDataRepository
IConfiguration

Configuration

Web Service
ISomeWebService Client

© 2012 Autodesk
Typical Application
Fake
IHostApplication
Fake
Interface IMessageBox
Fake
IProgressBar

Fake
IExceptionHandler

Business Logic

Fake
ILogger

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
 <TextBlock Text="Hello, world!" Foreground="Red" />
 WPF includes many built-in type converters
 Markup Extensions
<Button
Background="{x:Null}“
Height="{x:Static SystemParameters.IconHeight}“
Content="{Binding Path=Height, RelativeSource={RelativeSource Self}}"/>

© 2012 Autodesk
Content Controls

 Derive from System.Windows.Controls.ContentControl


 Constrained to contain a single item (Content property)
 Three main varieties
+ Buttons + Simple Containers + Containers with a
+ Button + Label header
+ RepeatButton + ToolTip + Expander
+ ToggleButton + Frame + GroupBox
+ CheckBox + TabItem
+ RadioButton

© 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
 Can handle more robust UI logic
 Less procedural code needed
 Data Binding Infrastructure
 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
 A resource can be virtually any .NET object
 Resources can be shared across multiple UI elements
 Data Binding
 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

You might also like