Execute method of an object on application crash in VB.Net - vb.net

I want to execute a function of an object when my application crashes. I have this third party library TMCTL which I am using in one of my form Main. This library is used to communicate with another windows application. Whenever my application is closed, its .Finish(CommID) method has to be executed. I have put this method in form's closing event. But sometimes, my application crashes due to unknown reasons. At that time this function doesn't get executed. This creates problem, when application is restarted.
I want to know is there any other way to execute this function apart from closing event. I tried using UnhandledException event in ApplicationEvents.vb. But I am not sure how to call TMCTL object in ApplicationEvents.vb from my form. I have declared it as Public in my form's code (Public cTmctl As TMCTL). It gives error if I try to call using Main.cTmctl in ApplicationEvents.vb

I don't think can be done this way, and if someone does come up with something I wouldn't trust it.
There are a couple of ways you could do this.
remember when you've started your 3rd party session (setting file, database, JSON file . . .), when the application closes properly you close the session and mark it as closed.
When your app starts again it can check was the last session closed. If yes, it starts another session, if no, it could (if possible) re-use the last session, or close the last session and create another.
or
Have a second service that mediates between your app and the 3rd party service. The new service (lets call it Middle Man), is called by your app to open the session on the 3rd party and to close it. The MM service monitors your app, if it has stopped running - or isn't responding - and there's an open session then it closes that session.
The second approach is helpful if you want the session to time out after some period of inactivity.

Related

Need to call functions and subs from windows services in VB.Net

I am new to vb.net and have a project that I have made my first windows service. Now I have a function that retrieves a count of transactions. I would like to call that function and put the results in a text file. I can hard code a stream to put into the text file, but whenever I call the function, the services just crashes. Not errors just dies. What am I doing wrong?
I have tried coding the function inside of the service-nope
I coded the function in a separate class-Nope! dies when I call it
Private Sub BrowserMailSender(obj As Object, e As EventArgs)
Try
FileIO.WriteToFile("service is started:" + Now + vbNewLine)
My_Count() 'service dies here
FileIO.WriteToFile("end" + vbNewLine)
Catch ex As Exception
MsgBox(ex)
End Try
the function works if I call from the main project but I would like the service to run and save the data behind the scenes.
The call to MsgBox is at the root of the problem. A Windows Service runs in a context where it does not have the ability to present a User Interface to the user. You'll have to find another way to communicate errors, such as the Event Log or a log file.
Prior to Vista, the line between services and the user was permeable, partly because the OS wasn't yet designed to keep them isolated, and partly because most users ran with full administrative privileges all the time. From Vista forward, you have to work "in the dark".
There are ways present a UI to the user, and one of the answers here briefly mentions one of them. However, I would caution you against trying to present a UI at all. The main principle of a service is that it sits in the background and does things without requiring the user to interact with it. Presenting a UI for events that the user is not aware are happening at that moment is an asymmetrical relationship. It could block your service indefinitely when a user isn't expecting to have to interact with it to allow it to continue.

Update GUI from another class in vb.net

I'm building a server and a client for a chat that runs on Tcp and Sockets, I want the client to handle more than one connection (to servers) so I made a class called "Client" to manage the async connection, so that I can run more instances at the same time like:
Dim ConnectionToServer1 as new Client
Dim ConnectionToServer2 as new Client
Since it's async when the the "connection" receives a message it generates an event (AsyncCallback) where I can convert the received bytes into a string.
The problem is: I've tried to set this string to a RichTextBox on my Form from inside the Client class, but nothing happens, I've tried to create a delegate in the form code but nothing works, the only way I was able to put the received message in the RichTextBox is by creating a public variable called LastMessage in the Client class where the last message is stored (every time it receives a message, the sub overrides the string), and then running a thread created by the Form which keeps checking for data (since the thread has been created by the form it has access to the controls, including the RichTextBox, right?)
Although I find this a bit clunky, is there any other way (through delegates maybe?) I can do it?
Here's some code:
Client class: http://pastebin.com/GF9um8Ss
Form code: http://pastebin.com/xW7mDj8j
Sounds like you started down all the right paths.
Now, on threaded applications one of the challenges that you will face is you can have tons of worker threads, but only the main, UI thread can actually make any updates to the UI. So keeping that in mind, if you have async code that needs to update the ui you will need to use what is effectively a delegate.
You can do this using tasks these days a lot easier, so read up on the Task Parallel Library, but essentially you need a delegate/task that is marshaled to run on the ui thread to handle the UI updates.
Set this global property as false
Control.CheckForIllegalCrossThreadCalls = false
this will let you edit any control of your form from any thread

Soft "Restart" Windows 8 App

I'm going to preface this by saying that I understand the new Windows 8 application lifecycle and how it is now 100% up to the user to decide if they want to terminate the app or not. So, I guess what I'm looking to find is a way to pseudo-restart my app, although I'm open to other suggestions as I'm pretty new to designing Modern UI apps.
I'm building an app that interfaces with a Web 2.0 service that requires authentication via OAuth. Fortunately the Windows 8 WebAuthenticationBroker makes this simple: it displays an asynchronous modal window that houses the web frame to allow the user to sign in and I get to provide a callback method when its done.
Now, obviously I only want to display this sign-in screen if I don't already have a session key stored for the user in roamingSettings.values. I used the Grid App template in Visual Studio, and I execute these functions in default.js as soon as the app is activated (checking roamingStorage, calling WebAuthBroker, etc). Now, the Grid App template provides a data.js to allow me to define some of the REST endpoints that I want to fetch. The main problem is that I can't fetch these REST endpoints until the user is authenticated! Yet they still have to (at least, I think) be declared in data.js ahead of time. So what I'm doing now to avoid errors in the event that the user isn't signed in, is the following:
if (roamingSettings.values[sessionKey]){
list = getFeedItems(); // my function that issues all the REST calls
} else {
list = new WinJS.Binding.List();
}
This works fine if the app is manually restarted after authentication is complete, but I would really rather have a way of completely reloading the app asynchronously after authentication is complete. I've spent a ton of time on this already and I'm getting extremely annoyed because I've seen other apps do this (Instametrogram, for example).
Any ideas?
To answer the core question here, how do you soft restart: window.location.reload() is all you need. This just does the refresh in place.
However, what you are actually looking to do is reset the datasource on the ListView instance -- all you need to do is get hold of that control at runtime, and re-assign the data source to it. E.g.:
var lv = document.getElementById("myListView");
lv.winControl.itemSource = list;
An example of this should also be in the app you have from when it currently assigns the list to the listview.

ASPNET out-of-proc session is mysteriously reset

I'm facing a very peculiar issue with sessions being reset without any apparent reason. This happens randomly, once every few tens or hundreds of requests.
My web application is running on windows 2003, IIS 6.0, .NET 1.1. The application has a webpage which populates a bunch of Session variables during its Page_Load event. The data is stored out of process in ASPNET State Service.
After the Page_load event exits and the page is displayed, the user clicks on a button, which retrieves the session data and does some work with it.
And this Button_click is where the issue occurs. On some occasions, the session variable is null, raising a nullRefException.
Our traces show that the sessionID during the Button_click event is a brand new session, with a different ID than the session of the Page_Load event. Thus, the application fails to retrieve the data that was stored during Page_Load. Our event log shows that the session variables for the problematic requests are indeed populated during the Page_load event, and the response is sent without issue, which normally would persist the data.
We have ruled out session timeouts; although a timeout would still result in the same nullRefException, the same session ID from Page_load would be used to retrieve non-existing data. In this case, the sessionID is different than the original.
We are not messing with the ASPNET cookie in any way, we do not use session.abandon, nor do we inadvertedly remove items from the session.
My question is: what server-side factors could cause the cardholder's session to be reset like that? The Application event log does not contain any useful info.
Also, is there anything client-side (e.g. cookie tampering) that could force IIS to assign a new session upon subsequent postbacks of the page?
Many thanks in advance.
I'm not sure if this applies to your situation, but it might help others.
I was designing a website and I found out the hard way, meaning I had to redesign a portion of this site I was working on. When you create or delete a folder (from an asp.net page) within the active IIS folder it resets all sessions for the website. This means every user currently on the site gets their sessions instantly deleted.
If you have control of your the server, store files outside the IIS folder and stream them in as needed. If you don't have control of the server, you will have to remove any work with folders.

Unattended application best practice question

We have an unattended app w/o a user interface that is is periodically run.
It is a VB.NET app. Instead of it being developed as a service, or a formless Windows application, it was developed with a form and all the code was placed in the form_load logic, with an "END" statement as the last line of code to terminate the program.
Other than producing a program that uses unneeded Windows form resources, is there a compelling reason to send this code back for rework to be changed to put the start up logic in a MAIN sub of a BAS file?
If the program is to enter and exit the mix (as opposed to running continuously) is there any point in making it a service?
If the app is developed with a Form do I have to worry about a dialog box being presented that no one will respond to even if there are no MessageBox commands in the app?
I recall there used to be something in VB6 where you could check an app as running unattended, presumably to avoid dialogs.
I don't know whether there are conditions where this will not run.
However, if the code was delivered by someone you will work with going forward, I would look at this as an opportunity to help them understand best practices (which this is not), and to help them understand that you expect best-practice code to be delivered.
First of all, you don't need it to be run in a Form.
Forms are there for Presentation, so it should not be done there.
If you don't want to mess with converting the application a Service (not difficult, but not very easy neither), you shoud create a Console Application, and then, schedule it with Windows Task Scheduler.
This way, you create a Console Application, with a Main function, that does exactly what you need.
Anyway, the programmer could show windows, so there should not be any messagebox. Any communication should be done via Logging to: local files, windows events, database.
If you want more information on any of them, ask me.
If you don't want it to be a service, nothing says that it has to be a windows service. Scheduling it to run via the Task Scheduler or something similar is a valid option.
However, it does sound like the developer should have choose a "Console App" project, instead of a "Windows Forms" project to create this app.
Send it back. The application is bulkier and slower than it needs to be, although that won't be much of an issue. It is somewhat more likely to run out of resources. But the main reason: converting it to a console app is very easy.
If you don't prefer for the Console window to popup, simply do the following.
Create a new class "Program.vb", add a public shared Main() method, and move the "OnLoad" logic from the form to this method.
Next delete the form, and change the project start up object (Available in the project properties window) to use the Program.Main instead of the Form.
This will have the same effect, without the windows forms resources being used. You can then remove the references to System.Windows.Form and System.Drawing.