Editor.GetEntity does not wait for user input (click) - vb.net

I have two dwg files: PID.dwg & 3D.dwg
The use case is to run a function on PID.dwg and then on 3D.dwg -- particularly in this order.
The commands used in SendCommand below are from a separate DLL file that I load using NETLOAD prior to this function's execution.
Dim app As AcadApplication = CType(Application.AcadApplication, AcadApplication)
' Ctype( Autodesk.AutoCAD.ApplicationServices.Application.AcadApplication,
' Autodesk.AutoCAD.Interop.AcadApplication )
If isPidAnd3dOpened() Then
' Activate PID document
app.ActiveDocument = acDocPid
'acDocPid.Activate()
acDocPid.SendCommand("DOSOMETHINGONPID" & vbCrLf)
' Activate 3D document
app.ActiveDocument = acDoc3d
'acDoc3d.Activate()
acDoc3d.SendCommand("DOSOMETHINGON3D" & vbCrLf)
End If
The function of "DOSOMETINGON3D" requires and input from the user using Editor.GetEntity.
However, when acDoc3d.SendCommand("DOSOMETHINGON3D" & vbCrLf) is executed, it does not pause to wait for user input.
What am I missing?

Probably You have to wait until the command DOSOMETHINGONPID is finished.
In ARX it would be something like this:
CString activeCMDName = _T("DOSOMETHINGONPID");
bool EOL = false;
while (!EOL)
{
CString cmds = Variable::Get(_T("CMDNAMES") );
if (cmds.Find( activeCMDName ) > 0 ) {
Command::Wait();
}
else {
EOL = true;
}
}
where
CString Variable::Get( CString name )
{
CString OutVal;
resbuf rb ;
acedGetVar(name, &rb);
OutVal.SetString(rb.resval.rstring);
acutDelString(rb.resval.rstring);
return OutVal ;
}
void Command::Wait()
{
ResBuf rb;
rb.Add(RTSTR , _T("\\"));
int ret = acedCmd(rb.GetFirst());
}
Sorry, I don't have this code in .net. Hope You will handle this.

First answer is correct, SendCommand cannot handle asynchronous commands. Here is a suggested solution in .Net:
//Create AutoCAD instance, then...
acadApp.ActiveDocument.SendCommand("(command \"NETLOAD\""+#"""C:\\acad\\networkdll\\SecondAssembly.dll"") ");
acadApp.ActiveDocument.SendCommand("#MYCOMMAND 0 ");
//Register EndCommand handler.
_DAcadApplicationEvents_EndCommandEventHandler handler = new
_DAcadApplicationEvents_EndCommandEventHandler(CommandEnded);
acadApp.EndCommand += handler;
waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
waitHandle.WaitOne();
acadApp.EndCommand -= handler;
//Close the startup drawing (this requires waiting # SendCommand) because
//Drawing will cause a COMException otherwise. 'Drawing is busy'
//Mostly likely since the ActiceDocument is the startup drawing.
Event Handler:
public void CommandEnded(string globalCommandName)
{
System.Windows.MessageBox.Show(globalCommandName + " just ended.");
waitHandle.Set();
}

Related

Read 'hidden' input for CLI Dart app

What's the best way to receive 'hidden' input from a command-line Dart application? For example, in Bash, this is accomplished with:
read -s SOME_VAR
Set io.stdin.echoMode to false:
import 'dart:io' as io;
void main() {
io.stdin.echoMode = false;
String input = io.stdin.readLineSync();
// or
var input;
while(input != 32) {
input = io.stdin.readByteSync();
if(input != 10) print(input);
}
// restore echoMode
io.stdin.echoMode = true;
}
This is a slightly extended version, key differences are that it uses a finally block to ensure the mode is reset if an exception is thrown whilst the code is executing.
The code also uses a waitFor call (only available in dart cli apps) to turn this code into a synchronous call. Given this is a cli command there is no need for the complications that futures bring to the table.
The code also does the classic output of '*' as you type.
If you are doing much cli work the below code is from the dart package I'm working on called dcli. Have a look at the 'ask' method.
https://pub.dev/packages/dcli
String readHidden() {
var line = <int>[];
try {
stdin.echoMode = false;
stdin.lineMode = false;
int char;
do {
char = stdin.readByteSync();
if (char != 10) {
stdout.write('*');
// we must wait for flush as only one flush can be outstanding at a time.
waitFor<void>(stdout.flush());
line.add(char);
}
} while (char != 10);
} finally {
stdin.echoMode = true;
stdin.lineMode = true;
}
// output a newline as we have suppressed it.
print('');
return Encoding.getByName('utf-8').decode(line);
}

Deleting handler from pipeline

I am trying to delete a certain handler from my handler pipeline, but I am having trouble doing it. When I list the handlers in the pipeline before and after, the handler that I tried to remove is still there. So what am I doing wrong here? Here is a code snippet. All of this is in the startup phase. You can see that last thing that I do is configure the pipeline factory. I am using Netty 3.6.1.final.
List<String> handlers = new ArrayList<String>();
// list handlers in the pipeline
try {
handlers = this.pipelineFactory.getPipeline().getNames();
for (int len = handlers.size(), i = 0; i < len; i++) {
String s = handlers.get(i);
System.out.println("Item " + i + " is " + s);
}
} catch( Exception e ) {}
try {
System.out.println("Remove hexdump");
this.pipelineFactory.getPipeline().remove("hexdump");
} catch( Exception e ) {
System.out.println("error = " + e.getMessage());
}
try {
handlers = this.pipelineFactory.getPipeline().getNames();
for (int len = handlers.size(), i = 0; i < len; i++) {
String s = handlers.get(i);
System.out.println("Item " + i + " is " + s);
}
} catch( Exception e ) {}
// Configure the pipeline factory.
this.bootstrap.setPipelineFactory(this.pipelineFactory);
Here is the output:
Item 0 is framer
Item 1 is hexdump
Item 2 is handler
Remove hexdump
Item 0 is framer
Item 1 is hexdump
Item 2 is handler
Not sure without checking out full code, but looks like pipelineFactor.getPipeline() will always create a new pipeline in your case. Since its a factory, it will be creating the handlers each time. Put in one more sysout for this.pipelineFactory.getPipeline() and if you are seeing 3 different object hashcodes then this is the root cause.
Solution could be pipeline = this.pipelineFactory.getPipeline(), and then using the pipeline for adding removing etc.
Also for the record, it seems wrong usage anyway, you should be getting the pipeline from the ChannelHandlerContext object either in a decode method or a messageReceived method of a handler.

Test zip password correctness in vb.net

I want to test if a zip has a particular password in vb.net. How can I create a function like check_if_zip_pass(file, pass) As Boolean?
I can't seem to find anything in the .net framework that does this already, unless I'm missing something incredibly obvious.
This method should NOT extract the files, only return True if the attempted pass is valid and False if not.
Use a 3rd party library, like DotNetZip. Keep in mind that passwords in zipfiles are applied to entries, not to the entire zip file. So your test doesn't quite make sense.
One reason WinZip may refuse to unpack the zipfile is that the very first entry is protected with a password. It could be the case that only some entries are protected by password, and some are not. It could be that different passwords are used on different entries. You'll have to decide what you want to do about these possibilities.
One option is to suppose that only one password is used on any entries in the zipfile that are encrypted. (This is not required by the zip specification) In that case, below is some sample code to check the password. There is no way to check a password without doing the decryption. So this code decrypts and extracts into Stream.Null.
public bool CheckZipPassword(string filename, string password)
{
bool success = false;
try
{
using (ZipFile zip1 = ZipFile.Read(filename))
{
var bitBucket = System.IO.Stream.Null;
foreach (var e in zip1)
{
if (!e.IsDirectory && e.UsesEncryption)
{
e.ExtractWithPassword(bitBucket, password);
}
}
}
success = true;
}
catch(Ionic.Zip.BadPasswordException) { }
return success;
}
Whoops! I think in C#. In VB.NET this would be:
Public Function CheckZipPassword(filename As String, password As String) As System.Boolean
Dim success As System.Boolean = False
Try
Using zip1 As ZipFile = ZipFile.Read(filename)
Dim bitBucket As System.IO.Stream = System.IO.Stream.Null
Dim e As ZipEntry
For Each e in zip1
If (Not e.IsDirectory) And e.UsesEncryption Then
e.ExtractWithPassword(bitBucket, password)
End If
Next
End Using
success = True
Catch ex As Ionic.Zip.BadPasswordException
End Try
Return success
End Function
I use SharpZipLib in .NET to do this, here is a link to their wiki with a helper function for unzipping password protected zip files. Below is a copy of the helper function for VB.NET.
Imports ICSharpCode.SharpZipLib.Core
Imports ICSharpCode.SharpZipLib.Zip
Public Sub ExtractZipFile(archiveFilenameIn As String, password As String, outFolder As String)
Dim zf As ZipFile = Nothing
Try
Dim fs As FileStream = File.OpenRead(archiveFilenameIn)
zf = New ZipFile(fs)
If Not [String].IsNullOrEmpty(password) Then ' AES encrypted entries are handled automatically
zf.Password = password
End If
For Each zipEntry As ZipEntry In zf
If Not zipEntry.IsFile Then ' Ignore directories
Continue For
End If
Dim entryFileName As [String] = zipEntry.Name
' to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
' Optionally match entrynames against a selection list here to skip as desired.
' The unpacked length is available in the zipEntry.Size property.
Dim buffer As Byte() = New Byte(4095) {} ' 4K is optimum
Dim zipStream As Stream = zf.GetInputStream(zipEntry)
' Manipulate the output filename here as desired.
Dim fullZipToPath As [String] = Path.Combine(outFolder, entryFileName)
Dim directoryName As String = Path.GetDirectoryName(fullZipToPath)
If directoryName.Length > 0 Then
Directory.CreateDirectory(directoryName)
End If
' Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
' of the file, but does not waste memory.
' The "Using" will close the stream even if an exception occurs.
Using streamWriter As FileStream = File.Create(fullZipToPath)
StreamUtils.Copy(zipStream, streamWriter, buffer)
End Using
Next
Finally
If zf IsNot Nothing Then
zf.IsStreamOwner = True ' Makes close also shut the underlying stream
' Ensure we release resources
zf.Close()
End If
End Try
End Sub
To test, you could create a file compare that looks at the file before it's zipped and again after it has been unzipped (size, date, etc...). You could even compare the contents if you wanted to use a simple test file, like a file with the text "TEST" inside. Lots of choices, depends on how much and how far you want to test.
There's not much built into the framework for doing this. Here's a big sloppy mess you could try using the SharpZipLib library:
public static bool CheckIfCorrectZipPassword(string fileName, string tempDirectory, string password)
{
byte[] buffer= new byte[2048];
int n;
bool isValid = true;
using (var raw = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var input = new ZipInputStream(raw))
{
ZipEntry e;
while ((e = input.GetNextEntry()) != null)
{
input.Password = password;
if (e.IsDirectory) continue;
string outputPath = Path.Combine(tempDirectory, e.FileName);
try
{
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
catch (ZipException ze)
{
if (ze.Message == "Invalid Password")
{
isValid = false;
}
}
finally
{
if (File.Exists(outputPath))
{
// careful, this can throw exceptions
File.Delete(outputPath);
}
}
if (!isValid)
{
break;
}
}
}
}
return isValid;
}
Apologies for the C#; should be fairly straightforward to convert to VB.NET.

Using Rx to Geocode an address in Bing Maps

I am learning to use the Rx extensions for a Silverlight 4 app I am working on. I created a sample app to nail down the process and I cannot get it to return anything.
Here is the main code:
private IObservable<Location> GetGPSCoordinates(string Address1)
{
var gsc = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService") as IGeocodeService;
Location returnLocation = new Location();
GeocodeResponse gcResp = new GeocodeResponse();
GeocodeRequest gcr = new GeocodeRequest();
gcr.Credentials = new Credentials();
gcr.Credentials.ApplicationId = APP_ID2;
gcr.Query = Address1;
var myFunc = Observable.FromAsyncPattern<GeocodeRequest, GeocodeResponse>(gsc.BeginGeocode, gsc.EndGeocode);
gcResp = myFunc(gcr) as GeocodeResponse;
if (gcResp.Results.Count > 0 && gcResp.Results[0].Locations.Count > 0)
{
returnLocation = gcResp.Results[0].Locations[0];
}
return returnLocation as IObservable<Location>;
}
gcResp comes back as null. Any thoughts or suggestions would be greatly appreciated.
The observable source you are subscribing to is asynchronous, so you can't access the result immediately after subscribing. You need to access the result in the subscription.
Better yet, don't subscribe at all and simply compose the response:
private IObservable<Location> GetGPSCoordinates(string Address1)
{
IGeocodeService gsc =
new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
Location returnLocation = new Location();
GeocodeResponse gcResp = new GeocodeResponse();
GeocodeRequest gcr = new GeocodeRequest();
gcr.Credentials = new Credentials();
gcr.Credentials.ApplicationId = APP_ID2;
gcr.Query = Address1;
var factory = Observable.FromAsyncPattern<GeocodeRequest, GeocodeResponse>(
gsc.BeginGeocode, gsc.EndGeocode);
return factory(gcr)
.Where(response => response.Results.Count > 0 &&
response.Results[0].Locations.Count > 0)
.Select(response => response.Results[0].Locations[0]);
}
If you only need the first valid value (the location of the address is unlikely to change), then add a .Take(1) between the Where and Select.
Edit: If you want to specifically handle the address not being found, you can either return results and have the consumer deal with it or you can return an Exception and provide an OnError handler when subscribing. If you're thinking of doing the latter, you would use SelectMany:
return factory(gcr)
.SelectMany(response => (response.Results.Count > 0 &&
response.Results[0].Locations.Count > 0)
? Observable.Return(response.Results[0].Locations[0])
: Observable.Throw<Location>(new AddressNotFoundException())
);
If you expand out the type of myFunc you'll see that it is Func<GeocodeRequest, IObservable<GeocodeResponse>>.
Func<GeocodeRequest, IObservable<GeocodeResponse>> myFunc =
Observable.FromAsyncPattern<GeocodeRequest, GeocodeResponse>
(gsc.BeginGeocode, gsc.EndGeocode);
So when you call myFunc(gcr) you have an IObservable<GeocodeResponse> and not a GeocodeResponse. Your code myFunc(gcr) as GeocodeResponse returns null because the cast is invalid.
What you need to do is either get the last value of the observable or just do a subscribe. Calling .Last() will block. If you call .Subscribe(...) your response will come thru on the call back thread.
Try this:
gcResp = myFunc(gcr).Last();
Let me know how you go.
Richard (and others),
So I have the code returning the location and I have the calling code subscribing. Here is (hopefully) the final issue. When I call GetGPSCoordinates, the next statement gets executed immediately without waiting for the subscribe to finish. Here's an example in a button OnClick event handler.
Location newLoc = new Location();
GetGPSCoordinates(this.Input.Text).ObserveOnDispatcher().Subscribe(x =>
{
if (x.Results.Count > 0 && x.Results[0].Locations.Count > 0)
{
newLoc = x.Results[0].Locations[0];
Output.Text = "Latitude: " + newLoc.Latitude.ToString() +
", Longtude: " + newLoc.Longitude.ToString();
}
else
{
Output.Text = "Invalid address";
}
});
Output.Text = " Outside of subscribe --- Latitude: " + newLoc.Latitude.ToString() +
", Longtude: " + newLoc.Longitude.ToString();
The Output.Text assignment that takes place outside of Subscribe executes before the Subscribe has finished and displays zeros and then the one inside the subscribe displays the new location info.
The purpose of this process is to get location info that will then be saved in a database record and I am processing multiple addresses sequentially in a Foreach loop. I chose Rx Extensions as a solution to avoid the problem of the async callback as a coding trap. But it seems I have exchanged one trap for another.
Thoughts, comments, suggestions?

Opening an MS-Cash Drawer, Wrong Code? Bad Code?

Humbling expierence here and I think this one will make a fool of me, but...I'm trying to convert an ancient cash register program to .net. Conquered everything else, but I can't pop open the cash register. Its connected to COM1, you are supposed to send a "trigger" text down COM1 that will cause the register to open.
Here is the .net code.
MsgBox("Opening Drawer")
Dim port As System.IO.Ports.SerialPort
port = New System.IO.Ports.SerialPort("Com1")
port.PortName = "COM1"
port.BaudRate = 9600
port.Parity = IO.Ports.Parity.None
port.DataBits = 8
port.StopBits = IO.Ports.StopBits.One
'port.Handshake = IO.Ports.Handshake.RequestToSend
port.RtsEnable = True
'port.DtrEnable = True
port.Open()
If port.IsOpen Then
'MsgBox("Attempt 1")
port.Write("####################")
MsgBox("Signal Sent: " & Chr(65))
Else
MsgBox("Port is not open")
End If
port.Close()
MsgBox("Pop, durn it!")
I get msgboxes "Signal Sent", "Done Pop Drawer"
Dang thing, just won't pop. It's an MS-Cash Drawer (EP125KC). Definitely connected to COM1, definitely has power. Chr(65) is the old code used to pop drawer and it works:
Open drawerComPort For Output Access Write As #1
Print #1, Chr$(65); "A";
Close #1
NOTE: The above code worked successfully. The root problem was caused by a reveresed power cord (negative was on the wrong side).
Thanks for all the help guys!
You've set your handshake to None but the cash drawer probably has its own idea. Also set DtrEnable to True. Chr(65) is the ASCII code for an "A", your VB code suggests the real command is "AA".
The manual documents that the cash drawer auto-tunes its baudrate. It recommends sending at least 20 # characters. And that the real command is Ctrl+G (Chr(7)). The "AA" command might have worked previously due to a baudrate mismatch. Perhaps.
If I remember my very rusty BASIC.
Print #1, Chr$(65); "A";
means print to port1 the character 65 followed by the string "A", Now the character 65 is 'A', so this looks to me like you should be sending "AA" to port1
port.Write("AA");
or alternately,
port.Write(new byte[]{65,'A'}, 0, 2);
It might be sending Unicode 65, which would be 0065, which would not end well.
Just a thought, can you try sending a raw int?
I dont use .net, but is the port buffered? do you need to send a flush/fflush()?
Are you sure you're supposed to send out this code? I would have always thought that the code is prefixed by ESC i.e. 0x1b hexadecimal...for cash drawers...
"\x1bA"
Interesting that double 'A' is used...oh well... :)
Edit: After thinking about this I realized there is another way of doing it, read on...
I have modified your original BASIC code with a bit of bullet-proofing...save it to opendrawer.bas
Sub OpenDrawer()
drawerComPort = "COM1"
Open drawerComPort For Output Access Write As #1
REM ADDED ERROR HANDLING
ON ERROR GOTO ErrHandler
Print #1, Chr$(65); "A";
Close #1
print "Drawer Ok"
OpenDrawer_Exit:
On Error Goto 0
Exit Sub
ErrHandler:
print "Oops, Write Failed"
Goto OpenDrawer_Exit
End Sub
REM The Main....
OpenDrawer
Download the old QB4.5 MS-Quick Basic compiler, and compile that to an executable, into opendrawer.exe, the QB4.5 can be found here. Now, the onus is on you to make this bulletproof, i.e. what happens if writing to COM1 fails, issue a message like in the example BASIC code I modified
Then you can use the System.Diagnostics.Process to shell out using a hidden window
public class TestDrawer
{
private StringBuilder sbRedirectedOutput = new StringBuilder();
public string OutputData
{
get { return this.sbRedirectedOutput.ToString(); }
}
public void Run()
{
System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo();
ps.FileName = "opendrawer";
ps.ErrorDialog = false;
ps.CreateNoWindow = true;
ps.UseShellExecute = false;
ps.RedirectStandardOutput = true;
ps.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = ps;
proc.Exited += new EventHandler(proc_Exited);
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.WaitForExit();
proc.BeginOutputReadLine();
while (!proc.HasExited) ;
}
}
void proc_Exited(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("proc_Exited: Process Ended");
if (this.sbRedirectedOutput.ToString().IndexOf("Oops, write failed") > -1){
MessageBox.Show(this, "Error in opening Cash Drawer");
}
if (this.sbRedirectedOutput.ToString().IndexOf("Drawer Ok") > -1){
MessageBox.Show(this, "Drawer Ok");
}
}
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (e.Data != null) this.sbRedirectedOutput.Append(e.Data + Environment.NewLine);
//System.Diagnostics.Debug.WriteLine("proc_OutputDataReceived: Data: " + e.Data);
}
The process shells out to a hidden window and all output is redirected and handled in the event handler...that should do the trick. Notice, how the redirected output goes into the sbRedirectedOutput (a StringBuilder instance). In the proc_ProcExited event handler, it checks the sbRedirectedOutput for the message 'Oops Write failed' which would be issued from the QB4.5 program.
Be aware, that you may need to include the QB4.5's run-time library in the same directory...not 100% sure...it's being years...
What do you think?
Hope this helps,
Best regards,
Tom.