Update Row in Table on Database for Each New User WebMatrix - mysql

I have a table (About_User) in my database (StarterSite) that is supposed to work so that each seperate row is for each seperate user. However, no matter which user is signed in, they all have access to the same row (in other words new rows aren't being created for each new user). I have triple checked to make sure everything in my database was set up correctly. I am using the StarterSite template with this Registration page (edited for question):
// If all information is valid, create a new account
if (Validation.IsValid()) {
// Insert a new user into the database
var db = Database.Open("StarterSite");
// Check if user already exists
var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(#0)", email);
if (user == null) {
// Insert email into the profile table
db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email);
// Create and associate a new entry in the membership database.
// If successful, continue processing the request
try {
bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
if (requireEmailConfirmation) {
var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
WebMail.Send(
to: email,
subject: "Please confirm your account",
body: "Your confirmation code is: " + token + ". Visit " + confirmationUrl + " to activate your account."
);
}
if (requireEmailConfirmation) {
// Thank the user for registering and let them know an email is on its way
Response.Redirect("~/Account/Thanks");
} else {
// Navigate back to the homepage and exit
WebSecurity.Login(email, password);
Response.Redirect("~/");
}
} catch (System.Web.Security.MembershipCreateUserException e) {
ModelState.AddFormError(e.Message);
}
} else {
// User already exists
ModelState.AddFormError("Email address is already in use.");
}
}
The table does have an ID column that (should) autoincrement.
The other columns are from a form that collects different information from the user like an 'About Me' page and therefore should be different for each person.
How can I accomplish this?

There are some things in your question that I don't understand. First of all your code doesn't look edited (it is the same as the template from row 39 to row 82). Second, your question has the mysql tag: if you are using a MySql database instead of the Sql Ce database of the Starter Site template, maybe this could be the problem (look at WebSecurity.CreateAccount fails for MySQL).
With the default StarteSite Sql Ce database the answer to your question is quite simple. Add the following row
db.Execute("INSERT INTO About_User(UserId, UserPage) VALUES (#0, #1)",
db.GetLastInsertId(), userPage);
just after the db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email); statement.
There is no need of an ID autoincrement column in your About_User table, but only of a UserId Primary Key column as foreing key.

Related

How can I group exact string together?

I'm working with a google sheet that contains a column of unique project numbers followed by a column with the equipment description used in that project. I have set up my code to send an automatic email with this information to a list of recipients. What I want to do that I don't know how to is what code can I use that will read the project number column and when it finds two project numbers exactly the same, it will group the equipment together into a list that will be sent in that automatic email. I know the list can be a variable but I just don't know how to make it look for spa project numbers to join the equipment together without changing anything in the google sheet. Thank y'all!
I'm agree with Cooper. To build an object is a most obvious way to get unique values (ID, etc) from any list:
var data = [
[1,'a'],
[2,'b'],
[3,'c'],
[1,'d']
]
var obj = {};
data.forEach(x => {
try { obj[x[0]].push(x[1]) } // try to add the value to an existed array
catch(e) { obj[x[0]] = [x[1]] } // or make an array if there is no existed one
});
console.log(obj); // out: [ {1:[a,d]}, {2:[b]}, {3:[c]} ]
var id = 1
console.log('All the values from ID '+ id + ': ' + obj[id].join(', ')); // out: a, d

Google Form data to store in cloud SQL database

I'm new to Google Forms and Google Apps Script. I have ten Google Forms, and on submitting forms they populate a corresponding Google Sheet.
Now, here is what I want, on submitting form I want that information to also be stored in the cloud SQL database. What steps will accomplish that?
The normal data flow for a Google Form that is accepting responses and replicating them to a Spreadsheet looks like this:
You've got two opportunities for a Form Submission Trigger to replicate the form responses in your Cloud SQL database; you can either trigger from the Google Form Form submit event or the Google Sheets Form submit event.
Either way, you will have a script that gets called for every form submission, and an event object that contains the response values. Your trigger function should use the JDBC to connect to the database - that link includes an intro that walks you through the highlights.
Example
Say we have a form asking two questions, "Name" and "Age". That would result in 3 columns in our spreadsheet; "Timestamp" plus one for each question.
To match that, we have a Cloud SQL database set up with the same three columns.
A Google Sheets Form submit trigger function that wrote to a Cloud SQL database would look like this untested code:
// Replace the variables in this block with real values.
var address = 'database_IP_address';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
// Receive form response and replicate to a row in SQL table
function handleFormSubmit( event ) {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(Timestamp, Name, Age) values (?, ?, ?)');
stmt.setString(1, event.namedValues['Timestamp']);
stmt.setString(2, event.namedValues['Name']);
stmt.setString(3, event.namedValues['Age']);
stmt.execute();
}
Posing an example of a solution I have working. I modified Mogsdad's script to use the most up to date parameters & connection function, and fixed the syntax errors.
//Event is automatially passed on form submission when executed as a trigger.
//It contains objects that the user submitted
function writeToCloudSQL(event) {
//Note we get subname from the 'Instance Connection Name' of the Overview tab in the CloudSQL portal
var subname = 'see image';
var user = 'user';
var userPwd = 'pwd';
var db = 'db_name';
var dbUrl = 'jdbc:google:mysql://' + subname + '/' + db;
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO tbl_users (Timestamp, DL_ID, DOB, Last4SSN, HTMLGathered) values (NOW(), ?, ?, ?, \'No\');');
stmt.setString(1, event.namedValues['DL_ID']);
stmt.setString(2, event.namedValues['DOB']);
stmt.setString(3, event.namedValues['Last4SSN']);
stmt.execute();
}
Locating the subname:
Locating the subname
Read more about the Event parameter here:
https://developers.google.com/apps-script/guides/triggers/events
Read more about the connection string here:
https://developers.google.com/apps-script/reference/jdbc/jdbc#getCloudSqlConnection(String,String,String)
Also be sure you've allowed network access to google scripts
https://developers.google.com/apps-script/guides/jdbc?hl=en#using_jdbcgetconnectionurl
Zapier with their SQL Server and Google Sheets integrations can do this. I'm not affiliated.
https://zapier.com/apps/sql-server/integrations
If you don't want to roll your own solution, SeekWell lets you automatically send data from SQL to Sheets and can also sync changes from Sheets back to a database. Apps Script can do pieces of this, but I found it buggy and limited for our use case, so I built something else. There are both free and paid plans.
Disclaimer: I built this.

Script to validate if value exists in a list

I have a google spreadsheet which will be used for collaboration and I was able to create a UI interface which will fetch and update data from a table to make it easier for users.
For the work I need to restrict users to only be able to update rows if they are assigned to them and I am able to do it. But along with that, I also need to allow administrator to assign or update rows which are not assigned to them.
I have a table with all employee's email address and an admin flag for those who are admin.
Name____________Email________________Is Admin
Employee 1_______emp1#domain.com_____Admin
Employee 2_______emp2#domain.com_____
Employee 3_______emp3#domain.com_____
Employee 4_______emp4#domain.com_____Admin
Employee 5_______emp5#domain.com_____
Employee 6_______emp6#domain.com_____
How can I write a something in my script that will allow me to if the user who is triggering a function has admin right or not.
I user Session.getActiveUser().getEmail() to pull out the users email address. I am creating the tool to be used within google apps domain.
Code that checks if the user is the owner of the row, this part works fine but what I want to do is if a user is admin they basically will skip this check.
if (s.getRange("E4").getValue() != usr()){
msg("Once a Task is assigned to an employee, only assigned employee can make any changes to the Task. Thank you");
return;
}
s = sheet
usr() = function calling to check active user email
If I can do something like countifs where I can check count based on the email address and Admin criteria and if its >= 1 proceed if its 0 show error that you can not make changes.
Please let me know.
Really appreciate the help.
Thank you.
Zooooon
Are you looking for something like this?
function myFunction() {
var s = SpreadsheetApp.getActiveSheet();
var usr = Session.getActiveUser().getEmail();
var emails = s.getRange("E2:F").getValues();
for (var i=0;i<emails.length;i++) {
if (emails[i][0] === usr){
if (emails[i][1] === "Admin") {
//Do something when Admin
return;
} else {
//Do something when not admin
return;
}
} else {
//Do something when email not in the list
}
}
}
I am assuming your data is in the range "D:F"

Receiving duplicate emails with sendEmail()

I tried both MailApp.sendEmail() and GmailApp.sendEmail() to send an email confirmation from onFormSubmit and ending up with multiple duplicate emails (as many as 6). The code looks like this:
function sendEmailConf_(ss, email, session) {
Logger.log("sendEmailConf_ email: %s for session: %s", email, session);
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var formResponses = form.getResponses();
Logger.log("Count of form responses: %s", formResponses.length);
for (var i = 0; i < formResponses.length; i++) {
if (formResponses[i].getRespondentEmail() == email) {
Logger.log("Sending email to: %s for session: %s", email, session[0]);
GmailApp.sendEmail(
email,
'Confirmation for registration of: ' + session[0] + ', ' + getSessionSchedStr(session),
('Thanks for registering!\n\n' + getResponseAsText(formResponses[i]) + '\n\n' +
'You may change your response using this URL: ' + formResponses[i].getEditResponseUrl())
);
}
}
}
Using script transcript and log statements, I confirmed that sendEmail() is getting called only once and that the email is a string with single email address in it. The emails I receive have exactly the same body and are received at the same time and they all have the same from and to addresses (both mine, since I am testing it). Anybody has a clue on what is going wrong here?
Edit: Just observed that the duplicate count is increasing by one every time it is run. I just tried it again and got 7 fresh emails, all exact duplicates (and different from prior 6). I am clueless on what could be causing such a behavior.
Open the script editor and choose Resources -> Current Project Triggers. Make sure you only have a single trigger associated with the script.
If you have shared the script with multiple users, you'll have to repeat this from the account of every user who may have authorized the script.

Sharepoint 2013 app user Guid

i am having little problem in getting Sharepoint Userid (GUID) in SP App 2013.
so far i am getting Sharepoint user's Email address and his Full name using userProfile class of Sharepoint (SP.UserProfile.js).
i needed to get Unique id of the user which we say GUID.. i used below code for that , but everytime i get random so called Guid of the same User.(ehich is definitely not unique id of user).
How can i get sharepoint's user id that is unique on every login.
Please Help!
Thanks
Here is my code snippet
var targetUser;
var userProps;
var contxt_web = null;
var clientContext = new SP.ClientContext.get_current();
/** Get id of Current SP User*/
contxt_web = clientContext.get_web();
clientContext.load(contxt_web);
/***/
peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProps = peopleManager.getMyProperties(targetUser);
clientContext.load(userProps);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
function onRequestSuccess() {
var messageText = "Name : " + userProps.get_displayName()
+ " Sharepoint-ID : " + contxt_web.get_id()
+ " Email : " + userProps.get_email();
}
Try using userprops.get_userId ,it may works..