How to open a .DWG file in Autocad 2014 through C# - c#

Hi I have a requirement in which I have to open a drawing file stored in C:\Temp Folder.
I tried the following code
public void launchacad(string pth) //pth is the path to the .DWG file
{
const string progID = "AutoCAD.Application.19.1";
const string exePath = #"C:\Program Files\Autodesk\AutoCAD 2014\acad.exe";
AcadApplication acApp = null;
try
{
acApp =
(AcadApplication)Marshal.GetActiveObject(progID);
}
catch { }
if (acApp != null)
{
MessageBox.Show("An instance of AutoCAD is already running.");
}
else
{
try
{
ProcessStartInfo psi =new ProcessStartInfo(exePath);
psi.WorkingDirectory = #"C:\Temp";
psi.Arguments = pth;
Process pr = Process.Start(psi);
pr.WaitForInputIdle();
while (acApp == null)
{
try
{
acApp =(AcadApplication)Marshal.GetActiveObject(progID);
}
catch
{
Application.DoEvents();
}
}
}
catch (Exception ex)
{
MessageBox.Show(
"Cannot create or attach to AutoCAD object: "
+ ex.Message
);
}
}
if (acApp != null)
{
acApp.Visible = true;
acApp.ActiveDocument.SendCommand("_MYCOMMAND ");
}
}
But as soon as Autocad starts it popups an error message saying Cannot find the specified drawing. When I use CMD.exe and type
"C:\Program Files\Autodesk\AutoCAD 2014\acad.exe" "C:\Temp\41 Stabd.dwg" It opens Autocad with the file(41 Stand.dwg) open.
I can't understand where I am making an error. Can someone help me out.

If still the drawing persists with problems, continue on to the next set of steps.
These can be done in any order, but have been listed in the order that Autodesk recommends makes the most sense. The file can be checked after each step. If things appear back to normal, there is no need to continue on to the rest of the steps.
​Open a blank DWG and type RECOVER at the command line. Browse to the problematic file to - allow AutoCAD a chance to restore the file.
Type OVERKILL at the command line, and select all objects. Check or uncheck properties to include or ignore, then click OK.
Type DELCON at the command line, and select all objects.
Type BREP and select all objects (if there are solids or surfaces in the file)
Type -SCALELISTEDIT, then "R" for reset, then "Y" for yes.
Type FILTERS, then click on the 'delete filters' button.
The DGNPURGE tool can be run if the file size is unexpectedly very large: http://knowledge.autodesk.com/article/AutoCAD-DWG-files-unexpectedly-increase-in-file-size
Try using a different version of AutoCAD to open the drawing, such as AutoCAD 2013 vs. AutoCAD 2015 or plain AutoCAD vs. AutoCAD Architecture, etc. Try different computers if available.
Open a blank DWG, and try to attach the problematic file as an XREF. If it allows you to attach the file, try next to BIND it to the current file. If that works, run the repair steps listed above.
Use the SAVEAS command to save the DWG in an older file format. Attempt to open the newly created file.
Export the file to DXF format using the DXFOUT command. Next, open a blan DWG and use the DXFIN command to import the file just created.
< Restore the Layout tabs:
Right-Click one of the default layout tabs
Select 'From Template...'
Open the original file
Choose the layout tabs to restore. (It is recommended to do this one tab at a time, in case one or more layout tabs are corrupted)
Move drawing objects between model and paper space. You may find that only one drawing space is usable in your file, although your main concern is model space:
​​1. Create a new layout and if need be, create a viewport.
Use CHSPACE to move all the geometry to paper space.
Create a new drawing and use the Design Center (ADC) to move the layout from the damaged file into it.
Use CHSPACE again to move the geometry back to model space.
Restore the original layouts from the bad file using the Design Center.
Dissect the drawing. In a copy of the file, conduct a process of elimination using QSELECT to select different object types and then delete them to see if that fixes what is wrong in the file. Do PURGE All after each deletion. Eventually you should remove the problem elements and then you can choose to leave them out, copy them in again from another file, recreate them, or further troubleshoot individual items to pinpoint exactly which one is problematic. A quick start to this whole process is to delete everything in the drawing and then test it. This will quickly tell you if the issue is with a drawing object or if it is a part of the drawing database.​

Related

EditorUtility.OpenFilePanel is executed twice

I want to open an OBJ file in Unity using C# during runtime when I press L. However, the file dialog always opens twice. After I selected the first file, I get a new dialog. Whatever file I select the first and second time, both files are opened and displayed.
I have:
void Update ()
{
if (Input.GetKeyDown(KeyCode.L)) {
LoadObj();
//StartCoroutine(ExecuteAfterTime(5));
}
}
IEnumerator ExecuteAfterTime(float time)
{
yield return new WaitForSeconds(time);
}
void LoadObj()
{
string path = EditorUtility.OpenFilePanel("Load scan file", "", "obj");
\\Open the file and display it
}
I tried:
Add a time (see commented code above) -- did not work
Add a boolean that allows to execute LoadObj() only when the previous file is opened -- did not work
Added EditorUtility.OpenFilePanel() before or after yield return new WaitForSeconds(time) -- in the latter case, there is the delay of 5 seconds, but it still opens twice in both cases.
I searched for other solutions, but did not find anything else.
I work on a Windows machine and use Unity 2018. The aim is to open a single file at a time, but it must be possible to open another file, say, after a few minutes.
Any idea how to prevent the dialog from opening twice?
As #Eshan Mohammadi suggested, I checked if I only had a single instance of the code. I deleted the entire file, created a new one and added it to my GameObject. However, only then I noticed that this particular GameObject is copied, including the code, of course.
So, I chaned the way the GameObject was copied and problem solved.

Stand alone ".exe" matlab file not saving images

I'm trying to create an ".exe" file that will read some sort of data(for a known path), and will plot it one time as "bplot" and the other time as "histogram".
The code works fine as I run it from the editor, and even after I've made an ".exe" file. The problem begins when I try to run it from a "C#" code with the command "Process.Start(#"my_path.exe")". It seems like it runs the code and I can see the figures that are made, but it doesn't save the pictures.
My matlab code is:
clear
clc
P = csvread('my_path\test_csv.csv');
SP = bplot(P);
pause (3);
saveas(figure(1),[pwd '\picture1.jpeg']);
pause (3)
B = csvread('my_path\test2_csv.csv');
histogram(B);
pause (3)
saveas(figure(1),[pwd '\picture2.jpeg']);
pause (3)
close
clear
clc
The "bplot" is an external function that I downloaded.
Any ideas how to save it in other way so the stand alone application will save the images when I call it from C# code?
Try using the syntax with ProcessStartInfo parameter (see here), rather than syntax with the path the file directly.
Indeed if not setting ProcessStartInfo.WorkingDirectory, it will be considered to be %SYSTEMROOT%\System32 (for which you don't have write access as normal user)
var startInfo = new ProcessStartInfo(#"my_path.exe");
startInfo.WorkingDirectory= .... you exe dir or something else....;
Process.Start(startInfo);

Write into a log file with C#

I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}

IVsInvisibleEditorManager not placing document within Running Document Table

I'm working on a Visual Studio package and I seem to be running into an issue with IVsInvisibleEditorManager and the Running Document Table (RDT).
To start, I have a file opened within a normal Visual Studio editor. Next, I register an IVsInvisibleEditor for this same file via:
IVsInvisibleEditor invisibleEditor;
ErrorHandler.ThrowOnFailure(this._InvisibleEditorManager.RegisterInvisibleEditor(
filePath
, pProject: null
, dwFlags: (uint)_EDITORREGFLAGS.RIEF_ENABLECACHING
, pFactory: null
, ppEditor: out invisibleEditor));
When I modify the file and close the primary Visual Studio editor, I am prompted with a message to save my document. My understanding is that this should not be the case as I still have access to this file within my invisible editor. Visual Studio then cleans up some of the resources associated with this file, which breaks my invisible editor.
I suspect this is because RegisterInvisibleEditor() is not correctly registering my document within the RDT.
The documentation for RegisterInvisibleEditor() states the following for dwFlags when using _EDITORREGFLAGS.RIEF_ENABLECACHING:
This allows the document to stay in the RDT in the scenario where a
document is open in a visible editor, and closed by the user while an
invisible editor is registered for that document.
This describes my problem exactly. The visible editor is being closed, but I'd like the document to remain in the RDT.
Does anyone know how to make my document persists within the RDT?
Is the RDT project specific? Does the fact that I'm passing in null for both pProject and pFactory cause any problems for the RDT?
Edit: I just tested the above code out, but passed in the appropriate IVsProject and there was no change. It still appears the RDT is not changed when registering an invisible editor.
It doesn't appear as though I can convince the IVsInvisibleEditorManager to add a lock to the document. Unfortunately, RegisterInvisibleEditor() is a COM method, which means I can't decompile and peek at what it's doing (at least to my limited knowledge).
However, I've come up with a workaround in which I manually manage entries within the RDT.
var rdt =
(IVsRunningDocumentTable)GetService(typeof(SVsRunningDocumentTable));
//Retrieve the appropriate IVsHierarchy. I've assumed there's only
//one project within this solution.
var solutionService = (IVsSolution)GetService(typeof(SVsSolution));
IVsProject project = null;
Guid guid = Guid.Empty;
solutionService.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION, ref guid, out enumerator);
var hierarchy = new IVsHierarchy[1] { null };
uint fetched = 0;
for((enumerator.Reset(); enumerator.Next(1, hierarchy, out fetched) == VSConstants.S_OK && fetched == 1;)
hierarchy = hierarchyArray[0]
//Then when creating the IVsInvisibleEditor, find and lock the document
uint itemID;
IntPtr docData;
uint docCookie;
var result = rdt.FindAndLockDocument(
dwRDTLockType: (uint)_VSRDTFLAGS.RDT_ReadLock
, pszMkDocument: filePath
, ppHier: out hierarchy
, pitemid: out itemID
, ppunkDocData: out docData
, pdwCookie: out docCookie
);
At some point you'll be finished with your IVsInvisibleEditor, at which point you should unlock the document from the RDT.
runningDocTable.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, docCookie);

Wix - File is locked for delete after opening its database

I have some problems while trying using WindowsInstaller library or Wix Microsoft.Deployment.WindowsInstaller.
I'm, getting exception that the file being used by the process and I cannot delete it even though I've closed all record,view and database and disposed them.
try
{
string currentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string msiPath = "PathTo\MyMSI.msi";
using (InstallPackage installPackage = new InstallPackage(msiPath, DatabaseOpenMode.ReadOnly))
{
string query = "SELECT * FROM Property WHERE Property = 'ProductVersion'";
using (View view = installPackage.OpenView(query))
{
view.Execute();
using (Record record = view.Fetch())
{
string version = record.GetString(2);
Console.WriteLine(version);
record.Close();
}
view.Close();
}
installPackage.Close();
}
File.Delete(msiPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
And still I get the following:
Access to the path 'PathTo\MyMSI.msi' is denied.
I've also tried with the object
Database
Any help will be appreciated.
I was able to figure out what is blocking the delete action.
It appears that the file was in read only.
I don't know why I got this kind of exception but the following solved it:
//removing read only from file in order to interact with it
FileInfo fileInfo = new FileInfo(msiPath);
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
Hope it will help others.
I appreciate everyone who helped here for your time.
Below are some steps you could follow for ur problem :
Wait a minute and try deleting the file again, sometimes Windows or the program using the file may still be closing and therefore still using the file you're attempting to delete.
Close and Explorer window and re-open.
Locate the program using the file and close it. If you're uncertain what program is using the file, close all programs until you're able to delete the file.
Try using unlocker, a free software program designed to unlock any file being used by Windows or other programs without restarting the computer.
Reboot the computer. If after closing all programs you're still unable to delete the file, it's likely that something in the background is still using the file.
If after rebooting the computer you're still unable to delete the file, boot the computer into Safe Mode and delete the file.
Thanks

Categories