manipulating email address with a sql stored procedure - sql-server

I'm trying to figure out how to best manipulate an email adress within this (part of) stored procedure.
IF(#LoginName IS NULL OR #LoginName = '')
BEGIN
set #LoginName = #Email
END
What is happening: a user is saved but If the email already exist the email address receives a number at the end of it. for example: test#email.com12
once this email is written to the database this stored procedure saves the email as the login name. however I want the login name to be just "test#email.com" without the "12" at the end of it. What would the best way to do this be?
Thanks for any help, my sql skills are not very good.
Here is the javascript that alters the email address and writes it to the database
function userEdit()
{
if (typeof userEdit.counter == 'undefined')
{
userEdit.counter = 0;
}
userEdit.counter++;
var change = document.getElementById("txtEmail").value;
var email = change + "" +userEdit.counter;
var telephone = document.getElementById("txtTelephone").value;
var mobile = document.getElementById("txtMobile").value;
var loginUser = document.getElementById("chkLogin").checked;
var password = document.getElementById("txtPassword").value;
var confirmpassword = document.getElementById("txtConfirmPassword").value;
card.user.update(wizard.stateInfo.activeUserID, wizard.stateInfo.activeUser, email, telephone, mobile, loginUser, password);
}

The best practice here is to keep a record of both the modified and unmodified email addresses, in two different variables. Then you don't need to "undo" the changes, you just pick the variable that is suitable to your needs at that time.

Related

Save different data for same user on different Guilds

I set up a stats command as follows
[Command("Stats")]
public async Task StatsOther(SocketUser socketUser = null)
{
if (socketUser == null)
{
socketUser = Context.User;
}
var account = UserAccounts.GetAccount(socketUser);
await Context.Channel.SendMessageAsync($"Hey {socketUser.Mention}, You have {account.Size} long sandwhiches and {account.XP} XP.");
}
And the class UserAccounts searches if there exists in our database a socketUser with the ID property. Now say the same user in on different guild I need to store different data for him but the socketUser.ID will be the same no matter the guild. So when the user tries to use stats command he will see the same data irrespective of the guild he is in right now.
Here is where UserAccounts.GetAccount leads and does its thing,
public static UserAccount GetAccountFromID(ulong ID)
{
var result = from a in accounts
where a.ID == ID
select a;
var FoundAccount = result.FirstOrDefault();
if (FoundAccount == null)
{
FoundAccount = CreateUserAccount(ID);
}
return FoundAccount;
}
Clearly the linq query is checking for IDs and they happen to be the same for a user no matter the guild.
I tried using SocketGuildUser but sadly a socketGuildUser.ID is also independent of the guild. So I am unable to store different data for the same user from different guilds. Using the latest beta available.
How can I achieve this.
You could make use of a Dictionary implemented for each user. Where each user have its own Dictionary<GuildID, Data>.
And on the SQL side (if you are using SQL), you could have a new table, where it has a foreign key constrain on the User ID, and has a Guild ID too.
(The foreign key constrain on userID might not be needed if none of the user's stats is shared between all guilds; Aka you just have a SQL-table which you can do a SELECT stuff FROM tableName WHERE userID = ? AND guildID = ?)

obtain the real identity of the connected user

dxStatusbar1.Panels1.Text :=
DataModule2.UniConnectDialog1.Connection.Username;
...gives me the username that has connected to sql server.
However the connected user has a different name in the actual database.
Example:
His login name for the sql server is 'John' and is user mapped to 'Northwind' database.
However in 'Northwind' database he is called 'John Smith'.
And this is the name (John Smith) I am trying to have displayed in dxStatusbar1.Panels1.Text
after he connects.
How can I get that ?
edit :
Tried Victoria suggestion :
UserName := DataModule2.UniConnection1.ExecSQL('SELECT :Result = CURRENT_USER', ['Result']);
dxStatusbar1.Panels[1].Text := UserName;
but get :
I couldn't find any UniDAC API way to get currently connected user name (not even for SDAC), so I would just issue a SQL command querying CURRENT_USER and grab the name from the result:
SELECT CURRENT_USER;
Or in the Unified SQL way with the USER function:
SELECT {fn USER};
Since you've mentioned stored procedure in your comment, it sounds to me like you probably want to get this information directly from a connection object without using query object. If that is so, you don't even need to have a stored procedure but execute directly command like this:
var
UserName: string;
begin
UserName := UniConnection1.ExecSQL('SELECT :Result = CURRENT_USER', ['Result']);
...
end;
Or in unified way:
var
UserName: string;
begin
UserName := UniConnection1.ExecSQL('SELECT :Result = {fn USER}', ['Result']);
...
end;
One of these might do the job for you. Haven't tested.
SELECT ORIGINAL_LOGIN()
SELECT SYSTEM_USER
SELECT SUSER_SNAME()
Hope it helps.
ORIGINAL_LOGIN: Returns the name of the login that connected to the instance of SQL Server. You can use this function to return the identity of the original login in sessions in which there are many explicit or implicit context switches.
SYSTEM_USER: Allows a system-supplied value for the current login to be inserted into a table when no default value is specified.
SUSER_SNAME: Returns the login name associated with a security identification number (SID).

What is the proper way to request this entity? Python and GQL

I'm trying to see if the username variable in the post function matches the username in the accountsArchive entity.
I think the problem is that user.username isn't the proper way to reference the username entity. Also, the query above may have a problem. What's the proper way to see if the two usernames match?
Python
class accountsArchive(db.Model):
# The username entity
username = db.StringProperty(required = True)
password = db.TextProperty(required = True)
email = db.StringProperty(required = True)
dateJoined = db.DateTimeProperty(auto_now_add = True)
class loginPage(Handler):
def post(self):
# The username variable
username = self.request.get("username")
password = self.request.get("password")
# The query
user = db.GqlQuery("SELECT * FROM accountsArchive WHERE
user.username = :name", name=username)
# This is how I tried to check if the two usernames matched
if username == user.username:
# Do stuff
You have a number of problems in your code.
Firstly
user = db.GqlQuery("SELECT * FROM accountsArchive WHERE
user.username = :name", name=username)
Is incorrect - you should go back and reread the docs https://cloud.google.com/appengine/docs/python/datastore/gqlreference?hl=en
This query should be
user = db.GqlQuery("SELECT * FROM accountsArchive WHERE
username = :name", name=username)
Next.
The result of this line of code is an instance of GqlQuery class not a user or as you might expect a list of users. See https://cloud.google.com/appengine/docs/python/datastore/gqlqueryclass?hl=en
You now have to fetch the results and/or iterate through them.
For instance
for u in user.run():
if u.username == username:
# then do something
However you have a problem. There is nothing in this that would limit the system a single unique user. So if you get more than one user with the same username what will you do.
Some comments.
You could use the username as the key of the accountsArchive which means you just use a get rather than a query.
Secondly if you are new to appengine and don't have an existing base of code, start out using ndb instead.

How can I assigned roles automatically in webmatrix

I want to assigned new registered users automatically the role of Member in Database.
WebMatrix sample Starter Site app - Account\Register.cshtml
Tested and it works.
// 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);
//Roles have already been added to webpages_Roles table
//Logic to determine role for e-mail (user) being added for the first time
if (email == "John#gmail.com") {
var userName=email;
var roleName="Administrator";
Roles.AddUserToRole(userName, roleName);
}
else if (email == "Greg#gmail.com") {
var userName=email;
var roleName="Guest";
Roles.AddUserToRole(userName, roleName);
}
else {
//All others are assigned the role of Member
var username=email;
var roleName="Member";
Roles.AddUserToRole(userName, roleName);
}
In your register code, which in the sample WebMatrix app is found in the file Account\Register.cshtml, there's if statements that first determine that the information being submitted is valid and then that the email doesn't exist in your database. Within those if statements, if the user is successfully created, then you can add code like:
// boy, is this a hack, Member = RoleID 8
db.Execute("INSERT INTO webpages_UsersInRoles (UserId, RoleID) VALUES( #0, 8 )", UserID);
Now I used 8 as an example. Look in your webpages_Roles table. This has a list of RoleNames and their RoleID. If you've already created the Member role, it will be in this table. Use the corresponding RoleID instead of the 8 that I used.

Can't get all rows from a query result using TideSDK API

I'm new to TideSDK so I am doing some tests. I found that the API has some methods to manage and retrieve data stored in a local DB. I created a table named Users with only two fields, id and name (This is the example at http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Database.DB), which I have fill with some random numbers and names. This is the function I am using:
function consulta (){
//Open the database first
var db = Ti.Database.openFile(Ti.Filesystem.getFile(
Ti.Filesystem.getApplicationDataDirectory(), 'customdatabase.db'));
var rows = db.execute("SELECT * FROM Users ORDER BY firstName");
while (rows.isValidRow()) {
document.getElementById('resultado').innerHTML = 'The user id is '+rows.fieldByName('id')+', and user name is '+rows.fieldByName('firstName')+'<br>';
rows.next();
}
document.getElementById('filas').innerHTML = rows.rowCount( );
//Release memory once you are done with the resultset and the database
rows.close();
db.close();
}**
My problem is this: Though the result of method rowCounts() is 29 (Meaning, of course, that there are 29 rows in the result), the WHILE block is just out puting one single row instead. Can someone help me to make this work? Shouldn't I use the API for this?
Checkout Sample API Usage for Database module here.
Try this:
while (rows.isValidRow()) {
document.write('The user id is '+rows.fieldByName('id')+', and user name is '+rows.fieldByName('firstName')+'<br >'); rows.next(); } document.getElementById('filas').in nerHTML = rows.rowCount( ); //Release memory once you are done with the resultset and the database rows.close(); db.close(); }
Place the script inside the body

Resources