Connection to the database from web app to retrieve and modify data - sql-server

I have created a web app and later created a SQL Server instance to which I added an already existing database from my local machin to Azure SQL Server. The database, tables and the data can be viewed in it.
However, my web app consists of web forms like
login page
signup page
change password
where it checks with the database if the data exists or not else modifies the data there.
I've changed the connection string that's provided by the database in the azure portal. Yet it doesn't work and it shows an error:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable
Now I have no idea how to resolve it.
And I was expecting some further process like
If I see for login creds' it checks within the database if the creds' exist and then show either an alert saying 'no such username or password' or 'redirects to another page'.

I created empty asp.net web page in visual studio and added new web form
Image for reference:
Right click on the webapp and select add option and click on new item.
Image for reference:
I added new webform to the webapp.
Image for reference:
I created login page in new web form
Login page:
I created database in azure sql and created table with user details.
Image for reference:
I connected azure sql database to the webapp.
Process for add Azure sql server to the web app:
open SQL Server object explorer in visual studio click on add sql server.
Image for reference:
Click on azure and selected my server and enter the password connected to azure sql db.
Image for reference:
My azure sql server is connected successfully to my webapp.
Image for reference:
In web.config file I add the connection string of my sql server
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=<serverName>;Initial Catalog=<dbName>;Integrated Security=True"/>
</connectionStrings>
I write the below code for login in error and redirect to the page of when login success in my login page:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace login_page
{
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection SQLConn = new SqlConnection("Data Source = C1ML63563-MS; Initial Catalog=db; Integrated Security = True");
protected void Button1_Click(object sender, EventArgs e)
{
String constr = WebConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection sqlConn = new SqlConnection(constr);
try
{
sqlConn.Open();
SqlCommand cmd = new SqlCommand("select count(*) from userdb where UserName ='" + txtusername.Text + "' and Password ='" + txtpassword.Text + "'", sqlConn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
adapter.Fill(DT);
cmd.ExecuteNonQuery();
if (DT.Rows[0][0].ToString() == "1")
{
Response.Write("<script>alert('Login successfully')</script");
Response.Redirect("~/web.aspx");
}
else
{
Response.Write("<script>alert('error in login')</script");
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
}
}
I run the web app It successfully run.
image for reference:
Login page:
If I enter wrong details I got error in login pop-up.
Image for reference:
If I enter Correct details which are already stored in database, it is redirecting to another page below code is used for redirect of another page:
Response.Redirect("~/web.aspx");
Image for reference:

Related

Connect to a Microsoft SQL Server database to which is normally connected to via GlobalProtect using .NET 6 application

I'm using .NET 6, Azure Function version 4 and SqlClient in my Azure Function application.
I have a connection string like this
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
Normally, I access this database using GlobalProtect by providing it portal, username and password.
Now, I'm developing an Azure Function app which will access this database, but I'm getting this error
System.Private.CoreLib: Exception while executing function:
MyAzurefunction. Core .Net SqlClient Data Provider: Cannot open
server 'serverName' requested by the login. Client with IP address
'MyIpAddress' is not allowed to access the server. To enable
access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range. It may take up to five minutes
for this change to take effect.
I know I'm getting this error because my IP Address doesn't have access to the server but how can I connect to it via my Connection String?
I create azure SQL database. connection string of database:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Image for reference:
I created function app with .net 6 in visual studio.
Image for reference:
I published it to Azure.
Image for reference:
Selected the ellipse(...) on the published page and selected Manage Azure App Service settings.
Image for reference:
Click on Add Setting in Application page and add the name of setting.
Image for reference:
In sql_connection enter the connection string of sql db in Local section for remote section click on Insert Value from Local.
Image for reference:
Install System.Data.SqlClient package in Manage Nuget packages of project. I added below code that connects to SQL Database :
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
Above function runs every 15 seconds to update the Status column based on the ship date.
I added my IP address in database firewall settings.
Image for reference:
At 15 seconds after startup, the function runs.
Output of number of rows updated in the SalesOrderHeader table:
In this way I connected to my SQL database to my function app.

Connection String generated by VS doesn't work, and any variation of it

I'm deploying a web application using IIS and ASP.NET CORE.
I setup a "appsetting.json" file that include a connection string to sql server.
So far, any variation I've tried didn't work.
The strange thing about it, is that it works perfectly on a my local machine, but when I deploy it and send an HTTPPost, log file says there's an error using connection to database on server.
Well, I tried all variations I could think of.
Current connection string generated by Visual Studio is :
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Swap;Integrated
Security=True;Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
I've tried changing the "Integrated Security" to False.
I've tried to replace it with User ID and password (of "sa" user).
I've tried adding a "Initial Catalog" property and set it to my database.
I'm preety sure the startup of the app is fine, because when I try to send a GET request to the main page, everything seems fine.
When I send a POST request and asks the DBcontext to Add and SaveChanges, it shows this error :
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'Swap' on server
'(localdb)\MSSQLLocalDB'.
This is the function that I tried to send a HTTPPost request to:
byte[] j = new byte[(int)Request.ContentLength];
Request.Body.Read(j, 0, (int)Request.ContentLength);
string str = Encoding.ASCII.GetString(j);
TokenSet tokenSet = new TokenSet {Token = str };
sqlTokensetData.Add<TokenSet>(tokenSet);
sqlTokensetData.SaveChanges();
HttpClient notificationSender = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://fcm.googleapis.com/fcm/send");
request.Headers.TryAddWithoutValidation("Authorization", "key="
<somekey>);
request.Headers.TryAddWithoutValidation("Sender", "id=<id>");
Message pushNotification = new Message(new string[] { str }, "Success!"
<somestring>);
request.Content = new
StringContent(JsonConvert.SerializeObject(pushNotification)
,Encoding.UTF8,"application/json");
HttpResponseMessage output = await notificationSender.SendAsync(request);
Log file error:
https://anotepad.com/notes/9a8jxa
I hope that the "str" string will be inserted to the database.
Thank you.
Well, Basicly, Thanks to the comments above I've managed to solve it.
What you need to do if you come by the same error:
1.Download SQL Server Express -
https://www.microsoft.com/en-us/sql-server/sql-server-editions-express as said above.
and configure the SQL Server however you see fit.
2.Configure sa user, set password and enable it.
3. If SQL Authentication doesn't work, then in Microsoft SQL Server Management Studio -> Right-click the server -> Properties -> Server Authentication -> Change to SQL Server and Windows Authentication
4. Change connection string to :
Data Source=;Initial Catalog=User ID=sa;
Password=;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
It worked for me.

SQL Server 2016 Always Encrypted Timeout at Published IIS

I Have strange problem when i tried to publish my asp.net mvc application to my local (pc) iis with "Always Encrypted" Enabled.
My application keep timeout when i tried to access database using EF6 at local IIS (not express) :
But if i tried to access & debug my asp.net mvc app using Visual Studio 2017, database with 'always encrypted enabled' can be accessed perfectly without timeout.
And also i can access it with SQL Management Studio without problem.
Both (SMSS & ASP.NET web config) using this configuration.
Column Encryption Setting=enabled;
Note : I'm using ASP.NET MVC 5 & EF 6, SQL Server 2016 Developer Edition.
Sorry for my bad english.
UPDATED :
I have tried using .NET Framework Data Provider to see if there's any clue that'll help me solving this issue, Using following code :
var context = new TestDevEntities();
StringBuilder sb = new StringBuilder();
string connectionString = context.Database.Connection.ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT [id],[name],[CCno] FROM [TestDev].[dbo].[testEncCol]", connection, null, SqlCommandColumnEncryptionSetting.ResultSetOnly))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
sb.Append(reader[2] + ";");
}
}
}
}
}
above code show me this error :
Now, with this kind of error i know i exactly i must do :)
Change the identity of application pool to the 'user' who previously generated the certificate.
Export currentuser cert (used by always encrypted) and import to the user that you want to use as application pool identity.
Now its worked!
EF should throw some kind of error as clear as .NET Data Providers do, instead of timeout failure that really confuse me #_#
UPDATED (1) :
Now the question is how to use it (Certificate) with default ApplicationPoolIdentity instead of custom account?
UPDATED (2) :
I have done what jakub suggest, but still no luck.
Thanks
One way (could be the only way) to use the DefaultAppPool identity instead of a custom (user) account is to store the certificate in the Local Machine certificate store (not Current User).
Once you create a certificate in the Local Machine certificate store, you need to grant DefaultAppPool access to the cert. You can do that using Microsoft Management Console (and the plugin for Local Computer certs):
Right click on the cert, select All Tasks > Manage Private Keys.
Click Add.
Set location to your computer (not your domain).
Enter IIS AppPool\DefaultAppPool as the object name.
Click OK twice.

window service and sqlserver connection

i have a project in window service, when i insert the following code in Onstart() event and debug it manually then database is inserted successfully, but when i create exe file of this project and started it in task manager then does nothing...i mean it didnt save any thing to database.
try
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=testing;Integrated Security=True");
SqlDataAdapter adp = new SqlDataAdapter();
cn.Open();
adp.InsertCommand = new SqlCommand("insert into testing1 values(1)", cn);
adp.InsertCommand.ExecuteNonQuery();
cn.Close();
}
catch { }
As the title of your post states "Windows service", I assume your program is running as a service. You are using integrated security, according to your connection string. Check if the account under which this runs has the rights to login to database server, and has the right to execute the insert.
You could of course also change to a fix database user account if your database is configured to allow that and there is one configured.
Edit
I also would suggest instead of an empty catch() clause, you print out/save to a log file the error message and stack trace to help diagnose the issue.

how to configure connection to the database in clouds services

I have surfed the web for two days looking for a better way to configure my application that I am uploading to AppFog so that it successfully connects to the mysql database in the cloud.
I have created the mysql service and I did bind it to the application. I also created tables and put some data on them using the local console ( using af tunnel mydatabase) in linux
but my apps does not seem to find the database. My application uses JDBC ... I used the database username and password and databasename given to me from the console (those funny chars in the screen) and it did not work. so I put my own credentials, still, no success...
I tried using the url that points to my application at the port given to the on the console, but still... actually, I put in the details the showed on the console to connect to the database in the cloud after deploying ... but my app seems not to find my database and its tables....
I do not know what is wrong...
please help..
MORE:
This is the code I used to try this connection:
try {
String connectionURL = "jdbc:mysql://http://someapp.aws.af.cm:10000 /OnlinePassword";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectionURL, USER, PASS);
statement = conn.createStatement();
}
Use appfog environment variable called VCAP_SERVICES to automatically detect your MySQL database credentials and connection info. You can take advantage of this to display all the info which will be in JSON format and use it to connect your app to MySQL database. You may try this.
First create a servlet and retrieve your database connection using a context attribute as follows:
public class DbInfoServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
request.setAttribute("jsonContent", java.lang.System.getenv("VCAP_SERVICES"));
request.getRequestDispatcher("/index.jsp").view.forward(request, response);
}
}
Then create a index.jsp file to display you DB connection info as follows:
<body>
<p>
<!-- Click here to display DB info -->
<!-- Display of your DB connection and credentials info is here. This will show in JSON document format
-->
<c:out value="${jsonContent}" />
</p>
</body>
Use hostname(i.e. IP), port, name(i.e. database name), username, password parameters from JSON document content to modify your JDBC connection code as follows:
try {
String connectionURL = "jdbc:mysql://hostname:3306/name";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectionURL, username, password);
statement = conn.createStatement();
}
If the above doesn't work, simply ensure that you are using the latest version of MySQL-connector-java jar file.
Have fun!

Resources