Remove role and recovery the role in the table - asp.net

for a mistake. I used a wrong command. I wanted to remove an user' role from the table aspnet_UsersInRoles.
I guess that the command might be
Roles.RemoveUserFromRole(userName, origin_role);
However I used a wrong command mistakenly.
Roles.DeleteRole(origin_role,false);
Originally the table has 4 roles. Now the RoleId in the table only has two,
61572264-4935-461d-9d8c-71f147f28c34
c09f25e6-fd6a-447b-8e0d-eba0cfc94e40
How can I find and recovery them?
Many many thanks.

Hate to say it, but you're hosed. The default ASP.Net providers don't include any sort of auditing or soft-delete. If you have a database backup, you can explore/restore from that.

Below you find the source code for the function you called.
It calls the dbo.aspnet_Roles_DeleteRole stored procedure.
I don't have access to an asp.net membership database at the moment, otherwise I would check for you.
You might want to check what the stored procedure does, but as ssyladin mentioned I doubt you will be able to recover anything (since you sent the throwOnPopulatedRole argument to false).
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
try {
SqlConnectionHolder holder = null;
try {
holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
CheckSchemaVersion( holder.Connection );
SqlCommand cmd = new SqlCommand("dbo.aspnet_Roles_DeleteRole", holder.Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = CommandTimeout;
SqlParameter p = new SqlParameter("#ReturnValue", SqlDbType.Int);
p.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p);
cmd.Parameters.Add(CreateInputParam("#ApplicationName", SqlDbType.NVarChar, ApplicationName));
cmd.Parameters.Add(CreateInputParam("#RoleName", SqlDbType.NVarChar, roleName));
cmd.Parameters.Add(CreateInputParam("#DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit, throwOnPopulatedRole ? 1 : 0));
cmd.ExecuteNonQuery();
int returnValue = GetReturnValue(cmd);
if( returnValue == 2 )
{
throw new ProviderException(SR.GetString(SR.Role_is_not_empty));
}
return ( returnValue == 0 );
}
finally
{
if( holder != null )
{
holder.Close();
holder = null;
}
}
}
catch
{
throw;
}
}

Related

How to get out integer from database using IDataReader and Mapper

I'm very new in programming and this is my first post (question) here, so please don't judge me.
I'm trying to build my first individual WCF service for my project. Let me first display my code , so it will be easier to understand.
This is my data access layer:
public class DataAccessLayer : IDisposable
{
string DBConnectionString = "DBCS";
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResult = 0;
try
{
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.Create(DBConnectionString);
string storedProcedureName = "uspValidateUser";
DbCommand dbCommand = db.GetStoredProcCommand(storedProcedureName);
db.AddInParameter(dbCommand, "#EmployeeLogin", DbType.String, employeeLogin);
db.AddInParameter(dbCommand, "#EmployeePassword", DbType.String, employeePassword);
db.AddOutParameter(dbCommand, "#OutRes", DbType.Int32, outputResult);
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
Mapper.Reset();
Mapper.CreateMap<IDataReader, Int32>();
outputResult = (int)Mapper.Map<IDataReader, Int32>(reader);
}
}
catch (Exception ex)
{
throw ex;
}
return outputResult;
}
public void Dispose()
{
}
}
This is my stored procedure:
ALTER PROCEDURE [dbo].[uspValidateUser]
#EmployeeLogin VARCHAR(20),
#EmployeePassword VARCHAR(20),
#OutRes int Output
AS
SET #OutRes = (select count(*)
from dbo.tblEmployee
where EmployeeLogin = #EmployeeLogin
and EmployeePassword = #EmployeePassword)
if (#OutRes = 1)
BEGIN
SET NOCOUNT ON;
set #OutRes = 1 --Login is correct
end
else
BEGIN
set #OutRes = 0 -- Login is incorrect
END
And code behind my web form:
public int ValidateUser(string employeeLogin, string employeePassword)
{
int outputResults = 0;
try
{
using (HospitalWCFService.ContractsClient objWCFService = new HospitalWCFService.ContractsClient())
{
outputResults = objWCFService.ValidateUser(employeeLogin, employeePassword);
}
}
catch (Exception ex)
{
lgnEmployeeLogin.FailureText = ex.Message;
}
return outputResults;
}
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
int outputResults = 0;
outputResults = ValidateUser(lgnEmployeeLogin.UserName, lgnEmployeeLogin.Password);
if (outputResults == 1)
{
Session["UserName"] = lgnEmployeeLogin.UserName.ToString();
FormsAuthentication.RedirectFromLoginPage(lgnEmployeeLogin.UserName, lgnEmployeeLogin.RememberMeSet);
}
else
{
lgnEmployeeLogin.FailureText = "Username and/or password is incorrect.";
}
}
To get user credentials I'm using login control lgnEmployeeLogin.
I'm having problems of retrieving that output integer #OutRes parameter from database using Mapper (I need to use mapper)
If it is possible, please explain solution in easiest language possible as I might not understand difficult technical slang.
Thank you all in advance!
Your lack of answers could be because you say that you have to use mapper - but I chose to ignore that, because ExecuteReader is for dealing with the rows and columns returned by a stored procedure, not for its output parameters. The stored procedure you provided has no result set!
This could be as simple as
db.ExecuteNonQuery();
OutputResult = db.Parameters( "#OutRes").value
to be clear, this replaces your using...ExecuteReader block
Also note: your code did not deal with opening (and closing) the SQL connection (db.Connection.Open();, so I ignored that here too.

How do I check whether a Local Publication exists given the publication name and how do I delete it along with everything associated with it?

I'm working in ASP .NET and I need to do a couple of things:
Check whether the Publication I'm about to create already exists.
If it does, delete it along with EVERYTHING related to it (jobs, etc. including anything at the subscriber side).
I started with this:
public static bool PublicationExists(string server)
{
string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
using (var conn = new SqlConnection(finalConnString))
{
using (var cmd = new SqlCommand("what is the query to check whether a publication exists?", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
using (var da = new SqlDataAdapter(cmd))
{
using (var ds = new DataSet())
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return true;
}
return false;
}
}
}
}
}
Now...
If (PublicationExists(server) == true)
{
//I want to delete the publication along with everything associated with it.
}
How would I go about doing this?

Insert into bridge table entity framework

Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.
Problem Explained:
Original partial DB Diagram
Partial EF Model Diagram
Code I Wrote:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
So that what I did in the code,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
Exception generated
P.S: Let me know if you need more clarification.
Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:
using(DBEntities entities = new DBEntities())
{
//Make user object
var user = new User{
UserName = TxtbxUserName.Text,
Password = TxtBxPassword.Text,
Email = TxtbxEmail.Text,
CreateDate = DateTime.Now,
LastActivityDate = DateTime.Now,
IsEnabled = true
};
//Fetch type of Role from Roles table
var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
user.UserRoles.Add(userRole);
entities.User.AddObject(user);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}
Regards
Well thanks guys...
Here what I have done and it works,
DBEntities entities = new DBEntities();
//Make user object
var usr = new User();
//Fetch type of Role from Roles table
var userRole = (from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole).Single();
//copy user related info from textboxes
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
usr.UserRoles.Add(userRole as Roles);
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
entities.Dispose();

calling oracle stored procedure from asp.net application

in my asp.net application, i am calling a stored procedure (oracle) to get some values from database.
Following is the sp:
create or replace PROCEDURE GetUserData(
--SQLWAYS_EVAL# ARCHAR(100)
UserName IN NVARCHAR2, v_refcur OUT SYS_REFCURSOR)
as
BEGIN
BEGIN --SQLWAYS_EVAL# =#Password;
open v_refcur for SELECT StaffId,
UserName,
Password,
Pin,
LastUpdateId,
LastUpdateDate,
FullName,
PinFailedAttempts,
PinFailedDate
FROM UserData
WHERE UserName = UserName;
END;
RETURN;
END;
Can anyone help me how to call this sp from my asp.net code.
Using ODP, you'll can do something like the following:
make your stored procedure a function that takes the user name in parameter and returns a refcursor
create or replace FUNCTION GetUserData(UserName IN NVARCHAR2) RETURN SYS_REFCURSOR;
and then
using (var connection = new OracleConnection(connectionString))
{
using (var command = new OracleCommand("GetUserData", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.BindByName = true;
// Return value parameter has to be added first !
var returnValueParameter = new OracleParameter();
returnValueParameter.Direction = ParameterDirection.ReturnValue;
returnValueParameter.OracleDbType = ParameterDirection.RefCursor;
command.Parameters.Add(returnValueParameter);
var userNameParameter = command.Parameters.Add("UserName", userName);
returnValueParameter.Direction = ParameterDirection.In;
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Read the current record's fields
}
}
}
}
The Microsoft Enterprise Library simplifies the discovery and binding of Oracle Stored Procedures. It is not too difficult to build a Data Access Layer between your Business Objects and the Oracle database. I am more a fan of ORM tools these days like DevExpress's XPO, which in the latest release supports calling stored procedures. However, the Microsoft Entlib is free whereas DevExpress is not.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Your.BusinessObjects;
namespace DataAccess
{
public class UserDataDAL
{
public static Database dataBase = DatabaseFactory.CreateDatabase(); ///< Use default connection string configured in web.config
public static List<UserInfo> GetData(string userName)
{
List<UserInfo> listOfUserInfo = new List<UserInfo>();
UserInfo userInfo;
DbCommand cmd = dataBase.GetStoredProcCommand("SCHEMA.GETUSERDATA");
dataBase.DiscoverParameters(cmd);
dataBase.SetParameterValue(cmd, "USERNAME", userName);
using (IDataReader dr = dataBase.ExecuteReader(cmd))
{
while (dr.Read())
{
userInfo = new UserInfo();
userInfo.StaffId = dr["STAFFID"] != DBNull.Value ? Convert.ToInt32(dr["STAFFID"]) : 0;
userInfo.UserName = dr["USERNAME"] != DBNull.Value ? Convert.ToString(dr["USERNAME"]) : String.Empty;
userInfo.Password = dr["PASSWORD"] != DBNull.Value ? Convert.ToString(dr["PASSWORD"]) : String.Empty;
userInfo.LastUpdateId = Convert.ToInt32(dr["LASTUPDATEID"]);
userInfo.LastUpdateDate = dr["LASTUPDATEDATE"] != null ? Convert.ToDateTime(dr["LASTUPDATEDATE"]) : new DateTime();
listOfUserInfo.Add(userInfo);
}
}
return listOfUserInfo;
}
}
}
If you only ever expect one row to be returned from the procedure, then you can return the first item in the list if present etc.

Displaying error messages in C# web forms

i did my coding in console and used a system.console. write line in almost every if/else statement so as to display an error message if wrong values are entered of to say if what goes wrong. how ever am trying to apply the same analogy in web forms such that should there be a user error while running the conditions, an error message may be displayed to the user on the screen.
How do i go about displaying the errors?i know of item validations but cant apply that using if and else. however if i use try catch, i dont know which code displays the error message to user. but i know for sure i cant use SC.writelines.
a sample of my code is below.please advice..
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string strConn;
string userType;
strConn = "Provider=MIcrosoft.Jet.OLEDB.4.0;data Source=" +
Server.MapPath("App_Data/test.mdb");
OleDbConnection mDB = new OleDbConnection(strConn);
mDB.Open();
userClass aUser = new userClass();
if (aUser.verifyUser(mDB, Login1.UserName, Login1.Password))
{
userType = aUser.getUserDesc();
if (userType.ToLower() == "customer")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "front desk")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "technician")
{
Response.Redirect("StaffMenu.aspx");
}
else if (userType.ToLower() == "admin")
{
Response.Redirect("StaffMenu.aspx");
}
}
else
{
e.Authenticated = false;
}
mDB.Close();
when the program moves to the User class to run the verify method, it does so by running the following bock of code..
public bool verifyUser(OleDbConnection mDB, string userIDStr, string userPwrdStr)
{
string sqlQuery;
OleDbCommand cmd;
OleDbDataReader rdr;
//SC.Write("\n*******User Login********\nEnter User ID:");
//userIDStr = userIDInt.ToString();
//SC.Write("\nEnter User Password:");
//userPwrdStr = userPwrdStr;
sqlQuery = "SELECT UserID, UserPassword, UserDescription FROM UserTable WHERE UserID = " +
toSql(userIDStr);
cmd = new OleDbCommand(sqlQuery,mDB);
//Boolean valid = false;
//Boolean HasRows = false;
try
{
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
if (userIDStr == (string)rdr["UserID"])
{
if (userPwrdStr == (string)rdr["UserPassword"])
{
userDescStr = (string)rdr["UserDescription"];
if (userDescStr.ToLower() == "admin")
{
//SC.WriteLine("Welcome to Admin Main Menu");
return true;
}
else if (userDescStr.ToLower() == "front desk")
{
//SC.WriteLine("Welcome to Front Desk Staff Main Menu");
return true;
}
else if (userDescStr.ToLower() == "technician")
{
//SC.WriteLine("Welcome to Technical Staff Main menu");
return true;
}
else if (userDescStr.ToLower() == "customer")
{
//SC.WriteLine("Sorry, Customers are not allowed access to the Administrative page");
return true;
}
}
else
{
//SC.WriteLine("\nInvalid User Password, Please try again");
//verifyUser(mDB);
}
}
else
{
//SC.WriteLine("Invalid User ID, Please try again");
//verifyUser(mDB);
}
//HasRows = true;
}
rdr.Close();
}
catch (Exception ex)
{
SC.WriteLine(ex.Message);
}
return false;
}//=================================end verify User()
how ever if the wrong username or password is entered, how can i display an error message to the user as to which of the controls is receiving the wrong value...
am hoping to use this code to replace my SC.writelines that displays messages to the user....
You would probably build up a list of errors in a string and assign them to a label on the form, or potentially a ul tag.
I'd also recommend not differentiating whether or not a username or the password is invalid. If they don't manage to login, you should just display a 'Could not log in' message. If they get a correct username and an incorrect password, then using your method, I would know that I had guessed a correct username and could hammer away at passwords for that.
In addition, have you looked at the built in ASP.net login controls and the membership providers? They take care of a lot of this for you, or you can roll your own that integrates with the supplied controls.

Resources