Creating a Scheduling system in my Senior Project, Teacher couldn't find out why it's not finding either.
EmployeeIDTxtBox and PasswordTxtBox are both Text Boxes but cannot be found.
Thanks for the help!
Can anyone find the error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class LogIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitBtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MISSQL;Initial Catalog=NUSSOFTDB;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM EmployeeT WHERE EmployeeID='" + Convert.ToInt16(EmployeeIDTxtBox.Text) + "' and Password ='" + PasswordTxtBox.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Schedule1.aspx");
}
else
{
Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
}
Related
I have an application using ASP.NET Core, Angular 5 And ADO.NET
It worked fine until I decided to change the code to set a session variable with a database connection string gotten from my appssettings.json file.
I am using this as a reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2
However, when I try to set the session variable, I get a Null object reference in my SetSessionVariable() method.
Error is:
An error occurred while starting the application.
NullReferenceException: Object reference not set to an instance of an
object. Angular5NetcoreAdo.Startup.SetSessionVariable() in Startup.cs,
line 82
My code is:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Angular5NetcoreAdo.Models;
// Added these.
using Microsoft.AspNetCore.Http;
using System;
namespace Angular5NetcoreAdo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// Added this.
public HttpContext HttpContext { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory.
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddScoped<EmployeeDataAccessLayer>();
// Added this.
services.AddSession(options =>
{
options.Cookie.Name = ".ConnectionString";
});
// Added this.
SetSessionVariable();
}
// Added this.
public void SetSessionVariable()
{
HttpContext.Session.SetString("ConnectionString", Convert.ToString(Configuration.GetConnectionString("DBAngular5NetcoreAdoDatabase")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
// Added this.
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
---- Per a suggestion below, I am including that code here:
// Middleware extension method.
using Microsoft.AspNetCore.Builder;
namespace Angular5NetcoreAdo
{
public static class RequestConnectionMiddlewareExtensions
{
public static IApplicationBuilder UseRequestConnection(this
IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestConnectionMiddleware>();
}
}
}
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;
using Microsoft.Extensions.Configuration;
namespace Angular5NetcoreAdo
{
public class RequestConnectionMiddleware
{
public IConfiguration Configuration { get; }
public HttpContext HttpContext { get; }
private readonly RequestDelegate _next;
public RequestConnectionMiddleware(RequestDelegate next,
IConfiguration configuration)
{
_next = next;
Configuration = configuration;
}
public async Task InvokeAsync(HttpContext context)
{
// Set the session variable with the database connection string from appsettings.json.
HttpContext.Session.SetString("ConnectionString", Convert.ToString(Configuration.GetConnectionString("DBAngular5NetcoreAdoDatabase")));
await _next(context);
}
}
}
Now in the Startup.cs, I call the new middleware message method after the app.UseSession();
app.UseSession();
// Call the middlware now to set the session variable with the database
// connection string from appsettings.json.
app.UseRequestConnection();
------------------ Added now as a new error refers to this class.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
namespace Angular5NetcoreAdo.Models
{
public class EmployeeDataAccessLayer
{
public HttpContext HttpContext { get; }
public string connectionString;
public EmployeeDataAccessLayer(HttpContext httpContext)
{
// Set the property.
HttpContext = httpContext;
// Get the connection string session variable.
connectionString = HttpContext.Session.GetString("ConnectionString");
}
public IEnumerable<Employee> GetAllEmployees()
{
try
{
List<Employee> lstemployee = new List<Employee>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SelectEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Department = rdr["Department"].ToString();
employee.City = rdr["City"].ToString();
lstemployee.Add(employee);
}
rdr.Close();
con.Close();
}
return lstemployee;
}
catch
{
throw;
}
}
public Employee GetEmployeeData(int id)
{
try
{
Employee employee = new Employee();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SelectEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", id);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Department = rdr["Department"].ToString();
employee.City = rdr["City"].ToString();
}
rdr.Close();
con.Close();
}
return employee;
}
catch
{
throw;
}
}
public int AddEmployee(Employee employee)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", employee.Name);
cmd.Parameters.AddWithValue("#City", employee.City);
cmd.Parameters.AddWithValue("#Department", employee.Department);
cmd.Parameters.AddWithValue("#Gender", employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
public int UpdateEmployee(Employee employee)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UpdateEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", employee.ID);
cmd.Parameters.AddWithValue("#Name", employee.Name);
cmd.Parameters.AddWithValue("#City", employee.City);
cmd.Parameters.AddWithValue("#Department", employee.Department);
cmd.Parameters.AddWithValue("#Gender", employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
public int DeleteEmployee(int id)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpId", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
return 1;
}
catch
{
throw;
}
}
}
}
Its because documentation says
HttpContext.Session can't be accessed before UseSession has been
called.
and you call it in ConfigurationServices method where HttpContext.Session does not exist yet.
So you will need create your own middleware and call it after UseSession() method in Configure method.
I am trying to insert data from an aspx page to a database but keep getting the error:
errorSystem.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'User'
The code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace DatabaseConnectivity
{
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegiConnectionString"].ConnectionString);
conn.Open();
string insertQuery = ("insert into User(firstname,secondname,username,country,console,email,gamertag,password)values (#firstname,#secondname,#username,#country,#console,#email,#gamertag,#password)");
SqlCommand cmd = new SqlCommand(insertQuery, conn);
cmd.Parameters.AddWithValue("#firstname", TextBox1.Text);
cmd.Parameters.AddWithValue("#secondname", TextBox2.Text);
cmd.Parameters.AddWithValue("#username", TextBox3.Text);
cmd.Parameters.AddWithValue("#country", TextBox4.Text);
cmd.Parameters.AddWithValue("#console", TextBox5.Text);
cmd.Parameters.AddWithValue("#email", TextBox6.Text);
cmd.Parameters.AddWithValue("#gamertag", TextBox7.Text);
cmd.Parameters.AddWithValue("#password", TextBox8.Text);
cmd.ExecuteNonQuery();
Response.Write("User Successfully Registered");
conn.Close();
}
catch(Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
}
}
User is a reserved keyword, so you must use square brackets to make it explicit that you mean the object named "User" it, i.e. use [User] instead of User.
net and im making a web service in which user get registered and then login . i have made a database . in which "ID ","Username","Password" . in webserive it show which user is login
. this code is not working (name = reader[0].ToString();return name; ) name is red line . plz explain or do correction what is wrong where im mistaking
here is my connection string
<connectionStrings>
<add connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Abdul Samad\Documents\Visual Studio 2013\Projects\WebApplication8\WebApplication8\App_Data\webserver_database.mdf;Integrated Security=True" name="webconnectionstr"/>
</connectionStrings>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication8
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public int Register(string name , string password)
{
SqlConnection connection = new SqlConnection();
try
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["webconnectionstr"].ToString();
connection.Open();
SqlCommand cmd = new SqlCommand(#"insert into [userTable] (username,password) values
('" + name + "','" + password + "')", connection);
cmd.ExecuteNonQuery();
return 1;
}
catch(Exception ex) {
return 0;
}
finally
{
connection.Close();
}
}
[WebMethod]
public int getUsername(int id)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["webconnectionstr"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand(#"select username from [userTable] where userId='" + id + "'", con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
name = reader[0].ToString();
}
return cmd;
con.Close();
}
}
}
You should return a string (Assuming you are trying to return the name from table.)
[WebMethod]
public string getUsername(int id)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["webconnectionstr"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand(#"select username from [userTable] where userId='" + id + "'", con);
SqlDataReader reader = cmd.ExecuteReader();
string str = "";
while (reader.Read())
{
str = reader[0].ToString();
}
con.Close();
return str;
}
Edit : A Better Option since you want only one value.
string str = cmd.ExecuteScalar().ToString();
i develop a application to get video from vivotek ip camera the code is given below but it shows connecting to 10.60.13.12... video is not received
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VITAMINDECODERLib;
using AxVITAMINDECODERLib;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnconnect_Click_1(object sender, EventArgs e)
{
string strPreIP = "http://";
if (txtip.TextLength != 0)
axVitaminCtrl1.Url = strPreIP + txtip.Text;
// Port
axVitaminCtrl1.HttpPort = Convert.ToInt32(txtport.Text);
// User name
if (txtusername.TextLength != 0)
axVitaminCtrl1.UserName = txtusername.Text;
// Password
if (txtpass.TextLength != 0)
axVitaminCtrl1.Password = txtpass.Text;
// View stream
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)comboviewstream.SelectedIndex.GetHashCode();
// Protocol
axVitaminCtrl1.ConnectionProtocol = (VITAMINDECODERLib.EConnProtocol)comboprotocol.SelectedIndex.GetHashCode() + 1;
axVitaminCtrl1.Connect();
}
private void button1_Click(object sender, EventArgs e)
{
axVitaminCtrl1.Disconnect();
}
private void comboviewstream_SelectedIndexChanged(object sender, EventArgs e)
{
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)((System.Windows.Forms.ComboBox)sender).SelectedIndex.GetHashCode();
}
private void axVitaminCtrl1_OnVideoCodec(object sender, _IVitaminCtrlEvents_OnVideoCodecEvent e)
{
e.eVideoCodec = VITAMINDECODERLib.EVideoCodecType.eViCodecMJpeg;
}
}
}
You should check debug/release platform (change it to x86)
Your pc that run this program and the camera should have same subnet
I have some code here that connects to my Mysql database. It checks your username and password and if your login was successful and it retrieves the phone number under that account. How would the SQL Query look like for retrieving the phone number once connected? Then how would I be able to display that phone number on a label?
Have a look at this tutorial, should cover most of what you would need to know about connecting to MySQL, executing queries and displaying results:
VBMySQL Tutorial - Part 4
There are a number of other tutorials on that site, should get you going.
If part 4 gets into too much depth too quickly, check out part 1 first
public partial class _Default : System.Web.UI.Page
{
string strCon = ConfigurationManager.AppSettings["myConString"];
SqlConnection con;
SqlCommand com;
public string strPKDataValue;
public SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(strCon);
}
protected void Button5_Click(object sender, EventArgs e)
{
com = new SqlCommand("select * from student", con);
con.Open();
try
{
dr = com.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
if (dr.Read())
{
Label9.Text = Convert.ToString(dr["stuid"]);
}
}
}
catch (Exception ex)
{
Response.Write("Error :" + ex.Message);
}
finally
{
dr.Close();
con.Close();
}
}
}