Blazor Webassembly, DatabaseCRUD: Internal Server Error 500 with published version - c#

Problem Details
I have a Blazor project with a simple Database-CRUD (create, read, update, delete) example. It works properly when I run it within Visual Studio but if I publish it the program runs into an error.
Project Details
IDE is Visual Studio 2019. Project is Blazor Webassembly. I tried .NET CORE 3.1 and .NET 5.0. Database is SQL Server 2019. IIS for publishing.
Code Details
Database access is working with mapping (Scaffold-DbContext). I use the nuggets “Microsoft.EntityFrameworkCore.Tools” and “Microsoft.EntityFrameworkCore.SqlServer”.
This is the read command:
using var httpResponse = await Http.GetAsync("/api/DataLrs/Index");
This is the read command-snippet I use for more error details:
using var httpResponse = await Http.GetAsync("/api/DataLrs/Index");
if (!httpResponse.IsSuccessStatusCode)
{
// set error message for display, log to console and return
errorMessage = httpResponse.ReasonPhrase;
Console.WriteLine($"There was an error! {errorMessage}");
return;
}
// convert http response data to UsersResponse object
dataLrsList = await httpResponse.Content.ReadFromJsonAsync<DataLrs[]>();
Error Details
When I publish the project with IIS and try to execute the same commands I get the following error in the browser:
Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500
Solution Attempts Details
As already mentioned, when I run it in Visual Studio it works without any problems. I already googled and tried several stuff but nothing really works.
How can I get a better error description?
Is anybody familiar with this problem?
I realized many people have the same/similar problem, but I couldn’t find a clear solution
Thanks!

Yes, you are right, I am using EF Core. Sorry! Forgot to mention that important detail.
Database Details
To make it not too complicated I am using a database on my pc and I am also publishing (IIS) on my pc. If all works, I would proceed with a server.
I retrieved my connection string via Visual Studio’s SQLServerObjectExplorer. I use for both modes (debug, publish) the same connection string which is stored in appsettings.json.
This is the connection string:
Data Source=CND823509T\SQLEXPRESS;Initial Catalog=DataComposerWebDBTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
Method Details
Here are some of my method details, I will just copy the important lines (hope that is enough). I got the structure from a general example I googled. As already mentioned, locally it works.
RazorePage.razor
dataLrsList = await Http.GetFromJsonAsync<DataLrs[]>("/api/DataLrs/Index")
DataLrsAccessLayer.cs
public IEnumerable<DataLrs> GetData()
{
try
{
return _context.DataLrs.ToList();
}
catch (Exception ex)
{
throw;
}
}
DataLrsController.cs
[HttpGet]
[Route("api/DataLrs/Index")]
public IEnumerable<DataLrs> Index()
{
return _dataLrs.GetData();
}
Questions Details
Do you need more details?
What do you mean with localDB stuff?
Thanks!

Related

gRPC client having lots of issues and not working

I started using gRPC with Visual Studio 2022 and never saw so many issues as now.
When I wanted to create an additional Proto file I got the error saying that I need to specify the language. That's weird, because I selected the proper option which is designed for C#. So it never worked and I simply had to copy default greeter file.
I created the console app which uses this default greeter service and it even worked. But I added the additional proto and created another fairy simple service and it did not want to compile it referring to some missing types of something. I can't remember the exact error message but I resolved it only by reducing the grpc.* package version to 2.27.I found this answer by googling and I find it weird that Microsoft releases something what does not work in the most simple case scenario.
I decided to test my new test grpc service and created the client:
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.MySimpleMethodAsync(new MyRequest { Id = 123 });
Console.WriteLine(reply.Message);
Console.ReadKey();
The MySimpleMethodAsync method is very simple, it just reads the record from the DB using Dapper, nothing special.
Surprisingly there was no compilation error, but when I tried to run it (along with the server app) I got the exception on the line var reply = await client.MySimpleMethodAsync, saying Grpc.Core.RpcException: 'Status(StatusCode=Unimplemented, Detail="Service is unimplemented.")'
I don't understand why it says so. The service is implemented, it's compilable! Googling did not help but I found that other people are having the same issue too.
Eventually I found that if I modify the grpc service and for some reason it does not like it and then I rollback the changes, it's not compilable anymore! I clearn solution, rebuild it - nothing helps! The only thing which helps is addting the brand new project and copy pasting the previous "stable" code.
I've never seen such the ...technology that never works!
Anyway, now the most important issue for me is #3 , why it says the service is not implemented?

Sudden - 'The certificate chain was issued by an authority that is not trusted in Microsoft.Data.SqlClient' in working project

I have an ASP.Net Webforms website running in IIS on a Windows Server.
Also on this server is the SQL server.
Everything has been working fine with the site but now I am seeing issues with using a DataAdapter to fill a table.
So here is some code, please note it's just basic outline of code as actual code contains confidential information.
public List<Summary> Fetch(string Connection, int parameter1, int parameter2, bool parameter3)
{
List<Summary> collection = new List<Summary>();
using (SqlConnection dbConnection = new SqlConnection(Connection))
{
using (SqlCommand dbCommand = dbConnection.CreateCommand()) // Result is complex
{
dbCommand.CommandType = CommandType.StoredProcedure;
//
// Code to add parameters and set commandText goes here
//
using (SqlDataAdapter da = new SqlDataAdapter(dbCommand))
{
DataTable table = new DataTable();
DataRow row;
try
{
da.Fill(table);
}
catch(Exception ex)
{
// Log error
}
for (int i = 0; i < table.Rows.Count; i++)
{
row = table.Rows[i];
Summary data = Populate(row);
collection.Add(data);
}
}
}
}
return collection;
}
The above is in a library and is called like this in the Web Forms site.
var Summaries = MyLibrary.Fetch(ConnectionString, 1, 111, false);
So as I say, everything was working fine. Now, all of a sudden the above has stopped working and Summaries is always empty.
To investigate I tried the following.
Created a test using xUnit with the same parameters used by the website. These were captured during debugging to ensure they matched.
The result returned 1 item.
I then ran the stored procedure in SQL management Studio and it matched the xUnit test with 1 item returned.
I then checked SQL Profiler and this is where things seemed a little odd. Nothing was being recorded in the trace when the web-forms was calling the library.
So both the web-site and xUnit test were using the same library, passing the same parameters and yet one worked and the other didn't... very odd.
As a last resort, I added the library project to the Web Forms project and proceeded to debug through that... then I found the error.
da.Fill(table);
The above line generated the following exception.
Exception thrown: 'Microsoft.Data.SqlClient.SqlException' in Microsoft.Data.SqlClient.dll
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
Having a look around here on stack, I saw many responses with I need to install a certificate.
My question is, if this is the case then why and why now?
Nothing has changed in the code from when it was working till now. The web-site and SQL server are on the same windows server. Also, why does the xunit test work without it and the website does not when I am debugging on the same machine!
The only items that I now has changed is install of .Net 6 and patch Tuesday resulted in some updates and a restart of the server.
Microsoft.Data.SqlClient 4.0 is using ENCRYPT=True by default. Either you put a certificate on the server (not a self signed one) or you put
TrustServerCertificate=Yes;
on the connection string.
I hit this issue as well. Net 6.0
It suddenly started occurring when I upgraded Microsoft.EntityFrameworkCore.SqlServer
FROM Version="6.0.0" to Version="6.0.1"
I added Encrypt and TrustServerCertificate to connection string.
data source=(local);Initial Catalog=XXXXXXX;Trusted_Connection=True;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=True
I have added TrustServerCertificate=True in my ConnectionStrings to solve this issue. This is how it looks like
"ConnectionStrings": {
"DefaultConnection": "Server=localhost; Database=GreenProducts;Trusted_Connection=True; TrustServerCertificate=True"
}
Hope this helps.
I suddenly got the same problem when first upgrading Microsoft.Data.SqlClient to 4.x.x. I reverted back to 2.0.1 and the same problem was present.
I then removed all "bin" and "obj" folders for each project. And then executed a "dotnet restore". After that it worked as before.
Similar to others, we got this error after upgrading Microsoft.EntityFrameworkCore.SqlServer from 2.2.6 to 6.0.5 and Microsoft.Data.SqlClient from 3.0.0 to 4.1.0.
However, in our case removing Microsoft.Data.SqlClient fixed the issue.
I noticed that Microsoft.EntityFrameworkCore.SqlServer listed a dependency of Microsoft.Data.SqlClient 2.1.4 in the solution explorer, maybe that is why removing the other one worked.

Can not connect to Sql database in C# asp mvc application with Entity Framework BUT the same code works with Winform application

First of all, please excuse me if it sounds too rooky. I consider myself novice in MVC applications.
I have ran into a strange problem and there does not seem to be any way out of this, at least so far..I have looked everywhere and left no stone unturned to get it worked. Finally I turned to this forum.
This is my first post, so any mistakes please overlook and guide me.
The problem is multifaceted...
The High Level Details...
I have created a C# ASP MVC Web Application waiting to be uploaded on a Remote Server (Client Machine)
The application uses Entity Framework - Code First approach
Connects to the database with Windows Authentication system
Scene1: Where the application worked
I have tested the application on my machine and it worked flawlessly.
I have Express edition of Sql Server Management Studio installed on my system.
Scene2: Where the application failed. The Problem - Big Picture
It works great on my system but while testing it on the Remote Server it crashes
The application fails to connect to the Remote Server Sql Database. As soon as it tries to connect to the database, it crashes with an error message "Login failed for user '<UserName>."
I have checked everything in the connection string - like -
Data source name is correct
Initial Catlog also points at the correct database name
Integrated Security = true
There is no UserID or password mentioned
Connection string worked great on my system. But it does work on the Client Machine and shows the error above.
Connection string is:
connectionString="Data Source=RemoteComputerName;Initial Catalog=DatabaseName;Integrated Security=True; MultipleActiveResultSets=true"
I am not able to figure out exactly what is causing the error - Is it my code or Is it the Sql Server database settings - permissions.
Since the connection worked on my local machine, which means the code is correct
In order to check whether sql server permissions are working..I have created partial 'test connection application' in WINFORM and uploaded on the Server, this time the code works and read all the table data.
but when I try to connect in MVC project it shows the error..."Login failed for user...".
I'm totally confused what works in WINFORM fails in MVC.
Database permissions must be right because when tried to access it using WINFORM it worked.
please let me know if I have missed to provide any details in this post.
Any help is highly appreciated!!!
Thank You.
Please show your connection string. (you can block out any real passwords, actual server names, actual db names).
Since you mention "Integrated Security = true"..........then you have to be aware of which Identity is running the process (the website or the winforms.exe)
When running as winforms app, you are running as "you" (most likely). As in, the logged in user to the windows o/s.
When running under IIS, you are running under the Identity associated with the App Pool you are using..which most likely is NOT you, but rather a service account.
Your service-account does not have access to the sql-server.
You can read in depth here: https://support.microsoft.com/en-us/help/4466942/understanding-identities-in-iis#:~:text=ApplicationPoolIdentity%3A%20When%20a%20new%20application,also%20a%20least%2Dprivileged%20account.
You can show this......by catching an exception, and then something like this:
You can replace ArithmeticException with whatever, I'm just showing "adding info" to a caught exception and rethrowing.
try
{
// some sql server access code
}
catch(Exception ex)
{
throw new ArithmeticException("What is the real IIdentity: " + this.FindIIdentity(), ex);
}
private string FindIIdentity()
{
try
{
//'Dim user As WindowsPrincipal = CType(System.Threading.Thread.CurrentPrincipal, WindowsPrincipal)
//'Dim ident As IIdentity = user.Identity
string returnValue = string.Empty;
WindowsIdentity ident = WindowsIdentity.GetCurrent();
returnValue = ident.Name;
try
{
returnValue += " on " + System.Environment.MachineName;
} catch (Exception ex)
{}
return returnValue;
} catch (Exception ex)
{
return "Error Finding Identity";
}
}
IIS screenshots

Azure database randomly stopped working after publishing UWP app

Ive made an app that uses Azure easy tables and connects using the following:
try
{
await ctv.combatDrillsTable.Initialization;
await ctv.combatDrillsTable.InitLocalStoreAsync();
await AddItemsAsync();
}
catch
{
var addError = new MessageDialog("Connection to your drills could not be established at this time, returning to " +
"main menu");
await addError.ShowAsync();
if (MainPage.MyFrame.CanGoBack)
{
MainPage.MyFrame.GoBack();
}
}
This was doing a GET request fine the last few weeks but now the connection error throws, I checked my Azure portal and the drills are there, the server overview shows the following:
HTTP Error stats
Im not really sure whats wrong and why Azure has just decided to stop working. I get the same results on bith my local machince is Visual Studio 2017 and the app installed on windows from the store.
Im not really sure whats wrong and why Azure has just decided to stop working.
Firstly, you need to enable logs in Azure, in that case you could access the information logged by Azure and check the logs to find the detail reason. Details for how to do please reference this article.
Since you're using easy table, the azure backend should be node.js. After enabled logs, you could access logs by address like: https://{your app name}.scm.azurewebsites.net/api/vfs/LogFiles/Application/index.html.
If you still cannot resolve your issues by checking the log details, you could upload the log for further looking.

Unable to Access Embedded Firebird Database Server with .Net Client

Unable to Access Embedded Firebird Database Server with .Net Client
I aim to develop a program which uses the Embedded Firebird Server but face errors when trying to make a connection using the .Net client. I have followed the advice from multiple threads on making it work, but I can’t figure it out. I’ve tried changing the connection string and files but keep getting the same errors.
Here is a detailed explanation of my research and everything I have tried so far:
How to connect and use Firebird db embedded server with Visual C# 2010
I download the files specified in the links, followed the steps and ran the code and got the same error message as did the original poster:
FirebirdSql.Data.FirebirdClient.FbException
Message=Unable to complete network request to host "127.0.0.1".
Using "localhost" in place of the IP generates the same error.
The accepted answer is to make sure all the .dll and config files are copied to my project files (directory with the code ) and the output directory (bin/debug), which I have done. I copied over every file in the zip folder. Additionally #Robin Van Persi states to not use the “compact .Net data provider”, how do I know if I am using this? I downloaded the file from the link in the question.
Another answer contributed by #PlageMan is to add ServerType=1; to the connection string and remove the DataSource and Port attributes which produces these errors:
FbConnection con = new FbConnection("User=SYSDBA;Password=masterkey;Database=TEST.FDB;Dialect=3;Charset=UTF8;ServerType=1;");
System.NotSupportedException Message=Specified server type is not correct.
FbConnection con = new FbConnection("User=SYSDBA;Password=masterkey;Database=TEST.FDB;Dialect=3;Charset=UTF8;");
System.ArgumentException
Message=An invalid connection string argument has been supplied or a required connection string argument has not been supplied.
The last answer by #Toastgeraet adds to rename the fbembed.dll to either fbclient.dll or gds32.dll. I’ve tried it all three ways, no change. In fact http://www.firebirdsql.org/en/firebird-net-provider-faq/ says fbembded.dll but that didn’t work either.
How to solve connection error in c# while using firebird embeded database?
Has the same advice on renaming the fbembed.dll to fbclient.dll which didn’t work for the original poster either.
The accepted answer ServerType=1 in the connection string, but a comment under #cincura.net answer gave me a new possibility to investigate; processor architecture. Unfortunately, switching between 64bt and 32bit versions didn’t make any difference.
I thought switching to the 32bit version might have been the answer since I'm using Visual Studios Express.
Error in using Embeded Firebird
The last comment in this thread is another person saying that changing to 32bit didn’t solve the problem either.
Trying to use the firebird embedded server - Specified server type is not correct
I went back to looking up information on the ServerType because I have seen it as 1 and 0 and found this post. #Nigel answer is to update to the latest version of the .Net provider. Unfortunately, I can’t figure out how to use the newest version on the Firebird website (4.5.1.0) because it lacks FirebirdSql namespace from the examples. Additionally, Visual Studios gives me some warning about the wrong version of .Net being targeted when I import it.
What am I doing wrong? Do I need to use a different connection string or new version of Firebird/ .Net provider? Am I missing something else?
I realize that this question may be considered a duplicate, but none of the answers I have found so far have solved my issue. Additionally, the previous StackOverflow Q/A’s which I have cited above are all years old so I’m hoping someone may have new information to share.
I just created a very basic program to test Firebird embedded from C#. You need to add the latest FirebirdSql.Data.FirebirdClient nuget package (4.5.1.0), and drop the entire contents of a Firebird embedded zip kit into the same folder as the .exe.
Note that you need to match the bitness of the application:
x86 (32 bit): Firebird-2.5.3.26778-0_Win32_embed.zip
x64 (64 bit): Firebird-2.5.3.26778-0_x64_embed.zip
AnyCPU seems to be rather tricky. When I compiled the executable as AnyCPU and ran it on a 64 bit machine, it gave a BadImageFormatException when combined with Firebird Embedded 64 bit, but worked with Firebird Embedded 32 bit; which is the opposite of what I expected.
class Program
{
private const string DefaultDatabase = #"D:\data\db\employee.fdb";
static void Main(string[] args)
{
string database = args.Length > 0 ? args[0] : DefaultDatabase;
var test = new TestEmbedded(database);
test.RunTestQuery();
Console.ReadLine();
}
}
class TestEmbedded
{
private readonly string connectionString;
public TestEmbedded(string database)
{
var connectionStringBuilder = new FbConnectionStringBuilder();
connectionStringBuilder.Database = database;
connectionStringBuilder.ServerType = FbServerType.Embedded;
connectionStringBuilder.UserID = "sysdba";
connectionString = connectionStringBuilder.ToString();
Console.WriteLine(connectionString);
}
internal void RunTestQuery()
{
using (var connection = new FbConnection(connectionString))
using (var command = new FbCommand("select 'success' from RDB$DATABASE", connection))
{
Console.WriteLine("Connecting...");
if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
Console.WriteLine("Executing query");
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
}
}
The connection string generated by this program is:
initial catalog=D:\data\db\employee.fdb;server type=Embedded;user id=sysdba
This seems to be the minimum required to connect. Note that although Firebird embedded on windows doesn't perform any authentication, providing user id is required, otherwise the trusted authentication is triggered which doesn't work with Firebird embedded.
The only way that works for me: setting the client path in the connection string.
<add name="MyEmbeddedDb" connectionString="user=SYSDBA;Password=masterkey;Database=|DataDirectory|MyDb.fdb;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;ServerType=1;client library=C:\firebird\fbembed.dll" providerName="FirebirdSql.Data.FirebirdClient" />
C:\Firebird is a folder I've extracted the entire downloaded zip file (Firebird-2.5.4.26856-0_Win32_embed.zip)

Categories