Sql Role Provider - sql

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 });

Related

C# foreach loop skipping some values during iteration

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");
}

ASP.Net Core - setting and getting session variables

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.

When creating a WCF service, I get error: doesn't implement interface member

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;
}

WCF Silverlight

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);

connecting webservice to sql server

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();