|
|
Not entirely sure what Language you are using here but it looks very much like VB. Therefore assuming that it is VB.
On the surface your code looks correct. If I had to rewrite the code it would look something like this:
Module Module1
Dim distance As Decimal = 0
Dim answer As String = nothing
Sub Main()
Console.WriteLine("Do you want to convert miles or kilometers? (M or K)")
answer = Console.ReadLine()
Console.WriteLine("What is the distance?")
distance = Console.ReadLine()
If answer = "M" Then
Console.WriteLine("The converted value is: " convertToKM(distance))
Else
Console.WriteLine("The converted value is: " & converToML(distance))
End If
Console.ReadLine()
End Sub
Function convertToKM(distance) As Decimal
Dim km as Decimal = 0
km = distance / 0.62137
Return km
End Function
Function convertToML(distance) As Decimal
Dim ml as Decimal = 0
ml = distance * 0.62137
Return ml
End Function
End Module
|
|
|
|
|
Hello,
I am developing an application with VB6 that need to use serial communication (MSComm control). Each data received from the input must be processed in the OnComm procedure. I have problem handling this OnComm events.
My question is what happens when my program is working inside the OnComm() sub, and another OnComm event rises (receiving new data on the port while the processing of the first data hasn't finished yet) ??
Will my program not begin processing the second event until he finishes with the first, or it will handle them simultaneously, or it will keep the second data waiting in the input buffer .. ??
If you could explain to me what happens exactly I would be very grateful.
|
|
|
|
|
Member 10568908 wrote: If you could explain to me what happens exactly I would be very grateful. VB6 is not built for multithreading; the language has been replaced by VB.NET some time ago.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Eddy Vluggen wrote: VB6 is not built for multithreading
But it's an event-driven language as I know. But I still didn't get how events are handled in-there.
When there is short piece of code in an event procedure, everything goes ok. But when there is some "time consuming" code and the event can be raised frequently, here I can no longer understand what happening inside my program ..
|
|
|
|
|
Member 10568908 wrote: But it's an event-driven language as I know. It's also still a dead language, and having event's does not make it multithreaded.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I guess the events are going to be queued. At least a lot of events work like that. That means: As soon as you finish the work in your events (or you make a call to DoEvents and please... don't do that if you can avoid it...) the next event which should have been triggered while you were processing something should get processed.
At least that's how the Windows Message queue should work. But you have to test it to be sure it really works that way.
Example: A VB6 application with 2 Command Buttons.
Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Sub Command1_Click()
Debug.Print "Begin Command1"
Sleep 5000
Debug.Print "End Command1"
End Sub
Private Sub Command2_Click()
Debug.Print "Command2"
End Sub
If you execute the program and click on Command1 first and then on Command2 you should see that the "End Command1" messages executes before (or after in case of a call to DoEvents) the message "Command2". And that the Event of Command2_Click has been queued while the application was busy processing Command1. You can even Click on Command2 e.g. 3 times and the event will be executed 3 times after the Sleep from Command1 is finished.
But there are cases where this does not apply. An example is the Timer (at least the control you can drag on the form).
Important is that the events are sent through the "Windows message queue".
|
|
|
|
|
Hello Nicholas,
I would like to thank you so much for your help and your explanation.
I've tried your code and it explains clearly what the DoEvents instruction does. Actually I wasn't understanding how it works, so your code really helped me out.
Additionally, I've modified it to better understanding, and I think the execution of the code below shows that the events are queued as you've said.
Example: A VB6 application with 2 Command Buttons.
Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Sub Command1_Click()
Debug.Print "Begin Command1"
Do
c = c + 1
Sleep 500
DoEvents
Loop Until c = 10
Debug.Print "End Command1"
End Sub
Private Sub Command2_Click()
Debug.Print "Begin Command2"
Do
c = c + 1
Sleep 500
DoEvents
Loop Until c = 10
Debug.Print "End Command2"
End Sub
When you click in one Command, the program waits for 5 seconds before the "End Command" message appears. When you click on the first then the second, what happens is that :
Begin Command1
Begin Command2
End Command2
End Command1
The whole execution takes 10 seconds. Which means that when raising the command2 event, the execution of command1 code has stopped and waited until the command2 code has finished to be resumed.
This confirms also that it's not multi-threaded as Eddy Vluggen has said.
Thank you all for your help and interaction.
|
|
|
|
|
How do I code this to round my results to 2 decimal places?
Module Module1
Dim itemQuantity As Integer = 0
Dim itemPrice As Decimal = 0
Dim totalSales As Decimal = 0
Dim stateName As String
Dim taxRate As Decimal = 0
Dim taxAmount As Decimal = 0
Dim customerName As String
Sub Main()
Console.WriteLine("Please enter your name.")
customerName = Console.ReadLine()
Console.WriteLine("Please enter your state: NJ, FL, or NY")
stateName = Console.ReadLine()
Console.WriteLine("Please enter the number of items purchased.")
itemQuantity = Console.ReadLine()
Console.WriteLine("Please enter the price of the item.")
itemPrice = Console.ReadLine()
Call computeTotal()
Call computeTax()
Console.WriteLine("The total sales for " & customerName & " are " & totalSales & " .")
Console.WriteLine("The tax amount is " & taxAmount & " based on a tax rate of " & taxRate & " .")
Console.WriteLine("The total with tax is " & totalSales + taxAmount & " .")
Console.ReadLine()
End Sub
Function computeTotal() As Decimal
totalSales = itemQuantity * itemPrice
Return totalSales
End Function
Function computeTax() As Decimal
If stateName = "NJ" Then
taxRate = 0.07
ElseIf stateName = "FL" Then
taxRate = 0.06
ElseIf stateName = "NY" Then
taxRate = 0.04
End If
taxAmount = totalSales * taxRate
Return taxAmount
End Function
End Module
|
|
|
|
|
Use string.Format to format your values, rather than concatenation which prints all the digits.
|
|
|
|
|
hello all,
brand new to VB. just going through some online tutorials. i seem to encounter an error when using the stack and queue classes. when i enter my code
Private mystack As New Stack
or
Private q As New queue
I get an error 'Type expected'.
I can clear the error by entering
Private mystack As New Collections.Stack
or
Private q As New Collections.queue
Any ideas????
|
|
|
|
|
"queue" isn't the name of a type, but "Queue" is. The type is located in the System.Collections namespace, meaning that it cannot be found unless you "Import" it, or prefix the type with the namespace-name (like System.Collections.Queue).
Add the line "Imports System.Collections" at the top of the file, and all should be well.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Worked like a charm...Thanks
|
|
|
|
|
You're welcome
|
|
|
|
|
hi there, im very new to vb so please be kind..
this problem only arose after reading the filesystemwatcher chaos thread on here so please feel free to be partly responsible!
I have recently created an app to watch a selection of folders and pick up txt files using filesystemwatcher. I thought I had my app working with no problems until I saw the chaos thread and downloaded the c# filewatcherdemo which studies the events thrown by new files.
seems like my app handles notepad files OK. in fact, copying and pasting in to any of the watch folders causes no problem.. but saving as *.txt to the folder from ms word causes the app to lock up..
ok so heres where its extra vague - im not sure if the application is locked in an infinite loop caused by the double 'create' event thrown by ms word or whether its just something else..
ill post my code if anyone would care to have a quick look - this feels like showing my infant school drawings in a board meeting so go easy!! haha
thanks for reading
tony
|
|
|
|
|
It's possible that the program is becoming deadlocked due to the user interface thread waiting on an object that never becomes signaled.
Run it in the debugger, and when it locks up, break into it to see where the main thread is.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
hi richard.. thanks for your post!
as I was unaware of what was causing the lock, i felt as though I wouldn't know where to put any break points in the script... BUT I had a rough idea..
it turned out that the file it was looping on was a temp file "~$*.txt" which is created then deleted and my program wasn't checking or handling this in any way - it just pauses if the move isn't possible then tries the process again..
extra code to report this as 'file not moved' or infact I may even just exit the sub as the reported temp files aren't of any interest anyway..
cheers for the basic yet helpful advise!!
tony
p.s. I previously had a cross threading problem with the application which I sorted using invoke.required.. I believe that is fixed now.... 99.9%
modified 17-Apr-14 7:20am.
|
|
|
|
|
am Try to doing how to display transparent flash files over a running video using msdxm or wmp control or is there any other way. i have done it using window less video but now video quality is lose is there any way to solve this problem
|
|
|
|
|
Hi, I'm feeling really stupid at the moment as i have spent days poring over code examples to no avail. I want to send a message received from a client to a textbox on a form here is an example of the code i've been attempting to modify
Imports System
Imports Microsoft.Samples.SharedInterface
Friend Class ImplementationClass
Inherits MarshalByRefObject
Implements ISharedInterface
Function HelloWorld(ByVal message As String) As String Implements ISharedInterface.HelloWorld
Console.WriteLine(("Client says: " & message))
Return "Hello to you too, client"
End Function
End Class
my understanding is that this code is run in a separate thread when this code implements it
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Ipc
Module Module1
Sub main()
RemotingConfiguration.Configure("Server.exe.config", False)
Dim chan As IChannel
For Each chan In ChannelServices.RegisteredChannels
Console.WriteLine(chan.ChannelName)
Next chan
Console.WriteLine("Waiting for connections...")
Console.WriteLine("Press enter to exit.")
Console.ReadLine()
End Sub
End Module
I have moved the code out of sub main and into a form, where the form executes it on load, but that leave no reference to the thread or object from the interface. as a result i cannot use any data received through the interface beyond writing it to the console. i cannot directly reference the form in the implementation class and without a link to the form i cannot even use a delegate. any suggestions would be greatly appreciated.
|
|
|
|
|
Hi,
In all the Microsoft examples I've seen, the server is dumb, i.e. it does not interact with the remotable objects. This fairly common requirement is quite easy to implement, once you know how. The trick is to create a standard object on the server and then publish it for remoting using System.Runtime.Remoting.RemotingServices.Marshal .
Here's the example based on that MS ISharedInterface
Public Interface ISharedInterface
Function HelloWorld(input As String) As String
End Interface
This is the remotable class, implementing the interface, which will be created as a local object on the server. For simplicity in the example I just pass a reference to a TextBox to the constructor. The HelloWorld function executes on a non UI thread and has to Invoke the TextBox.
Public Class MessageReceiver Inherits MarshalByRefObject Implements ISharedInterface
Private ReadOnly log As TextBox
Private Delegate Sub Update(text As [String])
Public Sub New(log As TextBox)
Me.log = log
End Sub
Public Function HelloWorld(input As String) As String
log.Invoke(New Update(AddressOf UpdateTextBox), input)
Return input
End Function
Private Sub UpdateTextBox(text As [String])
log.AppendText(text)
log.AppendText(Environment.NewLine)
End Sub
Public Overrides Function InitializeLifetimeService() As Object
Return Nothing
End Function
End Class
Now we have the 'abbreviated' form class which is the UI for the server. In it I haven't shown the declaration for a multiline TextBox named logTextBox. The important stuff is the creation of a local object followed by separate 'remoting'. Most MS examples use tcp but I've configured for ipc as that is more appropriate for process to process communication on a single machine.
Public Partial Class MainForm Inherits Form
Private server As IpcServerChannel
Private receiver As MessageReceiver
Protected Overrides Sub OnShown(e As EventArgs)
MyBase.OnShown(e)
receiver = New MessageReceiver(logTextBox)
server = New IpcServerChannel("IpcPortName")
ChannelServices.RegisterChannel(server, False)
logTextBox.AppendText("IpcServerChannel created")
logTextBox.AppendText(Environment.NewLine)
RemotingServices.Marshal(receiver, "ServerObject.rem")
End Sub
End Class
Finally for completeness there is a console based client which fires a few messages at the server.
Public NotInheritable Class ClientApp
Private Sub New()
End Sub
Private Shared remoteObject As ISharedInterface
Public Shared Sub Main(args As String())
Try
remoteObject = DirectCast(Activator.GetObject(GetType(ISharedInterface), "ipc://IpcPortName/ServerObject.rem"), ISharedInterface)
For i As Int32 = 0 To 4
Console.WriteLine(" " & remoteObject.HelloWorld("Hi Server " & i))
Thread.Sleep(2000)
Next
Catch re As System.Runtime.Remoting.RemotingException
Console.WriteLine(re)
End Try
Console.WriteLine("Press enter to end...")
Console.ReadLine()
End Sub
End Class
All that code was converted from c# with http://www.developerfusion.com/tools/convert/csharp-to-vb/[^] so I'm not totally to blame if it doesn't work!
Alan.
|
|
|
|
|
Thank you so much for your reply. With some minor changes I got the code working. Here is the final result.
The MS ISharedInterface in a class library referenced by both the server and the client.
Public Interface ISharedInterface
Function HelloWorld(input As String) As String
End Interface
The message receiver in the windows forms project for the server
Imports SharedInterface
Imports System.Windows.Forms
Public Class MessageReceiver
Inherits MarshalByRefObject
Implements ISharedInterface
Private ReadOnly log As Textbox
Private Delegate Sub Update(text As [String])
Public Sub New(log As TextBox)
Me.log = log
End Sub
Public Function HelloWorld(input As String) As String Implements ISharedInterface.HelloWorld
log.Invoke(New Update(AddressOf UpdateTextBox), input)
Return input
End Function
Private Sub UpdateTextBox(text As [String])
log.AppendText(text)
log.AppendText(Environment.NewLine)
End Sub
Public Overrides Function InitializeLifetimeService() As Object
Return Nothing
End Function
End Class
The Form for the Server i used was just the standard form. i added a textbox and made it multiline in the form designer. here is the code
Imports System.Windows.Forms
Imports System.Runtime.Remoting.Channels.Ipc
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting
Public Class Form1
Private server As IpcServerChannel
Private receiver As MessageReceiver
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
receiver = New MessageReceiver(logTextBox)
Server = New IpcServerChannel("IpcPortName")
ChannelServices.RegisterChannel(Server, False)
logTextBox.AppendText("IpcServerChannel created")
logTextBox.AppendText(Environment.NewLine)
RemotingServices.Marshal(receiver, "ServerObject.rem")
End Sub
and finally the client in its own console application
Imports SharedInterface
Imports System.Threading
Public NotInheritable Class ClientApp
Private Sub New()
End Sub
Private Shared remoteObject As ISharedInterface
Public Shared Sub Main(args As String())
Try
remoteObject = DirectCast(Activator.GetObject(GetType(ISharedInterface), "ipc://IpcPortName/ServerObject.rem"), ISharedInterface)
For i As Int32 = 0 To 4
Console.WriteLine(" " & remoteObject.HelloWorld("Hi Server " & i))
Thread.Sleep(2000)
Next
Catch re As System.Runtime.Remoting.RemotingException
Console.WriteLine(re)
End Try
Console.WriteLine("Press enter to end...")
Console.ReadLine()
End Sub
End Class
Again, Many thanks for the example you coverted, and the prompt reply.
|
|
|
|
|
I'm creating a software package that we are deploying to multiple employees at one of our client's sites. This software is designed to gather system information (OS, 32/64-bit, machine name, etc.) and also check whether N-able and Lync Basic 2013 is installed, and install them if necessary.
Currently both the N-able and Lync installation packages are embedded within my assembly. If the user is missing either program, the file will be extracted and ran silently without any user input. The issue I'm running into is that the N-able installation requires admin privileges. All the computers have the same admin account (we set it up that way; they don't have a central server/domain) and I'm trying to have the N-able run under that account so that way the user is prompted with any messages.
From everything I've been reading it seems that I have to create some kind of intermediate program that my program runs, which then can run the N-able silent installation using the admin account. However I haven't been able to find any good tutorials/step-by-step guides on how to do this?
Anybody have any links to guides on how I can do this. I just need to know how I can start another process using the credentials of an admin account that I already know; the users don't know these credentials so I can't have them type them in. I have tried using Process.Start with various settings, CreateProcessAsUser, CreateProcessWithLogonW, etc. but they all give me errors such as "This operation requires elevated permissions, "A required privilige is not held by the client", etc. It doesn't matter if I do it through the .NET Framework, P/Invoke, or a separate library, as long as the guide instructs me how I can use it from my assembly it's good.
Any help that you can provide will be greatly appreciated...I'm supposed to have this finished within the next day or two. Thank you a lot in advance.
A black hole is where God tried to divide by zero.
There are 10 kinds of people in the world; those who understand binary and those who don't.
|
|
|
|
|
Do it differently. Instead of installing the required third party programs when your program is started by a user, install them during the installation process of your program - since the installation is run by a System account, that will work.
|
|
|
|
|
My program doesn't need to be installed. It is a single executable that I'm placing the client's DropBox folder and then sending a link to everyone. This way they can just click the link and the program will run without requiring any user interaction.
A black hole is where God tried to divide by zero.
There are 10 kinds of people in the world; those who understand binary and those who don't.
|
|
|
|
|
Well, therein lies the problem.
What you're talking about doing is a security risk. In order for your code to be able to do what you want to, you have to ship the username and password for an Admin account with the code, to all of the users. That's a big no-no. You're exposing yourself and the company to security risk by doing that.
Also, what if the admin account username/password changes? Now you have to update the code to use the new ones! Worse yet, what if the username/password changes on some machines and not others?? Now you're screwed.
The proper way to do it is to come up with an install package for your prereqs and install those before the user launches the application, not after they launch it.
|
|
|
|