Check Roles in Webmatrix - razor

I add two users and two roles in the webpages_UsersInRoles. I am trying to check to role of the user logging into the application.
Here is my code:
var UserId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
var User = WebSecurity.CurrentUserName;
var db = Database.Open("ApplicationServices");
var stQueryString = "SELECT * FROM Table1 WHERE (UserId) = (UserId) ORDER BY SubmitDate DESC";
var data = db.Query(stQueryString, UserId);
var grid = new WebGrid(data, rowsPerPage:20);
var AdminQueryString = "SELECT * FROM Table1 ORDER BY SubmitDate DESC";
var AdminData = db.Query(AdminQueryString);
var AdminGrid = new WebGrid(AdminData, rowsPerPage:20);
<div id="Divgrid">
#if (Roles.IsUserInRole(UserId, "admin") && (AdminData.Any())){
#AdminGrid.GetHtml(
tableStyle: "grid",
headerStyle: "grid-header",
footerStyle: "grid-footer",
alternatingRowStyle: "grid-alternating-row",
selectedRowStyle: "grid-selected-row",
rowStyle: "grid-row-style",
columns: AdminGrid.Columns(
AdminGrid.Column(header:"", format:#View),
AdminGrid.Column(header:"", format:#Treatment),
AdminGrid.Column("Name", format:#<text>#item.ClientName</text>),
AdminGrid.Column("Date", format:#<text>#item.SubmitDate</text>))) }
else if (Roles.IsUserInRole(UserId, "user") && (data.Any())) {
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "grid-header",
footerStyle: "grid-footer",
alternatingRowStyle: "grid-alternating-row",
selectedRowStyle: "grid-selected-row",
rowStyle: "grid-row-style",
columns: grid.Columns(
grid.Column(header:"", format:#View),
grid.Column(header:"", format:#Treatment),
grid.Column("Name", format:#<text>#item.ClientName</text>),
grid.Column("Date", format:#<text>#item.SubmitDate</text>))) }
</div>
Here is the error I am getting:
CS1502: The best overloaded method match for 'System.Web.Security.Roles.IsUserInRole(string, string)' has some invalid arguments

The IsUserInRole takes two parameters, the first is the User name, not the user ID. You may be able to use WebSecurity.CurrentUserName in place of where you have UserID.
One problem is the query needs to change to allow passing the username as a parameter:
var stQueryString = "SELECT * FROM Table1 WHERE UserId = #0 ORDER BY SubmitDate DESC";
The #0 indicates to take the parameter being passed in the Query.

Related

NodeJS MySQL module can't use two placeholders in a query

I'm trying to do this, which is exactly as it is in the documentation:
get_ids_query = 'SELECT ?? from ?? WHERE stat = 1 LIMIT 10'
then I call the function with two values placed inside variables:
var name = Table_Names.Tables_PR[t].name
var PK = Table_Names.Tables_PR[t].PK
ids = await this.getIds(PK, name)
This is the function:
async getIds(conf1, conf2) {
return await this.mydb.query(this.get_ids_query, conf1, conf2)
}
and these are the logs:
console.log(PK)
console.log(name)
console.log(mysql.format(this.get_ids_query, conf1, conf2))
output: idusers
users
SELECT `idusers` from ?? WHERE stat = 1 LIMIT 10
I've also tried:
var name = [Table_Names.Tables_PR[t].name]
var PK = [Table_Names.Tables_PR[t].PK]
which logs like this and it still returns the same query:
[ 'idusers' ]
[ 'users' ]
query format: SELECT `idusers` from ?? WHERE stat = 1 LIMIT 10
What am I doing wrong here? why is it reading the first placeholder but won't read the second one?

MOODLE. Problem with definition user role for course

I'm trying make solution by Using MOODLE create users and enroll them in courses via SQL
Add user - done
Add user to course - done
But user without role into course. No roles in role column.
'googleoauth2' as auth value for login with social network API. It's work.
The problem is remains If I change 'auth' value to 'manual'.
Into database all records as in queries.
Help, please.
UPD: sorry, I need to change enlorID to courseID in instanceid field...
Code:
async function test(){
var query = `INSERT INTO mdl_user (auth, confirmed, username, password, firstname, lastname, email, mnethostid)
VALUES ('googleoauth2', 1, '${pseudo}', 'not cached', '${name}',
'${secondname}', '${email}', 1);`;
var insertOutput = await getMysqlQuery(query);
var userId = insertOutput.results.insertId;
var courseRecords = await getMysqlQuery("SELECT id FROM mdl_course WHERE idnumber=\"" + shortname + "\"");
if(courseRecords.length < 1)
throw 'Course not found';
var courseId = courseRecords.results[0].id;
var enrolRecords = await getMysqlQuery(`SELECT id FROM mdl_enrol WHERE courseid=${courseId} AND enrol='manual';`);
if(enrolRecords.length < 1)
throw 'Enrol not found';
var enrolId = enrolRecords.results[0].id;
var contextRecords = await getMysqlQuery(`SELECT id FROM mdl_context WHERE contextlevel=50 AND instanceid=${courseId};`);
if(contextRecords.length < 1)
throw 'Context not found';
var now = (new Date()).getTime() / 1000 ;
var contextId = contextRecords.results[0].id;
await getMysqlQuery(`INSERT INTO mdl_user_enrolments (status, enrolid, userid,
timestart, timeend, timecreated, timemodified) VALUES
(0, ${enrolId}, ${userId}, '${now}', '${now + 60*60*24*2}', '${now}', '${now}')`);
await getMysqlQuery(`INSERT INTO mdl_role_assignments
(roleid, contextid, userid, timemodified)
VALUES (5, ${contextId}, '${userId}', '${now}');`);
}
It looks like you are using JavaScript. I have a solution to enroll the student in course with a role in PHP programming language as below.
$plugin = enrol_get_plugin('manual');
$course = $DB->get_record('course', array('id' => $courseid)); // Get course object by courseid
$instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'manual'));
if (empty($instance)) {
// Only add an enrol instance to the course if non-existent.
$enrolid = $plugin->add_instance($course);
$instance = $DB->get_record('enrol', array('id' => $enrolid));
}
// Take care of timestart/timeend in course settings.
$timestart = time();
// Remove time part from the timestamp and keep only the date part.
$timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
if ($instance->enrolperiod) {
$timeend = $timestart + $instance->enrolperiod;
} else {
$timeend = 0;
}
// Enrol the user with this plugin instance.
$plugin->enrol_user($instance, $user->id, $roleid); // This will enroll user in course with roleid you provided.

Node JS Parse Error in MySQL Syntax

In the following code, I am trying to query the database based on three parameters (search type, search term, operator that connects different search types in one query). As you can see, I gave it two search types along with their terms so that the query will be like search where the author is WayneRooney AND the tag is UCL. Later, it might have more than two search types such as search based on author x, author y, mention z, and tag a.
var search = ['Author','Tag'];
var term = ['WayneRooney','UCL'];
var operator = 'AND';
var queryString = "select Tweet.ID, Tweet.Label, Tweet.TDate, Tweet.RetweetID, User.Name, User.ScreenName from Tweet, User where";
for(var i in search){
if(search.indexOf(search[i]) != 0){
queryString += operator;
}
if(search[i] == 'Author')
{
queryString += "Tweet.UserID IN (select ID from User where ScreenName = '"+ term[i] +"') AND User.ID IN (select ID from User where ScreenName = '"+ term[i] +"')";
}
else if(search[i] == 'Mention')
{
queryString += "select Tweet.ID, Tweet.Label, Tweet.TDate, User.ScreenName, User.Name, Tweet.RetweetID from Tweet, User where Tweet.ID IN (select TweetID from TweetMention where UserID IN (select ID from User where ScreenName = '"+ term[i] +"')) AND User.ID = Tweet.UserID";
}
else if(search[i] == 'Tag')
{
queryString += "select Tweet.ID, Tweet.Label, Tweet.TDate, User.Name, User.ScreenName, Tweet.RetweetID from Tweet, User where Tweet.ID IN (select TweetID from TweetHashs where HashID IN (select ID from Hashtag where Label = '"+ term[i] +"')) AND User.ID = Tweet.UserID";
}
};
var query = connection.query(queryString, function(err, rows) {
if (err) {
throw (err);
}
console.log(rows);
//res.write(JSON.stringify(rows));
var tweet = JSON.parse(JSON.stringify(rows));
var queries_made = 0;
var queries_success = 0;
The error that I got is:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.UserID IN (select ID from User where ScreenName = 'WayneRooney') AND User.ID IN'at line 1
I tried to figure out what the problem is but I couldn't.
You're missing prepended spaces when appending to your queryString, otherwise you get run-on keywords like: whereTweet.UserID IN ... or ANDTweet.UserID IN ....

Webmatrix/Razor SQL query - Websecurity variable

I am trying to write a query to show all records owned by the current logged on user but i am having issues inserting the "userid" variable into the string?
#{
Layout = "~/_template1.cshtml";
var db = Database.Open("StayInFlorida");
var userid = WebSecurity.CurrentUserId;
var premierproperty = "SELECT PropertyName, PropertyID FROM PropertyInfo WHERE OwnerID='userid'";
}
<h1>Properties - Page coming soon</h1>
#userid
#foreach (var row in db.Query(premierproperty)){
#row.propertyname
}
Any ideas?
Try like this:
#{
Layout = "~/_template1.cshtml";
var db = Database.Open("StayInFlorida");
var userid = WebSecurity.CurrentUserId;
var premierproperty = "SELECT PropertyName, PropertyID FROM PropertyInfo WHERE OwnerID = #0";
}
<h1>Properties - Page coming soon</h1>
#userid
#foreach (var row in db.Query(premierproperty, userid))
{
#row.propertyname
}

How to write Linq-To-SQL statment which is equal to my following TSQL?

TSQL:-
Update table1
Set Name = 'John',
Address = null
where
ID = 1
LINQ-TO-SQL
var tab = db.Table1.Single(s => s.ID == 3);
tab.Name = DateTime.Now;
tab.Address = null;
db.SubmitChanges();
There isn't a single LINQ to SQL statement for updates. You have to retrieve the object, modify it, then save the changes (code assumes a single row since you have a specific Id):
var entity = context.Table1.Single(t => t.Id == 1);
entity.Name = "John";
entity.Address = "Toronto";
context.SubmitChanges();
using (var dataContext = new MyEntities())
{
var contact = Contacts.Single (c => c.ContactID == 1);
contact.FirstName = 'John';
contact.Address= 'Toronto';
dataContext.SaveChanges();
}