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);
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();
}
I have a multi-select control whereby I need to commit all items selected to SQL Server table. When I submit the form only 1 item is getting committed even though when i inspect using Step Debugger all the selected values are indeed populated in variable employeees4 (attached image). i have observed that only the first item in the selection is getting committed. Any help on what i could possibly be missing?
Please note that i have used slightly different variable name in attached image has i.e year instead of employeees4, but the code is the same .
I am getting selected items as below :
[HttpPost]
public ActionResult NewOverTimeRequest(FormCollection formcollection)
{
Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
try
{
var batch = new OvertimeBatch();
request.employees = GetEmployees();
request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
var employeees1= request.EmployeeNumber.Split(',');
string[] employeees2 = employeees.SingleOrDefault().ToArray();
string employeees3 = Helpers.ConvertStringArrayToString( employeees2);
string[] employeees4 =employeees3.Split(new char[] { ',' });
if (ModelState.IsValid)
{
foreach ( string emp in employeees4)
{
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpNum", emp);
cmd.Parameters.AddWithValue("#DateDone", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View(request);
}
return RedirectToAction("OverTime");
}
}
Model :
[Required]
[Display(Name = "Employee ")]
public string[] EmployeeNumber { get; set; }
public Employee Employee { get; set; }
public String DisplayName { get; set; }
public IEnumerable<SelectListItem> employees { get; set; }
Try changing you If condition to below.
if (ModelState.IsValid)
{
using(SqlConnection conn = New SqlConnection(Helpers.DatabaseConnect))
{
conn.Open();
SqlCommand cmd = New SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpNum", SqlDbType.varchar(max));
cmd.Parameters.Add("#DateDone", SqlDbType.DateTime);
foreach(String emp In employeees4)
{
cmd.Parameters["#FixtureId"].Value=emp;
cmd.Parameters["#FixtureId"].Value= DateTime.Now;
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
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 });
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();