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();
Related
I have used Entity Framework for a long time, but have an edge case where I need to use SQL. I was wondering if I could use my existing Entity Framework Core context for this or not. Here is what I have currently, but the queryResults variable contains a "-1" value, instead of a list of Students, after running it:
string tableName = "Students";
var queryResults = db.Database.ExecuteSqlRaw(#"SELECT * FROM {0}", tableName);
Any ideas?
Entity Framework Core 3.1
.NET Core 3.1
Linq-to-SQL
It is possible; I just had to do this for a pet project.
You need to reference the Microsoft.EntityFrameworkCore.Relational NuGet.
ConsoleApp Example:
Program.cs
using System.Collections.Generic;
namespace EfDirectSql
{
class Program
{
/*
* written: VS2019 .Net Core 3.1 Console App
*
* used nugets:
*
* Microsoft.EntityFrameworkCore.SqlServer 3.1.0
* Microsoft.EntityFrameworkCore.Relational 3.1.0
*
*/
static void Main(string[] args)
{
// attention: supply your database server name
ApplicationContext context = new ApplicationContext("?YOURSERVER?", "Master");
// note: leveraging included extension methods for the dbContext class.
object scalarResult = context.ExecuteScalar("SELECT COUNT(1) FROM Master.dbo.SysObjects");
object nonQueryResult = context.ExecuteNonQuery("SELECT * FROM Master.dbo.SysObjects"); // likely your -1
IEnumerable<SysObject> readerResult = context.ExecuteReader<SysObject>("SELECT * FROM Master.dbo.SysObjects");
}
}
}
ApplicationContext.cs
using Microsoft.EntityFrameworkCore;
namespace EfDirectSql
{
public class ApplicationContext
: DbContext
{
public ApplicationContext(string serverName, string catalogName)
{
this.ServerName = serverName;
this.CatalogName = catalogName;
}
public readonly string ServerName;
public readonly string CatalogName;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer($"Data Source={this.ServerName};Initial Catalog={this.CatalogName};Integrated Security=true;");
base.OnConfiguring(optionsBuilder);
}
}
}
DbContextExtensions.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace EfDirectSql
{
public static class DbContextExtensions
{
public static object ExecuteScalar
(
this DbContext context,
string sql
)
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
object result = null;
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
result = command.ExecuteScalar();
}
finally
{
connection.Close();
}
return result;
}
public static int ExecuteNonQuery
(
this DbContext context,
string sql
)
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
int result;
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
result = command.ExecuteNonQuery();
// likely the -1
}
finally
{
connection.Close();
}
return result;
}
public static IEnumerable<TType> ExecuteReader<TType>
(
this DbContext context,
string sql
)
where TType : class, new()
{
IDbConnection connection = context.Database.GetDbConnection();
IDbCommand command = connection.CreateCommand();
IEnumerable<TType> result = new List<TType>();
try
{
connection.Open();
command.CommandText = sql;
command.CommandType = CommandType.Text;
IDataReader reader = command.ExecuteReader(CommandBehavior.Default);
result = Convert<TType>(reader);
}
finally
{
connection.Close();
}
return result;
}
private static IEnumerable<TType> Convert<TType>(IDataReader reader)
where TType : class, new()
{
List<PropertyInfo> properties = typeof(TType)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanWrite)
.ToList();
IList<TType> instances = new List<TType>();
while (reader.Read())
{
TType instance = new TType();
properties
.ForEach
(p =>
// for the purposes of the example, this works - could be outliers.
p.SetValue(instance, reader[p.Name] == DBNull.Value ? null : reader[p.Name])
);
instances.Add(instance);
}
return instances;
}
}
}
SysObject.cs
namespace EfDirectSql
{
// shortened represenation of the MS-SQL sysobject table
public class SysObject
{
public string name { get; set; }
public int id { get; set; }
public string xtype { get; set; }
public int uid { get; set; }
public int info { get; set; }
public int status { get; set; }
// the rest are not needed for a demo.
}
}
"I was wondering if I could use my existing Entity Framework Core context for this or not":
Yes you can use your existing databaseContext but you have to execute that query on your dbContext Entity see the example below:
var sqlCommand = $"SELECT * FROM Students";
var executeSQL = await _context.Students.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(executeSQL);
Output:
Note: As you can see I am executing sqlCommand on Students dbContext this is valid. But using DbContext you cannot pass the
table name dynamically. You must need to define it explicitly.
Hope above steps guided you accordingly, You can have a look on official document for more details here
Update Using Ado.Net Connection:
using (var connection = _context.Database.GetDbConnection())
{
connection.Open();
var tableName = "Students";
List<Student> _listStudent = new List<Student>();
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = string.Format("SELECT * FROM [{0}];", tableName);
SqlDataReader reader = (SqlDataReader)command.ExecuteReader();
while (reader.Read())
{
var student = new Student(); // You have to bind dynamic property here based on your table entities
student.FirstName = reader["FirstName"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
student.LastName = reader["LastName"].ToString();
_listStudent.Add(student);
}
reader.Close();
command.Dispose();
connection.Close();
}
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>");
}
}
}
Error 1
'UserWcfService.userService' does not implement interface member
'UserWcfService.IuserService.Getuserdetails()'.
'UserWcfService.userService.Getuserdetails()' cannot implement an
interface member because it is not
public. C:\Users\ravi\Documents\Visual Studio
2013\Projects\wcfservices\UserWcfService\UserWcfService\userService.svc.cs 16 18 UserWcfService
userservice.svc.cs code:
namespace UserWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "userService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select userService.svc or userService.svc.cs at the Solution Explorer and start debugging.
public class userService : IuserService
{
public string str = ConfigurationManager.ConnectionStrings["connstring"].ToString();
List<usertype> Getuserdetails()
{
List<usertype> userdetails=new List<usertype>();
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spgetdata", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for(int i=0; i<dt.Rows.Count; i++)
{
usertype objinfo = new usertype();
objinfo.name = Convert.ToString(dt.Rows[i]["name"]);
objinfo.gender = Convert.ToString(dt.Rows[i]["gender"]);
objinfo.dateofbirth = Convert.ToDateTime(dt.Rows[i]["dateofbirth"]);
objinfo.address = Convert.ToString(dt.Rows[i]["address"]);
objinfo.contactno = Convert.ToInt32(dt.Rows[i]["contactno"]);
objinfo.mailid = Convert.ToString(dt.Rows[i]["mailid"]);
userdetails.Add(objinfo);
}
}
conn.Close();
}
return userdetails;
}
public string newuser(usertype user)
{
string strmessage;
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#C_Users_Name", user.name);
cmd.Parameters.AddWithValue("#C_Users_Gender", user.gender);
cmd.Parameters.AddWithValue("#lC_Users_DOB", user.dateofbirth);
cmd.Parameters.AddWithValue("#C_Users_Address", user.address);
cmd.Parameters.AddWithValue("#C_Users_ContactNo", user.contactno);
cmd.Parameters.AddWithValue("#C_Users_MailID", user.mailid);
//cmd.Parameters.AddWithValue("#C_Users_RegisteredDate", userinfo.date);
int result = cmd.ExecuteNonQuery();
if(result==1)
{
strmessage = user.name + "details inserted succesfully";
}
else
{
strmessage = user.name + "Details not inserted";
}
conn.Close();
}
return strmessage;
}
}
}
and IUserService code:
namespace UserWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IuserService" in both code and config file together.
[ServiceContract]
public interface IuserService
{
[OperationContract]
List<usertype> Getuserdetails();
[OperationContract]
string newuser(usertype user);
}
[DataContract]
public class usertype
{
[DataMember]
public string name { get; set; }
[DataMember]
public string gender { get; set; }
[DataMember]
public DateTime dateofbirth { get; set; }
[DataMember]
public string address { get; set; }
[DataMember]
public int contactno { get; set; }
[DataMember]
public string mailid { get; set; }
[DataMember]
public DateTime date { get; set; }
}
}
All interface methods are by default public therefore your class which dervies interface needs to be public as well.
A good way to see what you are doing wrong here is to right click on the IuserService in
public class userService : IuserService
go to implement interface -> implement interface explicitly
this will create the stub methods that are implementing your interface. you can either drop your code into those or you could adjust the methods that you have appropriately
Here is an example which built I derived using the method I described above
public class userService : IuserService
{
public string str = ConfigurationManager.ConnectionStrings["connstring"].ToString();
List<usertype> IuserService.Getuserdetails()
{
List<usertype> userdetails = new List<usertype>();
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spgetdata", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
usertype objinfo = new usertype();
objinfo.name = Convert.ToString(dt.Rows[i]["name"]);
objinfo.gender = Convert.ToString(dt.Rows[i]["gender"]);
objinfo.dateofbirth = Convert.ToDateTime(dt.Rows[i]["dateofbirth"]);
objinfo.address = Convert.ToString(dt.Rows[i]["address"]);
objinfo.contactno = Convert.ToInt32(dt.Rows[i]["contactno"]);
objinfo.mailid = Convert.ToString(dt.Rows[i]["mailid"]);
userdetails.Add(objinfo);
}
}
conn.Close();
}
return userdetails;
}
public string newuser(usertype user)
{
string strmessage;
SqlConnection conn = new SqlConnection(str);
{
conn.Open();
SqlCommand cmd = new SqlCommand("spinsert", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#C_Users_Name", user.name);
cmd.Parameters.AddWithValue("#C_Users_Gender", user.gender);
cmd.Parameters.AddWithValue("#lC_Users_DOB", user.dateofbirth);
cmd.Parameters.AddWithValue("#C_Users_Address", user.address);
cmd.Parameters.AddWithValue("#C_Users_ContactNo", user.contactno);
cmd.Parameters.AddWithValue("#C_Users_MailID", user.mailid);
//cmd.Parameters.AddWithValue("#C_Users_RegisteredDate", userinfo.date);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
strmessage = user.name + "details inserted succesfully";
}
else
{
strmessage = user.name + "Details not inserted";
}
conn.Close();
}
return strmessage;
}
I am new to asp.net and I am trying to implement my role provider, actually sql role provider. In my Role Provider I added:
public void AddUsersToRole(string[] usernames, string[] rolenames)
{
SqlConnection conn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Users " +
" (Username, Role) " +
" Values(?, ?)", conn);
SqlParameter Username = cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50);
SqlParameter Role = cmd.Parameters.Add("#Role", SqlDbType.NVarChar, 50);
try
{
conn.Open();
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
Username.Value = username;
Role.Value = rolename;
cmd.ExecuteNonQuery();
}
}
}
But when I put in my login page the following:
Roles.AddUsersToRole(TextBoxUsername.Text, DropDownListRole.SelectedItem.Value);
And when I build it I got an error.
Please help, tnx in advance.
your method expecting string[] but you are providing string.
Roles.AddUsersToRole(TextBoxUsername.Text, DropDownListRole.SelectedItem.Value);
public void AddUsersToRole(string[] usernames, string[] rolenames)
solution:
Roles.AddUsersToRole(new string[] { TextBoxUsername.Text }, new string[] { DropDownListRole.SelectedItem.Value });
I'm trying to create a WCF Service using Silverlight Frontend. THe WCF Code is fairly simple however I keep getting The modifier public is not valid for this item. I have set everything to public, and cannot understand this error. Can someone please help.
Here is the code
[OperationContract]
public void SaveEmployee(int id, string firstname, string Lastname);
public void SaveEmployee(int id, string firstname, string Lastname)
{
Person NewPerson = new Person();
string connect = ConfigurationManager.ConnectionStrings["AdventureWorks"].ToString();
using (var con = new SqlConnection(connect))
{
SqlCommand cmd = new SqlCommand("spSaveEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParaID = new SqlParameter
{
ParameterName = "#ID",
Value = id
};
cmd.Parameters.Add(ParaID);
SqlParameter ParaFirstName = new SqlParameter
{
ParameterName = "#firstname",
Value = firstname
};
cmd.Parameters.Add(ParaFirstName);
SqlParameter ParaLastName = new SqlParameter
{
ParameterName = "#Lastname",
Value = Lastname
};
cmd.Parameters.Add(ParaLastName);
con.Open();
cmd.ExecuteNonQuery();
}
}
As you are creating the interface for your service, you can't provide the modificators for it's methods, only for whole interface.
Change your OperationContract to:
[OperationContract]
void SaveEmployee(int id, string firstname, string Lastname);