Tag Archives: Common Exception Handling

Invalid object name ‘UserInfo’

use ADO.NET Or other ORM framework, throw this exception, it may be the wrong database to connect. Maybe the database that the program wants to connect to is database1, and your configuration file or connection string is copied. If you neglect to modify it completely, this exception will appear.

Exception specific information

 NHibernate.Exceptions.GenericADOException : could not execute query
[ select userinfo0_.id as id0_, userinfo0_.name  as name2_0_, userinfo0_.description  as descript3_0_, userinfo0_.state  as state4_0_ from UserInfo userinfo0_ where userinfo0_.name ='testname' ]
[SQL: select userinfo0_.id as id0_, userinfo0_.name  as name2_0_, userinfo0_.description  as descript3_0_, userinfo0_.state  as state4_0_ from UserInfo userinfo0_ where userinfo0_.name ='testname']
  ----> System.Data.SqlClient.SqlException : Invalid object name 'UserInfo'.
	at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
	at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
	at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
	at NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters)
	at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)
	at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
	at NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results)
	at NHibernate.Impl.SessionImpl.List[T](String query, QueryParameters parameters)
	at NHibernate.Impl.QueryImpl.List[T]()
	UserInfoDAL.cs(21,0): at NHibernateWCF.DAL.UserInfoDAL.ExistUserInfo(String name)
	UserInfoDALTest.cs(18,0): at NHibernateWCF.Test.UserInfoDALTest.ExistUserInfoTest()
	--SqlException
	at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
	at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
	at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
	at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
	at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
	at System.Data.SqlClient.SqlDataReader.get_MetaData()
	at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
	at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
	at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
	at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
	at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
	at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
	at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()

This is the stack information in the case of NHibernate when the connection database is inconsistent. use ADO.NET Or other frameworks may be different in details, but they should all be exceptions of this kind in general.

The solution is to modify the connection string, change the database connected in the configuration to the correct database, so that the corresponding table can be found when executing SQL statements.

Solution to the problem of keyword not supported data source

When using the Entity Framework, if the connection string in the configuration file is not written correctly, this exception will be thrown. Moreover, when you modify the configuration file and press crtl + s to save, you will be prompted in the output window. The solution is to correct your connection string again. The correct format is as follows

<add name="testEntities" 
     connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" 
     providerName="System.Data.EntityClient" />

The built-in filter function in Excel can’t contain all the items

In an excel file, the columns include name, age, gender, etc.

Now there are 800 pieces of data, including 20, 21, 22, 25 and so on. Now using the filter function, it is found that there are no 25 items in the drop-down list. The reason for this phenomenon may be that there are blank lines in the middle. For example, if line 600 is a blank line and does not contain any content, the filter only filters lines 1 to 600. At this time, the drop-down list only contains the age values that have appeared in the first 600 lines. After using keywords for filtering, 601-800 rows of records will also be displayed in the results. However, we found that the line numbers of the records filtered out from 1 to 600 are blue, while the line numbers from 601 to 800 are black. Therefore, the 200 lines are completely displayed there without any filtering.

Note that the blank line here means that all cells in this line have no values, or even spaces. Even if the value of only one cell in a row is a space, although it looks like a blank row, excel will not treat it as a blank row when recognizing it.

Using code to create control objects, set the event listening method does not execute

This is in a WinForm program, click a button on the interface to generate another thread, generate WebBrowser control, and increase event monitoring

private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(m)); t.Start();
        }

        private void m()
        {
            WebBrowser w = new WebBrowser();
            w.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(w_DocumentCompleted);
            w.Navigate("www.baidu.com");
        }

        private void w_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MessageBox.Show("OK");
        }

When the program is running, you can find that there is no ok window pop-up. If you set the breakpoint, you will find that there is no w at all_ Run in the documentcompleted method. The reason is that the thread of the browser ends after executing the m method, and there is no time to execute the event listening method. At this point, there is a way to use the message box to make the thread temporarily not disappear

private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(m));
            t.ApartmentState = ApartmentState.STA;
            t.Start();
        }

        private void m()
        {
            WebBrowser w = new WebBrowser();
            w.DocumentCompleted +=new WebBrowserDocumentCompletedEventHandler(w_DocumentCompleted);
            w.Navigate("www.baidu.com");
            MessageBox.Show("AAA");
        }

        private void w_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            MessageBox.Show("OK");
        }

Now, if the thread does not disappear after AAA, then the event will be monitored and OK will appear

A first chance exception of type ‘ System.NullReferenceException ‘when occurred, you did encounter a bug

Maybe when you debug the program in Viusal studio, you find that output windows prints out a line of information about a first chance exception of type ‘ System.NullReferenceException ‘occurred, you may have wondered what is the first chance exception, Does this sentence mean that there is something wrong with my code?But if there is a problem, why does my program not throw any exception but display such a message in output windows?If I don’t look at the output window, I may not find this message at all.

 

Let’s talk about the first chance exception. When you are debugging a program in VS, when there is a problem with the program, it is the debugger (which can also be understood as vs itself) who first catches the exception. At this time, vs has to decide how to solve the problem.

 

    is to stop now, throw out the problem, pop up a dialog box, tell the user that there is a problem in your program, and let the user decide whether to continue or stop.

 

    leave it alone. If the user has a try catch, let the user’s own code process it. If there is no try catch, let the runtime capture it and then let the runtime process it. But when debugging, it is still vs to capture again.

 

 

So what does vs rely on to decide how to deal with it?Under debug settings, if CLR exception is checked, vs will catch an exception. It will not only print a message in output windows, but also pop up a dialog box to notify the user.

 

If there is no check here, then vs does nothing, just like there is no such thing.

For example, like the following code,

If vs catches and throws, the program stops at line 36 and notifies the user. If vs lets it go, the program jumps to line 39 and continues to execute the processing logic of the code.

Two concepts need to be understood. When C # programs are really running, it is runtime. As the top manager, exception will be thrown here. When debugging in VS, VS Runtime is the top manager, exception will throw it here, so that VS can notify users through the form of dialog box. First chance exception will inform the user through the pop-up box. If the user selects continue, the program can continue to run. However, if the code does not have a corresponding capture mechanism to deal with it, it is thrown to vs runtime again and captured, then it is called second chance exception. At this time, a dialog box will pop up again, but this time, the code will not continue to run.

Moreover, it should be noted that if we do not check the above option, vs will throw an exception dialog box on line 39 when calling the program.

But if we check it, we will throw an exception dialog box where the 52 line exception actually occurs.

Some people will ask if I should check it?If your project references a heavyweight tool like NHibernate, the DLL itself is likely to throw exceptions in many places, but the DLL itself has try If you check “catch”, vs will capture the catch code block before it is processed, and then inform the user. There will be a lot of such cases. As a result, the user will point to a lot of continue dialog boxes. Don’t check it at this time.

Reference link:

https://blogs.msdn.microsoft.com/davidklinems/2005/07/12/what-is-a-first-chance-exception/

http://dzimchuk.net/post/when-a-first-chance-exception-of-type-xxx-occurred-you-really-have-a-bug

Handling nullreference exception problems encountered in NHibernate

Recently, when using NHibernate, we encountered a very strange problem. When calling Session.SaveOrUpdate () method, an exception was thrown.

 

Look at the screenshot below. Although this exception was caught by vs in the catch line, the real problem is inside the try code block. As for how to make vs catch and prompt when problems occur, there is a detailed introduction in my other blog articles. I won’t talk about it here.

 

The code to throw an exception is as follows:

 

 

 

 

In the end, it’s the call Session.SaveOrUpdate The exception thrown when (). And I’ll go to the details of exception to see if there are any hints, but there are no valuable clues such as innerexcitation and message. Later, I kept thinking about why there was a problem, and finally found the root of the problem, which is current_ session_ context_ There’s something wrong with class.

 

The scene is like this. My project is a web project, in which NHibernate is used, and then I write the configuration in the web.config In the middle. After that, I wrote some new methods, and then set up a unittest project. Later, I need to move all the content related to NHibernate in order to test these service methods. I’ll take it web.config The content in is copied to the app.config The session context in NHibernate is still web, which is the reason for the problem.

 

 

Then I changed it to thread_ Static, the problem is solved. The reason is that the project of unittest does not have IIS. If session is still obtained from the web at this time, it will be null, so an exception is thrown.

[unable to read project file xxxxx, XXX failed to load project file, name cannot start with “<" character (hex value 0x3c)] exception handling method

Recently, I took over a new project. I downloaded the source code from SVN server to local. When I opened it with visual studio, I reported this exception at the moment of opening it.

Loading D: \% project \% SVN\ xx.csproj …

D:\Project\SVN\ xxx.csproj : error: unable to read project file“ xxx.csproj ”。

D:\Project\SVN\ xxx.csproj (20,2): failed to load project file. The name cannot start with the “& lt;” character (hex value 0x3c). Line 20, position 2.

Then, according to the prompt, I found the position of line 20. Sure enough, there are some problems here.

This is caused by something wrong with SVN. SVN version control software will add content to the csproj file. There should be something wrong with one step.

Solution: in the csproj file, find the problem line, and then delete it from line 20 to line 26.

Winsw throws an exception “error 1067: unexpected process termination” when converting Java application to Windows Service

Using winsw (GitHub) https://github.com/kohsuke/winsw )It is very convenient to convert Java application into windows service and deploy it on Windows Server.

Detailed operation steps can be searched, the document is relatively rich.

Here’s a problem I had. After I have configured every step according to the documentation, there is no problem with the service installation. Then when I start, the service throws an exception “error 1067: unexpected process termination”

public class App 
{
    public static void main( String[] args ) throws IOException, InterruptedException {
        Logger logger = LogUtil.getLogger();

        logger.info("a");
        logger.severe(new Date().toString());
        
    }
}

The reason is that the main method of Java module is not blocking. When the service is started, winsw will execute the Java – jar command in the configuration file to start a process, and record the process ID of the process, and then there will be a series of operations. The main method here is not blocking. Java jar starts the process, and winsw remembers the process ID. however, when the process information is used later, it is found that the process has terminated, so an exception is thrown.

Solution: the process should be a blocking process, that is, the process cannot end. The following code is OK.

public static void main( String[] args ) throws IOException, InterruptedException {
        Logger logger = LogUtil.getLogger();

        logger.info("a");
        logger.severe(new Date().toString());
        while (true) {
            logger.info("a");
            logger.severe(new Date().toString());
            Thread.sleep(10000);
        }
    }

Note that blocking doesn’t work System.in.read (), because in a non command line environment, this line of code will not have any running results.

Springboot application itself is a blocking application, so when using winsw tool to create windows service for springboot, this problem will not occur.

The socket connection was aborted in WCF

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host.

It may be that there is a DataTable in the data transmission of WCF. If it is a DataTable without a name, the above exception will be thrown.

Another exception is there was an error while trying to destroy parameter

The reason is that an empty table cannot be serialized. The possible reason is that the table is null and a null cannot be serialized

 

 

 

 

 

 

Ora-01008: not all variables are bound

OPEN PO_EXPCUR FOR V_QUERY_SQL USING …

This code will throw ora-01008 when the parameter setting is wrong: not all variables are bound

Reason: when executing a dynamic SQL statement, the number of variables filled in the SQL string is inconsistent with the number of variables bound in the using keyword.

May cause (ora-01006: binding variable does not exist) problems

There are many times that all kinds of reasons can cause this problem. Now we will talk about a relatively small reason.

V_QUERY_SQL  =  ‘SELECT  COUNT(DISTINCT (B.BATCH_ID))  FROM T_DD_RES T
        JOIN T_DD_REQ Q
        ON T.ID_DD_REQ = Q.ID
        JOIN T_DD_BATCH B
        ON T.BATCH_ID = B.BATCH_ID  WHERE T.INSERT_TIME >= TRUNC(PI_DATE)
         AND T.INSERT_TIME < TRUNC(PI_DATE) + 1
         AND Q.REQUEST_DATE >= TRUNC(PI_DATE)
         AND Q.REQUEST_DATE < TRUNC(PI_DATE) + 1 
         AND B.CDATE >= TRUNC(PI_DATE)
         AND B.CDATE < TRUNC(PI_DATE) + 1’

OPEN PO_EXPCUR FOR V_QUERY_SQL USING …

The SQL in the stored procedure, such as the above code, throws the exception that ora-01006: bound variable does not exist when calling. When viewing the SQL statement, make sure that all variables exist. But why is this exception thrown?

Finally, we find out the reason, because the SQL statement returns an integer value, but here we give this value to the cursor, so we throw this exception. Change the cursor related statements to the following SQL, and everything will be OK.

EXECUTE IMMEDIATE V_QUERY_SQL INTO PO_AMOUNT USING…

 

The server has rejected the client credentials

Our WinForm program is isomorphic to WCF and is connected to the server deployed on the server. Today, many WinForm users report that they have encountered problems when using WinForm and thrown an exception. The server has rejected the client credentials

Now let’s talk about the security authentication of WCF. Generally, our LAN applications do not have any security configuration, so what is the default security configuration of WCF?If no security configuration is made, WCF adopts windows security authentication. The default configuration is as follows:

<netTcpBinding>

  <binding name="netTcp">

    <security mode="Transport">

      <transport clientCredentialType="Windows" />

    </security>

  </binding>

</netTcpBinding>

After checking, it is found that all computers that throw exceptions have been disabled in the ad domain. WCF in the server because it is windows authentication, so found that the user has a problem, it threw this exception. When the users in the ad domain are restored, WCF will be normal.

 

It should be pointed out that there are other possible reasons for this exception. For example, when the WCF server needs to impersonate the client identity, it needs the client to provide the user name and password. If it does not, it will throw this exception.

 

In addition, if the security requirements are not so high, we can disable all security related settings. The configuration is as follows:

<bindings>

  <netTcpBinding>

    <binding name="customTcpBinding" maxReceivedMessageSize="20480000" transferMode="Streamed" >

      <security mode="None"></security>

    </binding>

  </netTcpBinding>

</bindings>

In this way, you will no longer carry out identity authentication, and you will never throw an exception similar to identity authentication. As long as the corresponding server IP and port can be accessed, you can call it normally.

 

https://stackoverflow.com/questions/53098405/wcf-throws-exception-that-the-server-has-rejected-the-client-credentials-what-i

https://stackoverflow.com/questions/8577612/the-server-has-rejected-the-client-credentials