Плагин AutoCAD: C#: (System.Data.SQlite + SpatialiteSharp) ОШИБКА в AutoCAD 2016/2017
1) Моя среда:
, Windows 10 Pro (лицензированная) - 64 бита - 8 ГБ ОЗУ;
, AutoCAD (лицензировано) 2014/2015/2016/2017 64 бит (все HOTFIX и SERVICEPACK установлены);
, Visual Studio 2010 Express Edition (для AutoCAD 2014);
, Visual Studio 2013 (для AutoCAD 2015/2016/2017);
, Антивирус: только Защитник Windows.
2) Решение Visual Studio 2013
пакеты NuGet:
- System.Data.SQLite
- SpatialiteSharp
Цель: .NET 4.5
3) База данных, используемая для этого теста
, Имя базы данных: ' dbtest.sqlite ', скачать здесь и сохранить в c:\temp
, Таблица базы данных: ' tb_test '
, Поля таблицы базы данных tb_test:
- featureName: TEXT
- геометрия: ПОЛИГОН
4) Запуск кода в AutoCAD 2015: ОК
В Visual Lisp я вызываю метод dbQuery.NET (файл MyCommands.cs):
(setq result_query (dbQuery))
и вернет список:
[0] "FeatureName=first test area , MinX=101.23 , MinY=101.5 , MaxX=215.7 , MaxY=201.953 , Area=5532.771185"
[1] "FeatureName=second test area , MinX=100 , MinY=50 , MaxX=200 , MaxY=100 , Area=5000"
5) ПРОБЛЕМА:: Код работает на Autocad 2016/2017::
Ошибка: "Приложение Autodesk перестало работать"
Мой плагин работает нормально в AutoCAD 2014 (.NET 4.0) и AutoCAD 2015 (.NET 4.5), но не работает в AutoCAD 2016/2017.
Код такой же, но изменились только AcMgd/AcCoreMgd/AcDbMgd и Target DotNet Framework.
При отладке моего плагина происходит сбой
connection.LoadExtension("mod_spatialite");
Затем я получаю окно с сообщением о сбое AutoCAD:
Приложение Autodesk перестало работать
6) Мой код плагина AutoCAD 2017
Нажмите здесь, чтобы загрузить VisualStudio 2013 " AutoCAD2017SpatialiteTest " Решение
Код MyCommands.cs
// Test (System.Data.SQLite + SpatialiteSharp) in AutoCAD 2017 plugin
// Date: March, 7, 2017.
//
//==============================================================
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using System.Data.SQLite;
using SpatialiteSharp;
using System.IO;
using System.Reflection;
// This line is not mandatory, but improves loading performances
[assembly: CommandClass ( typeof ( AutoCAD2017SpatialiteTest.MyCommands ) )]
namespace AutoCAD2017SpatialiteTest
{
// This class is instantiated by AutoCAD for each document when
// a command is called by the user the first time in the context
// of a given document. In other words, non static data in this class
// is implicitly per-document!
public class MyCommands
{
private static readonly object Lock = new object ();
private static bool _haveSetPath;
//*******************************************************************
// LispFunction is similar to CommandMethod but it creates a lisp
// callable function. Many return types are supported not just string
// or integer.
//
//
//
[LispFunction ( "dbQuery", "dbQuery" )]
public ResultBuffer dbQuery ( ResultBuffer args ) // This method can have any name
{
try
{
// Create Spatialite SQL Connection
//
string databaseName = @"c:\temp\dbtest.sqlite";
string connectString = @"Data Source=" + databaseName + ";Version=3;";
SQLiteConnection connection = new SQLiteConnection ( connectString );
/// Open the database and load in the Spatialite extension
connection.Open ();
/// Loads mod_spatialite.dll on the given connection
///
lock ( Lock )
{
//Need to work out where the file is and add it to the path so it can load all the other dlls too
if ( !_haveSetPath )
{
var spatialitePath = Path.Combine ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ().Location ), (Environment.Is64BitProcess ? "x64" : "x86"), "spatialite" );
Environment.SetEnvironmentVariable ( "PATH", spatialitePath + ";" + Environment.GetEnvironmentVariable ( "PATH" ) );
_haveSetPath = true;
}
}
connection.EnableExtensions ( true );
connection.LoadExtension ( "mod_spatialite" );
// Make some Spatialite function calls
string sql = "SELECT featureName, ST_MINX(geometry), ST_MINY(geometry), ST_MAXX(geometry), ST_MAXY(geometry), ST_AREA(geometry) FROM tb_test ";
double minX = 0.0, minY = 0.0, maxX = 0.0, maxY = 0.0, area = 0.0;
string featureName = "";
string result_query = "";
// initialize resBuf list
//
ResultBuffer resBufCatch = new ResultBuffer ();
resBufCatch.Add ( new TypedValue ( (int)LispDataType.ListBegin ) );
// execute sql query
//
using ( SQLiteCommand command = new SQLiteCommand ( sql, connection ) )
{
using ( SQLiteDataReader reader = command.ExecuteReader () )
{
while ( reader.Read () )
{
featureName = reader.GetString ( 0 );
minX = reader.GetDouble ( 1 );
minY = reader.GetDouble ( 2 );
maxX = reader.GetDouble ( 3 );
maxY = reader.GetDouble ( 4 );
area = reader.GetDouble ( 5 );
// define string with fields values from 'tb_test'
//
result_query = String.Format ( "FeatureName={0} , MinX={1} , MinY={2} , MaxX={3} , MaxY={4} , Area={5}", featureName, minX.ToString (), minY.ToString (), maxX.ToString (), maxY.ToString (), area );
// add result_query to buffer
//
resBufCatch.Add ( new TypedValue ( (int)LispDataType.Text, result_query ) );
}
}
}
// finalize resBuf list
//
resBufCatch.Add ( new TypedValue ( (int)LispDataType.ListEnd ) );
// Close and clean up the database connection
//
connection.Close ();
connection.Dispose ();
// return result_query value to lisp function...
//
return resBufCatch;
}
catch ( System.Exception ex )
{
string exception_message = String.Format ( "Error : {0}", ex.Message );
ResultBuffer resBufCatch = new ResultBuffer ();
resBufCatch.Add ( new TypedValue ( (int)LispDataType.Text, exception_message ) );
return resBufCatch;
}
}
}
}
7) Вопрос
Кто-нибудь поможет мне запустить этот плагин AutoCAD2017?
Большое спасибо.
1 ответ
Есть ли у вас сообщение об ошибке, подобное этому после сбоя?
Если да, не закрывайте диалоговое окно и перейдите в папку C:\Users\\AppData\Local\Temp (%temp%). Должен быть файл с именем dumpdata.zip. В архиве есть xml-файл, который может дать вам более подробную информацию об ошибке, и .dmp-файл, который вы можете открыть в Visual Studio.