Code snippits are great for inserting simple frequently used constructs,
like try/finally try/catch and so on. But, I don't know if I would use it
to replicate more complex, commonly used constructs rather than
abstracting that into a reusable form, which eliminates the need for
replication (replication of code is something I try to avoid as much as
possible).
As an example, I found that writing very simple editing commands in
.NET was extremely tedious compared to LISP, where it can be done
in typically less than half a dozen lines of code. In .NET, there was
much more code needed, to build simple commands that had no UI
and used the command line (e.g., like the 'ERASE' command).
To make it easier for me to quickly build those kind of commands in
.NET (where the pattern is to prompt for a selection set of objects,
possibly filtered, and then perform some action on each selected
object), I wrote a class that I can use to easily implement those kind
of commands, which factors out 95% of the 'grunt work' needed and
reduces the actual amount of code required to the absolute minimum.
The code in the class is consumed/reused by deriving new classes
from it, typically one for each editing command to be built. Below
are a few examples of how the resuable code in the class is consumed.
Note that most of the grunt work typically required by commands
that prompt for and then operate on a user selection, is delegated
to the base classes, e.g., things like document locking; transaction
management; object selection with filtering; iterating through the
selection; and even opening the objects.
The derived class merely needs to override a virtual method (called
ProcessEntity), that is called once for each each selected object,
that's passed as the parameter and is already open, and there it
can do what it needs to the object and bada bing, bada boom... done.
Of course, there's some performance overhead, but my experience
shows it to be neglegible, and certainly worth the productivtity gain.
namespace CaddZone.AutoCAD.EditorServices
{
////////////////////////////////////////////////////////////////////
// A class that implements a command to reset the color
// of selected block references to BYLAYER:
public class BlockRefPropertyReset : SelectionEditor<BlockReference>
{
protected override void ProcessEntity(BlockReference blockref)
{
blockref.ColorIndex = 256;
return EditorStatus.Continue;
}
[CommandMethod("BLOCKCOLORTOBYLAYER", CommandFlags.UsePickSet)]
public override void CommandHandler()
{
Execute();
}
}
///////////////////////////////////////////////////////////
/// CIRCLEOFFSET command:
///
/// This specialization of SelectionEditor implements
/// an editor that prompts you to select one or more
/// circles, and enter a distance. It then offsets each
/// selected circle's radius by the specified distance.
///
/// The larger thing which the trained eye will notice
/// about this, is that we have successfuly factored
/// out 95% of the 'grunt work' that must typically
/// be done in order to build relatively simple custom
/// AutoCAD commands, using the .NET API.
///
public class CircleOffsetEditor : SelectionEditor<Circle>
{
// Called after objects are selected, to
// obtain additional input:
protected override PromptStatus EndEditorInput( Editor ed )
{
PromptDistanceOptions ops = new PromptDistanceOptions( "" );
ops.Message = "\nCircle radius offset: ";
ops.AllowZero = false;
ops.DefaultValue = offset;
PromptDoubleResult res = ed.GetDistance( ops );
if( res.Status == PromptStatus.OK )
offset = res.Value; // store the value for use in ProcessObject()
return res.Status;
}
/// <summary>
/// Override this to gain access to the PromptSelectionOptions
/// that's used to get the selection of objects. Here we just
/// set the prompts to "Select/remove circles: "
/// </summary>
protected override void BeginSelect( PromptSelectionOptions options )
{
base.BeginSelect( options );
options.MessageForAdding = "Select circles: ";
options.MessageForRemoval = "Remove circles: ";
}
/// <summary>
/// This override is called once for each selected
/// object, which is passed in as the parameter.
///
/// The passed in object is already open for Write,
/// and cast to the Type of the generic parmeter
/// argument to this class (a Circle in this case).
///
/// This is where each object is Modified.
///
/// </summary>
protected override EditorStatus ProcessEntity( Circle circle )
{
if( circle.Radius + offset > 0.0 )
circle.Radius += offset;
return EditorStatus.Continue; // continue processing objects
}
// user-supplied offset distance:
private double offset = 1.0;
// Implement a command for this editor
[CommandMethod("CIRCLEOFFSET", CommandFlags.UsePickSet)]
public override void CommandHandler()
{
Execute();
}
}
////////////////////////////////////////////////////////////////////
// A class that implements the 'LENGTH' command, which
// measures the length of selected curves:
public class CurveLengthReporter : SelectionViewer<Curve>
{
protected override void Initialize()
{
totalLength = 0.0;
counted = 0;
base.Initialize();
}
protected override EditorStatus ProcessEntity( Curve curve )
{
try // Ignore eNotApplicable returned by rays/xlines
{
totalLength += curve.GetDistanceAtParameter( curve.EndParam );
++counted;
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
if( ex.ErrorStatus != ErrorStatus.NotApplicable )
throw ex;
}
return EditorStatus.Continue;
}
protected override string GetReportMessage()
{
if( counted > 0 )
{
return string.Format(
"Total length of {0} curves: {1}, average length: {2}",
counted, totalLength, totalLength / counted );
}
else
return "No curves were processed";
}
[CommandMethod( "LENGTH", CommandFlags.UsePickSet )]
public override void CommandHandler()
{
Execute();
}
private Distance totalLength = 0.0;
private int counted = 0;
}
//////////////////////////////////////////////////////////////
/// The SCALEWIDTH command
/// <summary>
///
/// The SCALEWIDTH command applies a scale factor to the
/// constant widths of a selection of polyLines.
///
/// Custom filtering:
///
/// This class also utilizes custom selection filtering, where
/// an overridden method of the base class examines each
/// object selected by the user, and acccepts or rejects it.
/// Custom filtering is enabled by overriding the FilterObject()
/// method. At runtime the SelectionEditor class will detect if
/// this method has been overridden in a derived class, and if
/// so, it will invoke the method to allow it to filter each object
/// selected by the user.
public class PolylineWidthScaler : SelectionEditor<Polyline>
{
// Get the scale factor to apply to each Polyline's width:
protected override PromptStatus EndEditorInput( Editor editor )
{
PromptDoubleOptions ops = new PromptDoubleOptions( "\nWidth scale factor: " );
ops.AllowNegative = false;
ops.AllowZero = false;
ops.DefaultValue = scaleFactor;
PromptDoubleResult res = editor.GetDouble( ops );
if( res.Status != PromptStatus.OK )
return res.Status;
if( Math.Abs( res.Value - 1.0 ) < 1.0e-6 )
{
Prompt( "\nScale factor cannot be 1.0," );
return PromptStatus.Other;
}
scaleFactor = res.Value;
return res.Status;
}
// Filter out polyLines whose constant width is nominally 0
protected override bool FilterEntity( Polyline polyline )
{
return polyline.ConstantWidth > 1.0e-6;
}
// Operate on each Polyline
protected override EditorStatus ProcessEntity( Polyline polyline )
{
polyline.ConstantWidth *= scaleFactor;
return EditorStatus.Continue;
}
[CommandMethod( "SCALEWIDTH", CommandFlags.UsePickSet )]
public override void CommandHandler()
{
base.CommandHandler();
}
private double scaleFactor = 1.0;
}
// only to show how rediculously simple it is to build commands
// with SelectionEditor<>, this example prompts for a selection set
// of circles, and changes their color to RED, and does it in only 4
// lines of code:
public class MakeCirclesRed : SelectionEditor<Circle>
{
protected override EditorStatus ProcessEntity(Circle circle)
{
circle.ColorIndex = 1;
return EditorStatus.Continue;
}
}
// To invoke the command, just use: new MakeCirclesRed().Execute();
}
So, while there's nothing wrong with snippets for reducing typing,
I think they can also be misused to replicate larger code constructs
that possibly shouldn't be replicated if that can be avoided through
carefully designed modular, reusable classes.
Glenn, since there is virtually no globals I have a sub that is the full monty way of adding an ent. Otherwise I was finding C# was way more verbose than vba. With as BlockTableRecord btr here and a BlockTableRecord btr there etc.
Well, if I may say so myself, I've found that trying to invent
your own API that offers the 'full monty' way of doing things,
will ultimately create more problems than it solves.
<snip>
I traversed this same path, asked myself the same questions you have asked yourself, and lamented all the extra work involved in using this API. But in the end, I agree with Tony.
We all know however that we are lazy and typing is not how we want to spend our days. If you're using Visual Studio as your IDE, I suggest Code Snippets. You can create snippets that encapsulate a logical action, like adding an entity to a database, although most of mine aren't quite that chunky, and modify the code after it's inserted.