Loading ABBYY Engine - abbyy

I have this code in C++/CLI project:
CSafePtr<IEngine> engine;
HMODULE libraryHandle;
libraryHandle = LoadLibraryEx("FREngine.dll", 0, LOAD_WITH_ALTERED_SEARCH_PATH);
typedef HRESULT (STDAPICALLTYPE* GetEngineObjectFunc)(BSTR, BSTR, BSTR, IEngine**);
GetEngineObjectFunc pGetEngineObject = (GetEngineObjectFunc)GetProcAddress(libraryHandle, "GetEngineObject");
pGetEngineObject( freDeveloperSN, 0, 0, &engine )
last line throws this exception:
RPC Server in not available
What may causing this exception?

ABBYY FRE is a COM object. GetEngineObject() behaves like a normal COM interface method except it's a separate function. Which means the following: it doesn't allow exceptions propagate outside. To achieve this it catches all exceptions, translates them into appropriate HRESULT values and possibly sets up IErrorInfo.
You trying to analyze the exception thrown inside a method have no chances to find what the problem is. That's because internally it might work like this:
HRESULT GetEngineObject( params )
{
try {
//that's for illustartion, code could be more comlex
initializeProtection( params );
obtainEngineObject( params );
} catch( std::exception& e ) {
setErrorInfo( e ); //this will set up IErrorInfo
return translateException( e ); // this will produce a relevant HRESULT
}
return S_OK;
}
void intializeProtection()
{
try {
doInitializeProtection();//maybe deep inside that exception is thrown
///blahblahblah
} catch( std::exception& e ) {
//here it will be translated to a more meaningful one
throw someOtherException( "Can't initialize protection: " + e.what() );
}
}
so the actual call can catch exceptions and translate them to provide meaningful diagnostics. In order to obtain tha diagnostics you need to retrieve IErrorInfo* after the function retuns. Use code from check() function from the same example project for that. Just don't stare at the exception being thrown - you have no chances with that, let it propagate and be translated.

Related

Connectjboss 4 with Firebird 3 via Jaybird 2.214-jdk1.6 [duplicate]

As soon as my code gets to my while(rs.next()) loop it produces the ResultSet is closed exception. What causes this exception and how can I correct for it?
EDIT: I notice in my code that I am nesting while(rs.next()) loop with another (rs2.next()), both result sets coming from the same DB, is this an issue?
Sounds like you executed another statement in the same connection before traversing the result set from the first statement. If you're nesting the processing of two result sets from the same database, you're doing something wrong. The combination of those sets should be done on the database side.
This could be caused by a number of reasons, including the driver you are using.
a) Some drivers do not allow nested statements. Depending if your driver supports JDBC 3.0 you should check the third parameter when creating the Statement object. For instance, I had the same problem with the JayBird driver to Firebird, but the code worked fine with the postgres driver. Then I added the third parameter to the createStatement method call and set it to ResultSet.HOLD_CURSORS_OVER_COMMIT, and the code started working fine for Firebird too.
static void testNestedRS() throws SQLException {
Connection con =null;
try {
// GET A CONNECTION
con = ConexionDesdeArchivo.obtenerConexion("examen-dest");
String sql1 = "select * from reportes_clasificacion";
Statement st1 = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
ResultSet rs1 = null;
try {
// EXECUTE THE FIRST QRY
rs1 = st1.executeQuery(sql1);
while (rs1.next()) {
// THIS LINE WILL BE PRINTED JUST ONCE ON
// SOME DRIVERS UNLESS YOU CREATE THE STATEMENT
// WITH 3 PARAMETERS USING
// ResultSet.HOLD_CURSORS_OVER_COMMIT
System.out.println("ST1 Row #: " + rs1.getRow());
String sql2 = "select * from reportes";
Statement st2 = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// EXECUTE THE SECOND QRY. THIS CLOSES THE FIRST
// ResultSet ON SOME DRIVERS WITHOUT USING
// ResultSet.HOLD_CURSORS_OVER_COMMIT
st2.executeQuery(sql2);
st2.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs1.close();
st1.close();
}
} catch (SQLException e) {
} finally {
con.close();
}
}
b) There could be a bug in your code. Remember that you cannot reuse the Statement object, once you re-execute a query on the same statement object, all the opened resultsets associated with the statement are closed. Make sure you are not closing the statement.
Also, you can only have one result set open from each statement. So if you are iterating through two result sets at the same time, make sure they are executed on different statements. Opening a second result set on one statement will implicitly close the first.
http://java.sun.com/javase/6/docs/api/java/sql/Statement.html
The exception states that your result is closed. You should examine your code and look for all location where you issue a ResultSet.close() call. Also look for Statement.close() and Connection.close(). For sure, one of them gets called before rs.next() is called.
You may have closed either the Connection or Statement that made the ResultSet, which would lead to the ResultSet being closed as well.
Proper jdbc call should look something like:
try {
Connection conn;
Statement stmt;
ResultSet rs;
try {
conn = DriverManager.getConnection(myUrl,"","");
stmt = conn.createStatement();
rs = stmt.executeQuery(myQuery);
while ( rs.next() ) {
// process results
}
} catch (SqlException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// you should release your resources here
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
} catch (SqlException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
you can close connection (or statement) only after you get result from result set. Safest way is to do it in finally block. However close() could also throe SqlException, hence the other try-catch block.
I got same error everything was correct only i was using same statement interface object to execute and update the database.
After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.
Check whether you have declared the method where this code is executing as static. If it is static there may be some other thread resetting the ResultSet.
make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this
public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
LogUtil.logRequestMethod();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
ps.setInt( 1, idStatusPrevious );
ps.setInt( 2, idStatus );
rs = ps.executeQuery();
Long count = 0L;
if ( rs != null ) {
while ( rs.next() ) {
count = rs.getLong( 1 );
break;
}
}
LogUtil.logSuccessMethod();
return count > 0L;
} catch ( Exception e ) {
String errorMsg = String
.format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
LogUtil.logError( errorMsg, e );
throw new FatalException( errorMsg );
} finally {
rs.close();
ps.close();
}
A ResultSetClosedException could be thrown for two reasons.
1.) You have opened another connection to the database without closing all other connections.
2.) Your ResultSet may be returning no values. So when you try to access data from the ResultSet java will throw a ResultSetClosedException.
It happens also when using a ResultSet without being in a #Transactional method.
ScrollableResults results = getScrollableResults("select e from MyEntity e");
while (results.next()) {
...
}
results.close();
if MyEntity has eager relationships with other entities. the second time results.next() is invoked the ResultSet is closed exception is raised.
so if you use ScrollableResults on entities with eager relationships make sure your method is run transactionally.
"result set is closed" happened to me when using tag <collection> in MyBatis nested (one-to-many) xml <select> statement
A Spring solution could be to have a (Java) Spring #Service layer, where class/methods calling MyBatis select-collection statements are annotated with
#Transactional(propagation = Propagation.REQUIRED)
annotations being:
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
this solution does not require to set the following datasource properties (i.e., in JBoss EAP standalone*.xml):
<xa-datasource-property name="downgradeHoldCursorsUnderXa">**true**\</xa-datasource-property>
<xa-datasource-property name="resultSetHoldability">**1**</xa-datasource-property>

Eclipse warning

I am getting the following warning
Null passed for nonnull parameter of new java.util.Scanner(Readable) in
model.WordCount.getFile(File).
Why am I getting this and how do I get rid of this warning? Here is the method:
/**
* Receives and parses input file.
*
* #param the_file The file to be processed.
*/
public void getFile(final File the_file) {
FileReader fr = null;
try {
fr = new FileReader(the_file);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
Scanner input = null;
String word;
input = new Scanner(fr);
while (input.hasNext()) {
word = input.next();
word = word.toLowerCase().
replaceAll("\\.|\\!|\\,|\\'|\\\"|\\?|\\-|\\(|\\)|\\*|\\$|\\#|\\&|\\~|\\;|\\:", "");
my_first.add(word);
setCounter(getCounter() + 1);
}
input.close();
}
I had to initialize the FileReader to null to avoid an error. This is what triggered the warning though.
If the line
fr = new FileReader(the_file);
throws an exception, then fr remains null and will definitely not work in the Scanner. That's what the warning is about.
It's basically telling you that printing the stack trace of an exception is no proper error handling. Instead you should think about returning out of the method in case of that early exception. Or alternatively, you may want to put the exception handling block around all code of the method, not just around that single line. Then the warning will also vanish, as an exception would lead to not executing any further code in the method.

ADO.NET SqlDataAdapter how to clear an error condition

Let's say you invoke the update method of the SQlDataAdapter:
MyDataSet.Tables[0].DefaultView.RowStateFilter = DataViewRowState.ModifiedCurrent;
if (MyDataSet.Tables[0].DefaultView.Count > 0)
{
MySqlAdapter.Update(DS.Tables[0].DefaultView.Table);
}
and your user happens to have left a required column NULL, so the back-end complains about it, and your catch block traps the "cannot be null" sql exception. How do you clear the error state so that ADO.NET doesn't keep raising the same error again and again, even when the user supplies the required value? What object's method should be invoked, or what property should be changed, to put the adapter back into a state where the update can occur, as long as the missing value is supplied?
This doesn't seem to be enough:
internal void OnRowUpdating(object sender, System.Data.SqlClient.SqlRowUpdatingEventArgs e)
{
if (e.Status == UpdateStatus.ErrorsOccurred)
{
e.Row.RowError = e.Errors.Message;
e.Status = UpdateStatus.SkipCurrentRow;
}
}
When the user fills in the required value the "cannot be null" exception will go away. It's that easy, but then again I do the saving this way:
DataTable changes=MyDataSet.Tables[0].GetChanges();
if (changes!=null)
{
MySqlAdapter.Update(changes);
MyDataSet.Tables[0].AcceptChanges();
}

How to catch FacebookApiExceptions when using FacebookApp.ApiAsync in WP7?

I'm currently using Facebook C# SDK v4.2.1 and I'm trying to post something onto the user wall. It worked fine until I got an FacebookOAuthException (OAuthException) Error validating access token. error and I can't catch that exception and it crashes my app.
I'm using this call FacebookApp.ApiAsync("/me/feed", ...). Because it happens async I'm not sure where I have to put my try-catch block to catch that error but with no success
This is what I'm using:
private void shareFBButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
// ... code for preparing strings to post ...
try
{
// setup FacebookApp and params ...
app.ApiAsync("/me/feed", args, HttpMethod.Post, (o) => {
if (o.Error != null)
{
Debug.WriteLine("ERROR sharing on Facebook: " + o.Error.Message);
}
else
{
Debug.WriteLine("FB post success!");
}
}, null);
}
catch (Exception ex)
{
Debug.WriteLine("ERROR sharing on Facebook: " + ex.Message);
}
}
So can someone tell me where I have to put my try-catch block, so I can catch the OAuthException?
EDIT:
After further investigation, the FacebookOAuthExcpetion is thrown from Facebook C# SDK after the SDK catches WebException and FacebookApiException. For further information look at "Pavel Surmenok" his answer. That is exactly what is happening.
As of the moment the only solution for catching FacebookApiException (base class of all Facebook SDK exceptions) is to catch it in App.UnhandledException method. Check type of e.ExceptionObject and if it is a FacebookApiException set e.Handled to true and the app won't exit itself anymore.
I found a solution for my problem. Maybe I should rephrase my question.
"How to catch an exception which occurred on a background thread?"
Which is exactly what is happening in my original question. An exception is throw inside the Facebook C# SDK on a background thread because Api calls are executed asynchronously.
Maybe most of you already know this, but I didn't because I'm new to WP7 development.
Solution:
In App.UnhandledException event handler, just set the e.Handled flag to true. Then the app won't exit ifself.
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// catch Facebook API exceptions
// if handled is set to true, app won't exit
if (e.ExceptionObject is FacebookApiException)
{
e.Handled = true;
// notify user of error ...
return;
}
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
Not sure if this is the right way to catch an API exception, but works fine for now.
I've reproduced this trouble. As I can see, the exception is generated in FacebookApp.ResponseCallback method. It contains "try" block with two "catch" sections (one for FacebookApiException and one for WebException). In the end of each "catch" sections the exception is being rethrown and is never been handled (that's why your app crashes). So, the debugger says you about this (rethrown) exception.
Later in "finally" section they create FacebookAsyncResult with reference to this exception in the property "Error".
I think that your solution (to handle this exception in App.UnhandledException) is the most appropriate one.
By the way, it's interesting, why SDK developers decided to rethrow exceptions in FacebookApp.ResponseCallback.
The debugger usually does a good job of indicating where the exception came from. In the debugger, you can examine the exception details and look at the nessted InnerExceptions to find the root cause.
That said, if the exception is thrown from within the app.ApiAsync call, then the catch handler that you already have would catch any exceptions. By the looks of things in the SDK (I've only looked briefly), there are certain circumstances where exceptions are caught and forwarded to the callback in the Error property, which you are also checking.
By looking at the SDK code, it would seem that the exception being thrown is actually the FacebookOAuthException; is that the case? If that is the case, then it looks like this exception is never provided to the callback, but always thrown.
If you can give more details about exactly what the exception type is and where it's thrown/caught, I might be able to give a more useful answer.
Trying to catch the exception in App.UnhandledException does not work as it is on a different thread. But you can play with the 'error reason' property from authResult before doing the query and so you will avoid to have the exception thrown.
private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookAuthenticationResult authResult;
if (FacebookAuthenticationResult.TryParse(e.Uri, out authResult))
{
if (authResult.ErrorReason == "user_denied")
{
// do something.
}
else
{
fbApp.Session = authResult.ToSession();
loginSucceeded();
}
}

Zend_Rss_Feed_Reader -> How to avoid exception if the feed source gets invalid?

I had the following:
$feedUrl = 'http://www.something.org/?feed=rss2';
$feed = Zend_Feed_Reader::import($feedUrl);
$lastNews = array();
//etc...
return $lastNews;
The problem was that, if the feed didn't exist for somereason, Zend will throw an exception and all my website will stay useless with that exception message.
I end up doing like this:
try {
$feedUrl = 'http://www.something.org/?feed=rss2';
$feed = Zend_Feed_Reader::import($feedUrl);
$lastNews = array();
//etc...
return $lastNews;
}
catch (Exception $e)
{
return false;
}
It works, but I just made up this. Not sure if it's ok. Any suggestions?
Regards,
MEM
That essentially the way you handle an Exception. Im not sure if i would return false, my preference would probably be for an empty array so that i dont have to have an if statement encapsulating loops that use the return value... but thats entirely up to you.
The only other exception would be to use a more specific exception like
try {
}
catch(Zend_Feed_Reader_Exception)
{
}
This way if a different error occurs you can handle it in a different fashion. Im not sure that exception actually exists but there is probably one or more exceptions unique tot he Zend_Feed component. Take a look at the code or docs to figure out which one(s) you want to catch and handle.