Tag Archives: c#

C#: How to Get details of the directory where the currently running program is located

1.asp.net webform

  1.1 Use “Request.PhysicalApplicationPath to get the physical path of the virtual directory where the site is located, and finally include “\”;

2. In c# winform
  2.1 “Application.StartupPath”: Get the path of the directory where the current application is located, excluding “\” at the end;
  2.2 “Application.ExecutablePath”: Get the path of the current application file, including the name of the file;
  2.3 “AppDomain.CurrentDomain.BaseDirectory”: Get the path of the directory where the current application is located, including “\” at the end;
  2.4 “System.Threading.Thread.GetDomain().BaseDirectory”: Get the path of the directory where the current application is located, including “\” at the end;
  2.5 “Environment.CurrentDirectory”: Get the path of the current application, without “\” at the end;
  2.6 “System.IO.Directory.GetCurrentDirectory”: Get the path of the current application, excluding “\” at the end;
3. c# windows service service
  3.1 “AppDomain.CurrentDomain.BaseDirectory” or “System.Threading.Thread.GetDomain().BaseDirectory”;
  3.2 “Environment.CurrentDirectory” and “System.IO.Directory.GetCurrentDirectory” will get the path to the “system32” directory;
       Note : If you want to use “Application.StartupPath” or “Application.ExecutablePath”
       You need to manually add a reference to “System.Windows.Forms.dll” and declare the reference with “using System.Windows.Forms” at the beginning of the program;
4. Obtain the system installation directory in the uninstaller:
  4.1System.Reflection.Assembly curPath = System.Reflection.Assembly.GetExecutingAssembly();
              string path=curPath.Location;//Get the path of the installer class SetupLibrary file, get the directory where the file path is located to get the directory of the installer;
 4.2System.Diagnostics.StackFrame f = new System.Diagnostics.StackFrame(1);
              MethodBase mb = f.GetMethod();
              System.Web.HttpContext.Current.Response.Write(mb.DeclaringType.ToString()); Get the information of the calling class, you can know the situation of the subclass from the parent class

How to Solve Win10 0x8007007E Error (OPC Component)

During the development of OPC client in Win10, the following missing component exception occurs when reading the device.
Message=Fail to retrieve the component with CLSID {28E68F9A-8D75-11D1-8DC3-3C302A000000} in COM class factory because of the following error: 8007007e The specified module could not be found. (Exception from HRESULT:0x8007007E).

Solution:

1. Copy the OPCDAAuto.dll file to the C:\Windows\SysWOW64 directory.
2. Press ” WIN + R ” to enter the CMD command line.
3, type: regsvr32 C:\Windows\SysWOW64\OPCDAAuto.dll, enter.
4, after successful registration, set in the configuration manager for the X86 platform (can not run under 64-bit)
5, regenerate the project solution, it can run normally.

SqlSugar Connect MySql 8.0.29 Error [How to Solve]

1. Background

I exported the database table structure and data from the company server Mysql (version: 8.0.16) and restored it to my local computer Mysql (version: 8.0.29). Just after starting the project, I was prompted with a SqlSugar database connection error. The prompt error is as follows:

Execute Db.Ado.CheckConnection() reports an error
Connection open error . The given key ‘0’ was not present in the dictionary.

note: the connection string: database=stocks;server=127.0.0.1;port=3306;uid=root;pwd=123;

The following is the error report problem of individual table query.

DB.Queryable().Where(p=>true).ToList() error. ToList() error, after analysis, the main problem is the current table field character set and sorting rules are not uniform. The error is reported as follows.
MySqlException: “Fatal error encountered attempting to read the resultset.”
Internal exception MySqlException: Expected end of data packet

2. Solution

1. Solution to connection error

Add charset=utf8mb4, and the connection will no longer report errors note: if you want utf8mb4, I use utf8 locally and still report an error

database=stocks;server=127.0.0.1;port=3306;uid=root;pwd=123;charset=utf8mb4;

2. Modify the inconsistency of database character set

Execute the following SQL script as required.

(1) Change the encoding (character set) of a table and the encoding (character set) of all fields in the table:

ALTER TABLE TABLE_NAME CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
·TABLE_NAME replace to your table name.

(2) Change the encoding (character set) of all tables and the encoding (character set) of all fields in the table:

SELECT
	CONCAT(
		'ALTER TABLE ',
		TABLE_NAME,
		' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;'
	)
FROM
	information_schema.`TABLES`
WHERE
	TABLE_SCHEMA = 'DATABASE_NAME';
·DATABASE_NAME replace to your databese name.

3. Other contents

Query all table names of a database:

SHOW FULL COLUMNS FROM TABLE_NAME;
·TABLE_NAME replace to your table name.

[Solved] Halcon & C# Error: HalconDotNet.HOperatorException:“HALCON error #5190: Invalid window parameter in op

Error occurred when calling HSmartWindowControlWPF control in C# WPF

HalconDotNet.HOperatorException:“HALCON error #5190: Invalid window parameter in operator set_window_param”

 


The main reason is that the required dynamic library files are missing.

Solution:
From the installation directory
C:\Program Files\MVTec\HALCON-xxxx-Progress\bin\x64-win64
Find the hcanvas.dll file and put it in your own runtime directory.

Database App.config configurate file Error & Solution

Error message 1

Object reference is not set to an instance of the object.

Error Message:

[Problem Analysis]: Open the App.config file, check the string in the name node and the current brackets is the same, the comparison found, not the same, more than one S. Remember, C# reads the name in brackets used in the node, and the configuration file node configuration name must be consistent!

Solution

[problem-solving] remove “s” and run it.

[other Error] 1: some friends don’t pay attention to this situation that you add spaces in the string will also lead to this problem, such as the following:

Spaces must be removed. You cannot add any spaces in the configuration file.

[other Error] 2: if the node position is written incorrectly, the above error will also occur. For example, in the screenshot below, the node should be written to the arrow position.

[other Error] 3: If the App.config configuration file is not added, or the App.config file is not placed in the project launchable project directory, the above error will also occur. For example, the following is wrong:

The following green part is the project’s startable items, App.config file must be put here to work.

[Other Error] 4: modified the name of the configuration file, the configuration file requirements must be the default App.config to work, if you modify the file name, there will also be errors, such as the following is not allowed: the case of.

 

Error message 2

The type initial value setting item of “ThreeLayer.DAL.SQLHelper” raises an exception.

Error Message:

The problem is that as long as the prompt “SQLHelper’s type initial setting item raises an exception”. Generally, it is a configuration file problem, because we use App.config configuration file to save the data connection string. For beginners, because they can’t understand this error, so they don’t know where to start, here please remember the following troubleshooting methods.

Solution
[Solution 1] The configuration file node is written wrong

Originally this place node name is also the above is less than an s, change to the following can be: [Solution 2] configuration file App.config file if you change the name, not placed in the “startable project” root directory.

[Solution 2] configuration file App.config file if the name is modified, not put into the “startable project” root directory, some VS versions will also appear the above error. (This is the same as the solution to error 1)

Summary
According to the above method, you can perfectly solve the common problem of getting the connection string through App.config. I hope today’s content can help you.

[Solved] C# Access Mongodb Database Error: command find failed: Command find requires authentication

The error reports are as follows:

error reason analysis:
literally means that the user name and password authentication are missing, so the database cannot be accessed
solution steps:
1 Add the user name and password to the configuration file connecting to mogondb

run the program again

over

IIS Web Deploy Website Error: HTTP error 500.19 – Internal Server Error

HTTP error 500.19-Internal Server Error
The requested page cannot be accessed because the relevant configuration data for the page is invalid.

Detailed error information:

Module: IIS Web Core
Notice: BeginRequest
error code: 0x800700b7
Configuration error: When the unique key attribute “name” is set to “ScriptHandlerFactory”, duplicate collection items of type “add” cannot be added
Because the child site inherits the web.config of the parent site

Because the child site inherits the web.config of the parent site

  <location path="." allowOverride="true" inheritInChildApplications="false">
  /* Wrap <system.web> with location in the web.config file
    </system.web>
*/
// If it doesn't work, wrap all configurations with the <add> attribute in location
 
  </location>

For example: system.web, system.webServer, ApplicationConfiguration and other configuration
locations with add attributes only need to be written once

Make the subsite not inherit the web.config of the parent site

Error: Unable to build IHost No DbContext named ‘PersistedGrantDbContext‘ was found.

IdentityServer4 data migration error: surprisingly Apollo appsettings.json configuration problem!

PM> dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb –project MicroService.IdentityServer
Build started…
Build succeeded.
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Unable to build IHost
No DbContext named ‘PersistedGrantDbContext’ was found.
PM> dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb –project MicroService.IdentityServer


[Solved] RSA decrypt error: the data to be decrypted exceeds the maximum 128 bytes of this module

RSA decryption error: the data to be decrypted exceeds the maximum 128 bytes of this module

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Encoding.UTF8.GetBytes(content), false);
            var Text=Encoding.UTF8.GetString(cipherbytes);

cipherbytes = rsa.Decrypt(Encoding.UTF8.GetBytes(content), false);
Modify to:
cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);