.NET getting a ThreadStateException - asp.net

Hello I am getting an error on the following line:
If Not System.Windows.Clipboard.GetDataObject Is Nothing Then
I believe it would look something like this in C#
if (System.Windows.Clipboard.GetDataObject!=null) {
The Error is:
"ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made."
Can anyone tell me how to fix this? A few suggestions online mentioned adding <STAThread()> _ over the 'main' method, however, this is an ASP.NET controller method, I tried adding this over it and it didn't help. Anyone have any suggestions?

ASP.NET doesn't really get along with STAThread.
You need an additional task scheduler to run a thread in STA mode to access what you want from the operating system
Take a look at this article it got me going with something like this.
Also, keep in mind that multiple request to your page might mess up things, since you're interacting with the clipboard of the operating system (which runs in another COM context) son concurrency might by risky.
What are you trying to acomplish, maybe there is a better way.

Don't forget to read the final notes.
http://www.telerik.com/community/forums/community-forums/interesting-resources/using-clipboard-class-in-asp-net.aspx

It seems that this can be caused by an out of date dll in your /bin directory. Have you tried clearing it?
http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/2411f889-8e30-4a6d-9e28-8a46e66c0fdb/
http://www.devnewsgroups.net/windowsforms/t36723-current-thread-must-set-single-thread-apartment-sta.aspx
Also, you can explicitly start up a new thread in Single Apartment Mode
imports System.Threading
dim newThread As New Thread(new ThreadStart(AddressOf ThreadMethod))
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
'and elsewhere
Public Sub ThreadMethod()
If Not System.Windows.Clipboard.GetDataObject Is Nothing Then
'stuff
End if
End Sub

Related

How do you get code to execute at the end of a procedure?

I'm working on a new piece of code at work to assist the rest of the programmers in making app server calls. Previously we just had a .i file and relied on the developer to make sure you made all the right calls and cleaned up the app server connection at the end of the program. Obviously some people have forgotten to do that in the past and it's caused problems for us.
I've been building a basic appserver.cls file, but I can't figure out how to get it to disconnect at the end of the program.
I've tried the following things so far.
ON CLOSE OF THIS-PROCEDURE
DO:
clAppServer:cleanupAppServer().
END.
This doesn't seem to fire at the end of the webspeed call.
DESTRUCTOR appserver():
cleanupAppServer().
END DESTRUCTOR.
This works when it does garbage collection, but Progress doesn't seem to do garbage collection at the end of a webspeed call and the objects are still in memory (which is an entirely different issue that I need to deal with).
ON CLOSE OF SESSION:LAST-PROCEDURE
DO:
clAppServer:cleanupAppServer().
END.
This doesn't even compile obviously.
I've tried a whole bunch of other things that are variants on these three to no avail.
Is there any way to do what I'm asking? Bonus points if it can be inside the appserver.cls file.
If I understand the question, you want to disconnect from another AppServer once the work is done. Would try something along the lines of the below work?
Create a AppServer-handle-wrapper class. This class is responsible for the A/S connection; it has a public "Handle" (or similarly-named) property that you can use to run stuff on the AppServer.
In this class' destructor you can add code that does your clean-up : disconnect and delete server handle .
Code that wants to run something on the AppServer does something like ...
def var asConn as AppServerConnection.
asConn = new AppServerConnection().
run foo.p on asConn:Handle (param1, out param2).
// cause GC
asConn = ?.
// manually destroy
delete object asConn.
The destructor will then do the right thing.
Note that if you have this code in an internal procedure or method, then the variable would go out of scope at the end of it, and the GC would kick in.
There's an example of this approach at https://github.com/consultingwerk/ADE-Sourcecode/blob/566ac0a6e085d6305a8f364f13a1d805d3597d2a/src/netlib/OpenEdge/Net/ServerConnection/ClientSocket.cls
Bear in mind that in the ClientSocket is that the handle is private - you may want to make it public for a general AppServer connection.

'ChromiumWebBrowser' does not contain a definition for 'NewScreenshot'

I'm just looking into CefSharp and am confused about NewScreenshot. I've found lots of references to it as well as example code, but none of it works. I found it marked as obsolete in the 63.0 docs...
Has NewScreenshot been removed? If so, what replaces it (how can I tell that the screen has rendered)? For my purposes a blocking (non-async) method would work fine.
Update:
Searching the source for the latest version of CefSharp I find no reference to NewScreenshot.
I started with the Minimal Example that #amaitland referred to. I made a few changes, adapting it for my use. As part of that change I moved the Shutdown() call to the program's destructor.
When I ran the project I received a mystifying error about calling Shutdown() from a thread different than the thread from which Initialize() was called.
Looking through the code I saw ScreenshotAsync and, as I wasn't (knowingly) using another thread, suspected it may be involved. I looked for another way to get my SVG image and found NewScreenshot. Which of course didn't solve my problem, which was that the GC was running my destructor in a different thread (I had no idea that could happen).
At any rate, by this time I'd shucked ScreenshotAsync for NewScreenshot which is how I ended up here.
I set a breakpoint in my handler (which I haven't included as it's never called). Here's what I hope is the relevant code. I've omitted the init code but I believe it's unchanged from the example.
public static void Main()
{
private const string url = "https://www.google.com/";
browser = new ChromiumWebBrowser();
browser.Paint += OnBrowserPaint;
browser.Load(url)
Console.ReadKey();
}
In stepping through the code in the debugger, I set a breakpoint on browser.Load(url). If I examine browser.Paint, I find errors:
Here's the tooltip for DeclaringMethod:
I have no idea if this is related to my event handler not firing, but want to point it out in the event it is involved.
I appreciate your other suggestions but feel I need to find out why an event that should be firing is not.
I'll be happy to reduce and upload the project if it will help. Oh, and thanks for your help!

how to handle exceptions in vb.net?

I am creating a program in which a user can search and add their desired order. The problem that I'm facing now is that when I throw the exception, the program does not read the exception so that the user will know if the id that is entered is on the database or not. I will provide the code snippet of the program that I'm working on.
Problems
Your code will not throw an error if the item_code does not exist in your database. It will simply not enter the while loop.
This is not the proper use of an exception. It is not an error if the record is not found. The proper way of checking if the item_code exists is a check if the datareader has results.
You must properly defend yourself again SQL injection. By concatenating the sql query you are opening yourself up to a whole host of problems. For example, if a user maliciously enters the following text, it will delete the entire Products table: ';DROP TABLE Products;-
You are not disposing of the OleDbConnection or the OleDbCommand objects correctly. If an exception occurs, your code will not run the Dispose() method. This can cause you to quickly run out of resources.
Solutions
You should check if the dataRead has any rows. If it does not, then you can alert the user via javascript. Like so:
If dataRead.HasRows Then
//READ DATA
Else
//ALERT USER
End If
Solution #1 address Problem #2 as well
Use a parameterized query. The .NET framework will prevent these kinds of attacks (SQL Injection).
selectProductQuery = "SELECT * FROM Products WHERE item_code = #item_code"
...
newCmd.Parameters.AddWithValue("item_code", txtItemCode.Text);
Wrap all objects that implement Dispose() in a using block. This will guarantee everything is properly disposed of, whether an error is thrown or not.
Using newCon As New OleDbConnection(....)
Using newCmd As New OleDb.OleDbCommand(...)
...
End Using
End Using
To be perfectly honest, there is quite a bit "wrong" with your code, but this should get you headed in the right direction.
The line:
Response.Write(<script>alert('The ...')</script>)
Needs to be (note the quotes):
Response.Write("<script type='text/javascript'>alert('The ...')</script>")
Same for the other one at the top, but I dont think that will fix your overall problem.
Instead, use javascript like this:
if(!alert('Whoops!')){window.location.reload();}
to pop up an alert box and then reload the page after they click on the button.

Asp.Net MVC double submit/request breaks SQL connection

I am running into a strange problem I don't fully understand. The main symptom is that when I double click a link (that points to a controller action) in my MVC application, my database server connection gets blown, and I get the error :
Execution of the command requires an open and available connection. The connection's current state is broken.
If I step through starting at a breakpoint at the top of the controller action, it will step down a couple lines and then jump back up to the breakpoint. Somehow the first request isn't executing fully before the second one gets there, and somehow my database connection breaks when it gets to any query. Every time this happens, I have to restart the application server.
It was happening intermittently at first, but the double clicking of links seems to reproduce it everytime. Does this happen to anyone else? What am I missing here?
Thanks,
rusty
Update :
A.) I incorrectly tagged this as Linq-to-sql when we are actually using Linq-to-entities.
B.) The connection object is defined as a member variable of the controller :
namespace C2S.Controllers
{
public class ArtifactController : Controller
{
private c2sEntities _entities = new c2sEntities();
...
I noticed in some of the asp.net tutorials they declare the variable in the same spot but have a separate constructor for the controller where the db object is initialized. Does this make any difference?
C.) The problem is not only with the double-clicking as described above. The connection breaks at other seemingly random times; I cannot seem to reproduce the error consistently (even double-clicking does not always break it). Restarting the web site usually fixes it, although sometimes I have to restart the host machine. After its back up, repeating the same sequence of actions usually does not reproduce the same error!
Maybe there's something I don't understand about setting up my linq-to-entities classes or the nature of the database connection. Does anyone have any thoughts? I really don't even know how to investigate this one!
Thanks again
Rusty
It's a bit difficult to say from your description of the problem, but a first guess would be:
Is your connection object static (i.e. controller or application level) or defined locally within the action? Double clicking a link would fire the event twice and that sounds like what you are describing here. So the first call creates the connection, then the 2nd call comes in and tramps all over the 1st call to the method, breaking the connection it thinks it has.
Edit: Does the problem only occur on double clicks. Does it work as expected if you only single click on the link? An example of the code in question would help.
I am guessing that you're not properly closing your database connection. You should consider making use of the using statement.
using(SqlConnection conn = new SqlConnection("connstring")) {
using (SqlCommand cmd = new SqlCommand("SQLSTATEMENT", conn)) {
// more code here......
}
}
This will ensure that your connection is closed even if there's an error in your code somewhere.
Read all about it here: http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx

Error handling using events, checking if an error happened and react accordingly

I have an object, say Order where if an error occurs, it raises the ErrorOccurred event. If I'm running some code in say, the codebehind for a .aspx page with an public Order registered as WithEvents and I want to check to see if an error has occurred before I run more code, how do I do this? I can't simply check theOrder.ErrorOccurred. Do I have to create a local boolean flag that switches over in the event handler (OnErrorOccurred)? Or is there a better way to do this?
Thanks!
Example:
Public WithEvents theOrder As New Order
Public Sub DoStuff()
theOrder.DoSomething()
If theOrder.ErrorOccurred Then
do stuff
End If
End Sub
That seems like a reasonable approach. If there is lots of logic going on with an Order object that depends on knowing about errors, having a Status field would allow easy communication to any consumer what the status of the order was, rather than everyone having to subscribe to the event and track it themselves.
Alternately you could track it internally in the Order and just throw exceptions when critical methods were accessed if the Order was in an error state. This has the disadvantage of making you do more error handling, but would have the advantage of making sure that any Order consumer handled them explicitly.
Why not use structured error handling?
Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try
http://support.microsoft.com/kb/315965
This is what it is intended for.
Problems may arize if someone calls DoSomething but thay are unaware that they need to check theOrder.ErrorOccurred. based on what DoSomething is doing, allowing one to call a method and letting it fail quietly can be a problem.
If do something is doing logging sure, let it fail. If it is finalizing an order process..
Brian
Use the Try Catch Block
Try
'try your code here
Catch somevariablenamehere As Exception
'use methods from Exception class to get to know the error better and how to deal with it
Finally
'this is optional, If you want to do something finally, like cleaning up etc. You can do here
End Try
'to end the Try block

Resources