Angular 11 HTTP POST to SQL Server Database - sql-server

I am trying to post my inputs to my SQL Server database. I can in fact POST to the database, but I get back a blank response. I know it's because I am returning "Success" instead of my variables but how to I correctly format that for the return statement?
POST method:
[HttpPost]
public JsonResult Post(Weather Wea)
{
string query = #"INSERT INTO dbo.Information (Date, TemperatureC, TemperatureF, Summary) VALUES ('" + Wea.Date + #"'
,'" + Wea.TemperatureC + #"'
,'" + Wea.TemperatureF + #"'
,'" + Wea.Summary + #"'
)";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("WeatherAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand(query, myCon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Success");
}
Front-end POST
export class PostDataComponent {
baseUrl: string;
date: number;
temperatureC: number;
summary: string;
weatherForm: FormGroup;
constructor(public http: HttpClient, #Inject('BASE_URL') baseUrl: string, private formBuilder: FormBuilder) {
this.baseUrl = "https://localhost:44347/WeatherForecast";
this.weatherForm = formBuilder.group({
Date: new FormControl(),
TemperatureC: new FormControl(),
Summary: new FormControl()
});
}
CreateData() {
const params = new HttpParams({
fromObject: {
'date': this.weatherForm.value.Date.toString(),
'temperatureC': this.weatherForm.value.TemperatureC.toString(),
'summary': this.weatherForm.value.Summary.toString()
}
});
console.log(params);
this.http.post(this.baseUrl, {},{ params: params }).subscribe(data => {
console.log(data);
});
}
}

Couple things here.
As marc_s commented, you should be using parameterization instead of concatenating to avoid any potential SQL injection:
string query = #"INSERT INTO dbo.Information (Date, TemperatureC, TemperatureF, Summary) VALUES (#Date, #TemperatureC, #TemperatureF, #Summary)";
...
using (System.Data.SqlClient.SqlCommand myCommand = new SqlCommand(query, myCon))
{
myCommand.Parameters.AddWithValue("#Date", Wea.Date);
myCommand.Parameters.AddWithValue("#TemperatureC", Wea.TemperatureC);
myCommand.Parameters.AddWithValue("#TemperatureF", Wea.TemperatureF);
myCommand.Parameters.AddWithValue("#Summary", Wea.Summary);
...
Unless you have a trigger on your target table with an output, your query isn't returning any data (just the number of rows inserted) and your SqlDataReader is empty. You could get rid of the reader/DataTable and use myCommand.ExecuteScalar() instead in this case. If you do have a trigger outputting the inserted data, disregard this.
If you don't have an output trigger but do still need to return the inserted values for whatever reason, you could keep your SqlDataReader and update your query to the following
string query = #"INSERT INTO dbo.Information (Date, TemperatureC, TemperatureF, Summary)
OUTPUT inserted.Date,inserted.TemperatureC,inserted.TemperatureF,inserted.Summary
VALUES (#Date, #TemperatureC, #TempreatureF, #Summary)";
Without knowing the response format you're looking for, it's hard to give an answer on how to generate it. If you need to return the inserted values, you could use the OUTPUT keyword as in the previous bullet and serialize your DataTable.

Related

.NET Core 6 SQL Server connection without Entity Framework

I am new to .NET Core. I have defined the connection string in appsettings.json like this:
"ConnectionStrings": {
"TestBD": "Server=localhost;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
I am not using Entity Framework. I need to connect to the database using this connection string from the Program.cs file.
Any help is really appreciated. Thanks
You refer the following sample code to use ADO.NET in Asp.net 6 program.cs:
//required using Microsoft.Data.SqlClient;
app.MapGet("/movies", () =>
{
var movies = new List<Movie>();
//to get the connection string
var _config = app.Services.GetRequiredService<IConfiguration>();
var connectionstring = _config.GetConnectionString("DefaultConnection");
//build the sqlconnection and execute the sql command
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
string commandtext = "select MovieId, Title, Genre from Movie";
SqlCommand cmd = new SqlCommand(commandtext, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var movie = new Movie()
{
MovieId = Convert.ToInt32(reader["MovieId"]),
Title = reader["Title"].ToString(),
Genre = reader["Genre"].ToString()
};
movies.Add(movie);
}
}
return movies;
});
The result like this:

How to get names of all sheets in excel

I want to create a method to get names of all sheets in a workbook. My workbook has 7 sheets. If I want to read and save names of sheets to the variable excelSheets, I receive 9 names, where two names response to non-exists sheets ("lists$" and "TYPAB").
I don't understand where is the problem? How can I get names only the existing sheets?
public List<string> NamesOfSheets(string filename)
{
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
List<string> excelSheets;
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
Oscar, thanks for your help, but office interlop doesn't solve my problem.
I found that "lists$" is hidden sheet, so only name TYPAB doesn't respond to any existing sheet.
So I added clause where and problem is solved. :)
public List<string> NamesOfSheets(string filename)
{
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 12.0;HDR=Yes;'";
List<string> excelSheets;
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
try
{
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheets = dt.Rows.Cast<DataRow>()
.Where(i => i["TABLE_NAME"].ToString().EndsWith("$") || i["TABLE_NAME"].ToString().EndsWith("$'"))
.Select(i => i["TABLE_NAME"].ToString()).ToList();
return excelSheets;
}
catch (Exception)
{
throw new Exception("Failed to get SheetName");
}
}
}
Why not use Office Interop for this?
foreach (Excel.Worksheet displayWorksheet in Globals.ThisWorkbook.Worksheets)
{
Debug.WriteLine(displayWorksheet.Name);
}
https://msdn.microsoft.com/en-us/library/59dhz064.aspx

NodeJS OracleDB bind parameters returning parameter name

I am very new to NodeJS, but I have been working to use it to serve my Angular project. I need to access an Oracle DB and return some information using a select statement. I have one statement that works correctly using a bind parameter that is set up like this:
var resultSet;
connection.execute("SELECT column_name, decode(data_type, 'TIMESTAMP(3)','NUMBER'"
+ ",'VARCHAR2','STRING','CHAR', 'STRING','NUMBER') as \"DATA_TYPE\""
+ "FROM someTable where table_name = :tableName",
[table], //defined above
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
// console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns exactly what I want it to, with the bound variable being what I wanted it to be. Below is the code that doesn't work:
var resultSet;
connection.execute(
"SELECT DISTINCT :columnName from someTable",
['someColumn'],
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns {":COLUMNNAME": "someColumn"}. I do not understand why it won't display the results correctly. The two snippets of code are exactly the same, save the SQL query part. I know this a long question, but I really need help. Thank you!
You can bind data values, not the text of the statement itself.

Facing trouble while inserting bulk data into sql

In MVC4 , i have following code in my view :
<script>
var things = [];
function fun () {
var Quran = {
"surah": things[1].surah,
"ayah": things[1].ayah,
"verse": things[1].verse
};
things.push(Quran);
for (var n = 0; n < length; n++) {
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'GET',
url: "Gateway/DB_Rola?action=1",
data: things[n],
success: function (Data) {
var mera_obj = Data.key;
document.getElementById("Param2").value = '(' + mera_obj.Response_Code + ' , ' + mera_obj.Response_Description + ')';
},
error: function () {
alert("ERROR: can't connect to Server this time");
return false; }
});
alert("done for "+(n+1));
} // loop ends
return false;
}; // function ends
and controller method is :
public ActionResult DB_Rola(thing things)
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\PEACE_QURAN.MDF;Integrated Security=True";
System.Data.SqlClient.SqlConnection connection = new SqlConnection(connectionString);
int surah = things.surah;
int ayah =things.ayah;
String verse = things.verse;
// designing parametiric_query from the parameters
string query = "insert into Ayyat_Translation_Language_old_20131209 values(null,null,#Surah,#Verse)";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
//setting parameters for parametric query
SqlParameter Parm1 = new SqlParameter("Surah", surah);
SqlParameter Parm2 = new SqlParameter("Ayah", ayah);
SqlParameter Parm3 = new SqlParameter("Verse", verse);
//adding parameters
cmd.Parameters.Add(Parm1);
cmd.Parameters.Add(Parm2);
cmd.Parameters.Add(Parm3);
cmd.ExecuteNonQuery();
System.IO.StreamWriter file = new System.IO.StreamWriter(#"E:\Office_Work\Peace_Quran\Peace_Quran\Files\hisaab.txt", true);
file.WriteLine(" "+things.ayah);
file.Close();
connection.Close();
return View();
}
as mentioned above in code ,there is loop in my view page that passes single object at a time which is received in above controller method .it works for small amount of data but when i send bulk .i.e. 50+ records at once, some of records are not saved in my DB. i don't know what's wrong with my DB code. please help me figure it out.

Couldn't send and store String data to database through WCF

I have created a Windows 8 app, I have a table in SQL server database to store people's name, " [Name] VARCHAR (50)"
I have manage to send and save integer values to database, but when i modified my coding to store the string, it does not work, table data is empty. Please help!
itemDetail.html
<div>
<input id="join1" type="text" />
<button id="joinbtn">insert</button>
</div>
itemDetail.js
var joinButton = document.getElementById('joinbtn');
// Register Click event
joinButton.addEventListener("click", joinButtonClick, false);
function joinButtonClick() {
// Retrieve element
var baseURI2 = "http://localhost:45573/AddService.svc/Join";
var jointext = document.getElementById('join1').value;
WinJS.xhr({
type: "POST",
url: baseURI2,
headers: { "Content-type": "application/json" },
data: '{"namet":' + jointext + '}'
}).then(function complete(request) {
var resdata = request.responseText;
}, function error(er) {
var err = er.statusText;
})
}
AddService.svc.cs
public void Join(string namet)
{
string connectionString = System.Configuration.ConfigurationManager.
ConnectionStrings["Database1ConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "INSERT INTO Table2(Name) VALUES (#Name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name", namet);
try
{
con.Open();
int numAff = cmd.ExecuteNonQuery();
}
con.Close();
}
IAddService.cs
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
void Join(string namet);
Thank you!
I think the problem may be in this line
data: '{"namet":' + jointext + '}'
Try changing it to
data: '{"namet":\'' + jointext + '\'}'

Resources