Rectangle 27 31

  • In order for this to be synchronous, the currently executing script would have to wait for the user to provide input, and then continue.
  • While there is a currently executing script, the user is unable to interact with the UI. In fact, the UI doesn't even update until after the script is done executing.
  • If the script can't continue until the user provides input, and the user can't provide input until the script is finished, the closest you'll ever get is a hung browser.

To illustrate this behavior, debug your code and set a break point on the line following a line that changes the UI:

$("body").css("backgroundColor", "red");
var x = 1;  // break on this line

Notice that your page background is not yet red. It won't change to red until you resume execution and the script finishes executing. You are also unable to click any links in your page while you've got script execution paused with your debugger.

There is an exception to this rule for alert() and confirm(). These are browser controls, and are treated differently than actual web page UI elements.

The good news is that it really shouldn't be very hard to convert your code. Presumably, your code currently looks something like this:

if (confirm("continue?")) {
    // several lines of code if yes
}
else {
    // several lines of code if no
}
// several lines of code finally

Your asynchronous version could create a function ifConfirm(text, yesFn, noFn, finallyFn) and your code would look very much the same:

ifConfirm("continue?", function () {
    // several lines of code if yes
},
function () {
    // several lines of code if no
},
function () {
    // several lines of code finally 
});

Edit: In response to the additional example you added to your question, unfortunately that code will need to be refactored. It is simply not possible to have synchronous custom confirmation dialogs. To use a custom confirmation dialog in the scenario where an event needs to either continue or cancel, you'll just have to always cancel the event and mimic the event in the yesFn callback.

$("a[href]").click(function (e) {
    e.preventDefault();
    var link = this.href;
    ifConfirm("Are you sure you want to leave this awesome page?", function () {
        location.href = link;
    });
});

Or, a form:

$("form").submit(function (e) {
    e.preventDefault();
    var form = this;
    ifConfirm("Are you sure you're ready to submit this form?", function () {
        form.submit();
    });
});

Nice! Exactly what I did in the end, too :D

javascript - Change the asynchronous jQuery Dialog to be synchronous? ...

javascript jquery asynchronous dialog synchronous
Rectangle 27 20

Normally it's not necessary to reset the passwords, one can just wait until the user logs in the next time.

  • First try to verify the entered password with the new algorithm. New passwords and already converted passwords will not take longer for verification then.
  • If it does not match, compare it with the old hash algorithm.
  • Should the old hash value match, then you can calculate and store the new hash, since you know the password then.

Every password-storing-system must have the option to switch to a better hash algorithm, your problem is not a one-time migration problem. Good password hash algorithms like BCrypt have a cost factor, from time to time you have to increase this cost factor (because of faster hardware), then you need the exact same procedure as you need for the migration.

Your option 2 with hashing the old hash is a good thing, if your first algorithm is really weak, and you want to give more protection immediately. In this case you can calculate a double-hash and replace the old hash in the database with the new double-hash.

$newHashToStoreInTheDb = new_hash($oldHashFromDb)

You should also mark this password-hash (see why), so you can recognize it as double-hash. This can be done in a separate database field, or you can include your own signature. Modern password hash functions also include a signature of the algorithm, so that they can upgrade to newer algorithms, and still can verify older hashes. The example shows the signature of a BCrypt hash:

$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
___
 |
 signature of hash-algorithm = 2y = BCrypt

The verification would run like this:

  • If it is a new hash, call the new hash-function to verify the entered password, and you are done.
  • If it is a double-hash, compare it with the double-hash algorithm new_hash(old_hash($password)).
  • Should the double-hash value match, then you can calculate and store the new hash.

In my opinion, double hashing is a horrible idea. One of the reasons that you hash a password, is that if if your hash is leaked, they can still not authenticate as a user. If you do new_hash($raw_password) first, a user could log in by just entering the old leaked hash into the password field. Defeating the purpose of moving to a secure hashing algorithm.

@Lemon - Of course the old password-hash in the database would be replaced with the double hash, but you are right, that this is not the optimal solution. I edited the answer to show the best-practise, it still uses double-hashing, but marks the old hash.

security - Moving old passwords to new hashing algorithm? - Stack Over...

security passwords
Rectangle 27 451

By configuring git config core.editor notepad, users can now use notepad.exe as their default editor. Configuring git config format.commitMessageColumns 72 will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.

dscho

And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor opens to a hidden window or somewhere obscure and the user gets lost.

larsxschneider
gitster

When a graphical GIT_EDITOR is spawned by a Git command that opens and waits for user input (e.g. "git rebase -i"), then the editor window might be obscured by other windows. The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging.

Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line

git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"
C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.
"c:\Program Files\Notepad++\notepad++.exe" %*
C:\prog\git>git config --global core.editor C:\prog\git\npp.bat

It just works from the DOS session, but not from the git shell. (not that with the core.editor configuration mechanism, a script with "start /WAIT..." in it would not work, but only open a new DOS window)

Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes:

Or if you are in a 64 bit system:

git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config.

what you refer to in the config file is actually a shell (/bin/sh) script

So what does work is:

C:\prog\git>git config --global core.editor C:/prog/git/npp.bat
C:/prog/git/npp.bat
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"

With that setting, I can do 'git config --global --edit' from DOS or Git Shell, or I can do 'git rebase -i ...' from DOS or Git Shell. Bot commands will trigger a new instance of notepad++ (hence the -multiInst' option), and wait for that instance to be closed before going on.

Note that I use only '/', not \'. And I installed msysgit using option 2. (Add the git\bin directory to the PATH environment variable, but without overriding some built-in windows tools)

The fact that the notepad++ wrapper is called .bat is not important. It would be better to name it 'npp.sh' and to put it in the [git]\cmd directory though (or in any directory referenced by your PATH environment variable).

For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "Aborting commit due to empty message": change your .bat or .sh file to say:

"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>.

That will tell notepad++ to open the temp commit file, rather than a blank new one.

In your shell script, you need double quotes around $*, otherwise it won't work properly for paths with spaces in them. Thanks for the thorough explanation - I'm installing git (and a bunch of other stuff) on Windows for beginning programmers, and the command line is hard enough to grok without making them learn vi commands.

Following Bennett's answer you do not need to create a script, you can just use an apostrophe ' inside the quotes ".

@NateGlenn Use the shortened dir /X equivalent: "PROGRA~2" for "Program Files (x86)", which is a good habit to get into when using cross-platform compatible tools on Windows, which allows you to squash the whitespace.

How can I set up an editor to work with Git on Windows? - Stack Overfl...

windows git cygwin editor
Rectangle 27 29

Trailmax got most of it right, but as the comments pointed out, the user would be essentially stranded if they were to mess up their new email address when updating.

1. Modify your User object First, let's update the Application User to add the additional field we'll need. You'll add this in the IdentiyModel.cs file in your Models folder:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    [MaxLength(256)]
    public string UnConfirmedEmail { get; set; }//this is what we add

}

Also, it doesn't mention it in the linked article, but you'll want to update your AspNetUsers table as well:

ALTER TABLE dbo.AspNetUsers
ADD [UnConfirmedEmail] NVARCHAR(256) NULL;

Now we need to make sure our login is checking the old email confirmation as well so that things can be "in limbo" while we wait for the user to confirm this new email:

//
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var allowPassOnEmailVerfication = false;
        var user = await UserManager.FindByEmailAsync(model.Email);
        if (user != null)
        {
            if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
            {
                allowPassOnEmailVerfication = true;
            }
        }


        // This now counts login failures towards account lockout
        // To enable password failures to trigger account lockout, I changed to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return allowPassOnEmailVerfication ? RedirectToLocal(returnUrl) : RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

That's it...you are essentially done! However, I always get annoyed by half answers that don't walk you past potential traps you'll hit later on, so let's continue our adventure, shall we?

In our index.cshtml, let's add a new section for email. Before we get there though, let's go add the field we need in ManageViewmodel.cs

public class IndexViewModel
{
    public bool HasPassword { get; set; }
    public IList<UserLoginInfo> Logins { get; set; }
    public string PhoneNumber { get; set; }
    public bool TwoFactor { get; set; }
    public bool BrowserRemembered { get; set; }

    public string ConfirmedEmail { get; set; } //add this
    public string UnConfirmedEmail { get; set; } //and this
}

Jump into the index action in our Manage controller to add that to our viewmodel:

var userId = User.Identity.GetUserId();
        var currentUser = await UserManager.FindByIdAsync(userId);

        var unConfirmedEmail = "";
        if (!String.IsNullOrWhiteSpace(currentUser.UnConfirmedEmail))
        {
            unConfirmedEmail = currentUser.UnConfirmedEmail;
        }
        var model = new IndexViewModel
        {
            HasPassword = HasPassword(),
            PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
            TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
            Logins = await UserManager.GetLoginsAsync(userId),
            BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
            ConfirmedEmail = currentUser.Email,
            UnConfirmedEmail = unConfirmedEmail
        };

Finally for this section we can update our index to allow us to manage this new email option:

<dt>Email:</dt>
    <dd>
        @Model.ConfirmedEmail
        @if (!String.IsNullOrWhiteSpace(Model.UnConfirmedEmail))
        {
            <em> - Unconfirmed: @Model.UnConfirmedEmail </em> @Html.ActionLink("Cancel", "CancelUnconfirmedEmail",new {email=Model.ConfirmedEmail})
        }
        else
        {
            @Html.ActionLink("Change Email", "ChangeEmail")
        }
    </dd>
public class ChangeEmailViewModel
{
    public string ConfirmedEmail { get; set; } 
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string UnConfirmedEmail { get; set; } 
}
public ActionResult ChangeEmail()
    {
        var user = UserManager.FindById(User.Identity.GetUserId());
        var model = new ChangeEmailViewModel()
        {
            ConfirmedEmail = user.Email
        };

        return View(model);
    }
@model ProjectName.Models.ChangeEmailViewModel
@{
ViewBag.Title = "Change Email";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>New Email Address:</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    @Html.HiddenFor(m=>m.ConfirmedEmail)
    <div class="form-group">
        @Html.LabelFor(m => m.UnConfirmedEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UnConfirmedEmail, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Email Link" />
        </div>
    </div>
}
[HttpPost]
    public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction("ChangeEmail", "Manage");
        }

        var user = await UserManager.FindByEmailAsync(model.ConfirmedEmail);
        var userId = user.Id;
        if (user != null)
        {
            //doing a quick swap so we can send the appropriate confirmation email
            user.UnConfirmedEmail = user.Email;
            user.Email = model.UnConfirmedEmail;
            user.EmailConfirmed = false;
            var result = await UserManager.UpdateAsync(user);

            if (result.Succeeded)
            {

                string callbackUrl =
                await SendEmailConfirmationTokenAsync(userId, "Confirm your new email");

                var tempUnconfirmed = user.Email;
                user.Email = user.UnConfirmedEmail;
                user.UnConfirmedEmail = tempUnconfirmed;
                result = await UserManager.UpdateAsync(user);

                callbackUrl = await SendEmailConfirmationWarningAsync(userId, "You email has been updated to: "+user.UnConfirmedEmail);


            }
        }
        return RedirectToAction("Index","Manage");
    }
private async Task<string> SendEmailConfirmationWarningAsync(string userID, string subject)
    {
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
        var callbackUrl = Url.Action("ConfirmEmail", "Account",
           new { userId = userID, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(userID, subject,
           "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

        return callbackUrl;
    }

And now finally, we can put in the cancellation of the new email address:

public async Task<ActionResult> CancelUnconfirmedEmail(string emailOrUserId)
    {
        var user = await UserManager.FindByEmailAsync(emailOrUserId);
        if (user == null)
        {
            user = await UserManager.FindByIdAsync(emailOrUserId);
            if (user != null)
            {
                user.UnConfirmedEmail = "";
                user.EmailConfirmed = true;
                var result = await UserManager.UpdateAsync(user);
            }
        }
        else
        {
            user.UnConfirmedEmail = "";
            user.EmailConfirmed = true;
            var result = await UserManager.UpdateAsync(user);
        }
        return RedirectToAction("Index", "Manage");

    }

5. Update ConfirmEmail (the very very last step)

After all this back and forth we can now confirm the new email, which means we should remove the old email at the same time.

var result = UserManager.ConfirmEmail(userId, code);
 if (result.Succeeded)
 {

     var user = UserManager.FindById(userId);
     if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
     {
         user.Email = user.UnConfirmedEmail;
         user.UserName = user.UnConfirmedEmail;
         user.UnConfirmedEmail = "";

         UserManager.Update(user);
     }
 }

we could add a claim rather than adding an additional field

This is a great complete answer and should really be the accepted one. Thanks for posting this it was very helpful.

Thanks @RichardMcKenna, I'm glad you found it helpful. I'm always conflicted between trying to keep it short...but wanting to give as much detail as someone may want.

Thanks for explaining and showing this so closely! Especially the second part. I really like this solution a lot more than the accepted one.

asp.net - .NET Identity Email/Username change - Stack Overflow

asp.net asp.net-identity
Rectangle 27 29

Trailmax got most of it right, but as the comments pointed out, the user would be essentially stranded if they were to mess up their new email address when updating.

1. Modify your User object First, let's update the Application User to add the additional field we'll need. You'll add this in the IdentiyModel.cs file in your Models folder:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    [MaxLength(256)]
    public string UnConfirmedEmail { get; set; }//this is what we add

}

Also, it doesn't mention it in the linked article, but you'll want to update your AspNetUsers table as well:

ALTER TABLE dbo.AspNetUsers
ADD [UnConfirmedEmail] NVARCHAR(256) NULL;

Now we need to make sure our login is checking the old email confirmation as well so that things can be "in limbo" while we wait for the user to confirm this new email:

//
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var allowPassOnEmailVerfication = false;
        var user = await UserManager.FindByEmailAsync(model.Email);
        if (user != null)
        {
            if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
            {
                allowPassOnEmailVerfication = true;
            }
        }


        // This now counts login failures towards account lockout
        // To enable password failures to trigger account lockout, I changed to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return allowPassOnEmailVerfication ? RedirectToLocal(returnUrl) : RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

That's it...you are essentially done! However, I always get annoyed by half answers that don't walk you past potential traps you'll hit later on, so let's continue our adventure, shall we?

In our index.cshtml, let's add a new section for email. Before we get there though, let's go add the field we need in ManageViewmodel.cs

public class IndexViewModel
{
    public bool HasPassword { get; set; }
    public IList<UserLoginInfo> Logins { get; set; }
    public string PhoneNumber { get; set; }
    public bool TwoFactor { get; set; }
    public bool BrowserRemembered { get; set; }

    public string ConfirmedEmail { get; set; } //add this
    public string UnConfirmedEmail { get; set; } //and this
}

Jump into the index action in our Manage controller to add that to our viewmodel:

var userId = User.Identity.GetUserId();
        var currentUser = await UserManager.FindByIdAsync(userId);

        var unConfirmedEmail = "";
        if (!String.IsNullOrWhiteSpace(currentUser.UnConfirmedEmail))
        {
            unConfirmedEmail = currentUser.UnConfirmedEmail;
        }
        var model = new IndexViewModel
        {
            HasPassword = HasPassword(),
            PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
            TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
            Logins = await UserManager.GetLoginsAsync(userId),
            BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),
            ConfirmedEmail = currentUser.Email,
            UnConfirmedEmail = unConfirmedEmail
        };

Finally for this section we can update our index to allow us to manage this new email option:

<dt>Email:</dt>
    <dd>
        @Model.ConfirmedEmail
        @if (!String.IsNullOrWhiteSpace(Model.UnConfirmedEmail))
        {
            <em> - Unconfirmed: @Model.UnConfirmedEmail </em> @Html.ActionLink("Cancel", "CancelUnconfirmedEmail",new {email=Model.ConfirmedEmail})
        }
        else
        {
            @Html.ActionLink("Change Email", "ChangeEmail")
        }
    </dd>
public class ChangeEmailViewModel
{
    public string ConfirmedEmail { get; set; } 
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string UnConfirmedEmail { get; set; } 
}
public ActionResult ChangeEmail()
    {
        var user = UserManager.FindById(User.Identity.GetUserId());
        var model = new ChangeEmailViewModel()
        {
            ConfirmedEmail = user.Email
        };

        return View(model);
    }
@model ProjectName.Models.ChangeEmailViewModel
@{
ViewBag.Title = "Change Email";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>New Email Address:</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    @Html.HiddenFor(m=>m.ConfirmedEmail)
    <div class="form-group">
        @Html.LabelFor(m => m.UnConfirmedEmail, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UnConfirmedEmail, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Email Link" />
        </div>
    </div>
}
[HttpPost]
    public async Task<ActionResult> ChangeEmail(ChangeEmailViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return RedirectToAction("ChangeEmail", "Manage");
        }

        var user = await UserManager.FindByEmailAsync(model.ConfirmedEmail);
        var userId = user.Id;
        if (user != null)
        {
            //doing a quick swap so we can send the appropriate confirmation email
            user.UnConfirmedEmail = user.Email;
            user.Email = model.UnConfirmedEmail;
            user.EmailConfirmed = false;
            var result = await UserManager.UpdateAsync(user);

            if (result.Succeeded)
            {

                string callbackUrl =
                await SendEmailConfirmationTokenAsync(userId, "Confirm your new email");

                var tempUnconfirmed = user.Email;
                user.Email = user.UnConfirmedEmail;
                user.UnConfirmedEmail = tempUnconfirmed;
                result = await UserManager.UpdateAsync(user);

                callbackUrl = await SendEmailConfirmationWarningAsync(userId, "You email has been updated to: "+user.UnConfirmedEmail);


            }
        }
        return RedirectToAction("Index","Manage");
    }
private async Task<string> SendEmailConfirmationWarningAsync(string userID, string subject)
    {
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
        var callbackUrl = Url.Action("ConfirmEmail", "Account",
           new { userId = userID, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(userID, subject,
           "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

        return callbackUrl;
    }

And now finally, we can put in the cancellation of the new email address:

public async Task<ActionResult> CancelUnconfirmedEmail(string emailOrUserId)
    {
        var user = await UserManager.FindByEmailAsync(emailOrUserId);
        if (user == null)
        {
            user = await UserManager.FindByIdAsync(emailOrUserId);
            if (user != null)
            {
                user.UnConfirmedEmail = "";
                user.EmailConfirmed = true;
                var result = await UserManager.UpdateAsync(user);
            }
        }
        else
        {
            user.UnConfirmedEmail = "";
            user.EmailConfirmed = true;
            var result = await UserManager.UpdateAsync(user);
        }
        return RedirectToAction("Index", "Manage");

    }

5. Update ConfirmEmail (the very very last step)

After all this back and forth we can now confirm the new email, which means we should remove the old email at the same time.

var result = UserManager.ConfirmEmail(userId, code);
 if (result.Succeeded)
 {

     var user = UserManager.FindById(userId);
     if (!string.IsNullOrWhiteSpace(user.UnConfirmedEmail))
     {
         user.Email = user.UnConfirmedEmail;
         user.UserName = user.UnConfirmedEmail;
         user.UnConfirmedEmail = "";

         UserManager.Update(user);
     }
 }

we could add a claim rather than adding an additional field

This is a great complete answer and should really be the accepted one. Thanks for posting this it was very helpful.

Thanks @RichardMcKenna, I'm glad you found it helpful. I'm always conflicted between trying to keep it short...but wanting to give as much detail as someone may want.

Thanks for explaining and showing this so closely! Especially the second part. I really like this solution a lot more than the accepted one.

asp.net - .NET Identity Email/Username change - Stack Overflow

asp.net asp.net-identity
Rectangle 27 8

Since the callback is asynchronous (at least, in the sense that it's waiting on the user to do something), it might be easier to handle what you need to inside the callback:

function confirm() {
    jConfirm('are you sure?', 'Confirmation Dialog', function(r) {
        if (r) doSomething();
    });
}

The point I'm trying to make is that there isn't really an easy way to accomplish what you want. You're trying to correlate procedural and event-driven programming -- something JavaScript doesn't help you do.

function confirm() {
    var result = false;
    var response = false;

    jConfirm('are you sure?', 'Confirmation Dialog',
      function(r) {
        result = r;
        response = true;
    });

    while(!response) continue; // wait
    return result;
}

Thanks for the response, but I need the function to return the result from the callback function. So if the user clicks ok -> return true, if the user clicks cancel -> return false. Then this will work just like the built in confirm function.

Thanks, I actually tried the while loop to test that solution, but IE will throw an alert dialog saying javascript is hanging. You're right I wouldn't want to do that. I'll wait to hear from the authors and post the solution. Maybe they hadn't finished it themselves.

The infinite loop won't work. JavaScript is single-threaded; jQuery's confirm UI cannot even be interacted with whilst the while loop is spinning.

jquery - Can you wait for javascript callback? - Stack Overflow

javascript jquery dialog callback confirm
Rectangle 27 513

There's a few ways to do it.

@2rs2ts: "Prompting" is the text. It "prompts" the user to do something. Actually waiting for the user to do that thing is not prompting.

How do you read from stdin in Python? - Stack Overflow

python stdin
Rectangle 27 513

There's a few ways to do it.

@2rs2ts: "Prompting" is the text. It "prompts" the user to do something. Actually waiting for the user to do that thing is not prompting.

How do you read from stdin in Python? - Stack Overflow

python stdin
Rectangle 27 510

There's a few ways to do it.

@2rs2ts: "Prompting" is the text. It "prompts" the user to do something. Actually waiting for the user to do that thing is not prompting.

How do you read from stdin in Python? - Stack Overflow

python stdin
Rectangle 27 510

There's a few ways to do it.

@2rs2ts: "Prompting" is the text. It "prompts" the user to do something. Actually waiting for the user to do that thing is not prompting.

How do you read from stdin in Python? - Stack Overflow

python stdin
Rectangle 27 14

You need to initialize the motion manager and then check motion.userAcceleration.y value for an appropriate acceleration value (measured in meters / second / second).

In the example below I check for 0.05 which I've found is a fairly decent forward move of the phone. I also wait until the user slows down significantly (-Y value) before drawing. Adjusting the device MotionUpdateInterval will will determine the responsiveness of your app to changes in speed. Right now it is sampling at 1/60 seconds.

motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1.0/60.0;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
    NSLog(@"Y value is: %f", motion.userAcceleration.y);
    if (motion.userAcceleration.y > 0.05) { 
        //a solid move forward starts 
        lineLength++; //increment a line length value
    } 
    if (motion.userAcceleration.y < -0.02 && lineLength > 10) {
        /*user has abruptly slowed indicating end of the move forward.
         * we also make sure we have more than 10 events 
         */
        [self drawLine]; /* writing drawLine method
                          * and quartz2d path code is left to the 
                          * op or others  */
        [motionManager stopDeviceMotionUpdates];
    }
}];

Note this code assumes that the phone is lying flat or slightly tilted and that the user is pushing forward (away from themselves, or moving with phone) in portrait mode.

Does doesn't work in Background. To Track the users location on the Go, we've to making it background enabled. Is there any way we can achieve that?

@MohammadAbdurraafay Instead of asking a question in the comments, you should ask a new question to get answers, help, etc.

This code crashes because of issues with the NSOperationQueue. See my answer here for the correct way to setup an NSOperationQueue. Also, @JohnFontaine, please make the appropriate changes to your answer.

objective c - iOS detect movement of user - Stack Overflow

objective-c ios core-motion uiaccelerometer
Rectangle 27 2

The answer to that lies purely in User Experience (UX) domain. Android devices are usually personal devices and you should put that in mind while coding your app.

Users are maybe playing a game or making a phone call, launching your activity without any notification is rude and I would uninstall any app that would do that.

Also if the phone is locked your activity will not actually launch instead it will wait until the user unlocks the phone.

Notifications on the other hand are made to tell the user that the app wants to show you something. So use them instead.

Unless you are building a private app then you know what is better for your requirements.

I would be more specific about the app: it is meant to call and open a gate whenever I drive towards it, using GPS location. I (and everyone else installing this app) expect and except this rude behavior when the phone automatically opens the gate for me, even if it is in the middle of another call (the new call won't be more the 5 sec), or when someone in the back seat is playing a game, because that is exactly what it is meant for.

By the way, I would love to hear if you have a solution for the problem you brought up (and which I am going to ask about separately) - How is it possible to keep the service receiving notifications and starting the call activity when the screen is locked.

I'm not sure if that is possible via public APIs you may look for hacks for that

service - Android - calling startActivity() from LocationListener.onLo...

android service start-activity
Rectangle 27 10

Basically, what firefox does is this:

When you use alert here it blocks and all bets are off - the page has frozen, execution halted and things are at "platform level".

It might be considered a bug, and it's certainly not what I would expect - but at the core this is about the incompatibility between alert and JavaScript task/microtask semantics.

If you change that alert to a console.log or appending to document.innerHTML you'd get the result you expect.

var alert = function(arg) { // no longer a magical and blocking operation
  document.body.innerHTML += "<br/>" + arg;
}

// this code outputs "First, Second, Third" in all the browsers.

setTimeout(alert.bind(null, "Third"), 0);

var p = Promise.resolve("Second");
p.then(alert);

alert("First");

Optionally, pause while waiting for the user to acknowledge the message.

  • Execute until it encounters the first alert.
  • Run any microtasks to completion before pausing (tasks are paused, and not microtasks).
  • The then is run as a microtask, so "Second" gets queued and precedes the alert.
Second
First

Confusing, but allowed from what I can tell.

I don't get it - you seem to be right. But I just created the minimal example with alert because we found this behavior in code that does not use alerts at all... I will try to create a better minimal example. If I do not manage to create a minimal example or find the problem elsewhere, I will mark this as the correct answer.

@sirion this isn't about alert in particular, this is about running all microtasks to completion when pausing the event loop until a task completes. There are other cases that can trigger it (like synchronous ajax for example).

Synchronous ajax is a good hint - I think I saw that somewhere in the surrounding code.

I suspect this introduced it: bugzilla.mozilla.org/show_bug.cgi?id=1094248 , the issue is discussed there and it's an interesting read.

alert (or something else) synchronously running microtasks seems to be the unexpected thing here. Technically A+ forbids processing the queue from user code (which alert() surely is), but I'm fine with any behaviour as long as the callback is executed after .then() returns. Firing the queue should be a bit more explicit though :-)

javascript - Firefox: Promise.then not called asynchronously - Stack O...

javascript firefox promise
Rectangle 27 380

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

I've got a thread that constantly updates and renders a screen object, and I call the builder.show() method within the update method of the screen object.

Oh. If you're on a worker thread, try putting the builder.show(); call with runOnUiThread, similar to this example: stackoverflow.com/a/3134720/1098302 Or maybe it would be better to put all the code above (that creates the AlertDialog) in a separate method, and call that method from within runOnUiThread.

Thank you. Thats good. Howerver, there's a little problem. Need to declare global Context, Context cont; and then, replace "this" in alertdialog by cont. AlertDialog.Builder builder = new AlertDialog.Builder(cont); final EditText input = new EditText(cont);

I think instead of creating a global variable for context, you can pass the context like: "MainActivity.this" (you need to replace the text "MainActivity" with activity class name you want to use).

Might be worth noting that, like most Android UI, this is all asynchronous... meaning it won't wait for the user to tap OK unless you have something making that the gate to the next step...

Input text dialog Android - Stack Overflow

android text input
Rectangle 27 376

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

I've got a thread that constantly updates and renders a screen object, and I call the builder.show() method within the update method of the screen object.

Oh. If you're on a worker thread, try putting the builder.show(); call with runOnUiThread, similar to this example: stackoverflow.com/a/3134720/1098302 Or maybe it would be better to put all the code above (that creates the AlertDialog) in a separate method, and call that method from within runOnUiThread.

Thank you. Thats good. Howerver, there's a little problem. Need to declare global Context, Context cont; and then, replace "this" in alertdialog by cont. AlertDialog.Builder builder = new AlertDialog.Builder(cont); final EditText input = new EditText(cont);

I think instead of creating a global variable for context, you can pass the context like: "MainActivity.this" (you need to replace the text "MainActivity" with activity class name you want to use).

Might be worth noting that, like most Android UI, this is all asynchronous... meaning it won't wait for the user to tap OK unless you have something making that the gate to the next step...

Input text dialog Android - Stack Overflow

android text input
Rectangle 27 3

Let me explain me better, I'm trying to create an API and the user only have access to the promise resolve/reject part. Now the solution I would like to give him does not work. Any ideas?

Don't put everything onto that initial promise object. It sounds what you really need to expose to your user is a) a way to resolve (which includes rejection) and b) a way to get the result (promise) back. So all you need to do is give him a function:

function createAsync() {
    var resolve;
    var promise = new Promise(function(r) { resolve = r; })
    .then(function(fun) {
        if (typeof fun != 'function')
            throw Error('You must resolve a function as argument')
    }).catch(function(err){
       // Some internal api tasks...
       throw err;
    });
    return function(value) {
        resolve(value);
        return promise;
    };
}
var start = createAsync();
// possibly later
start('This must be a function but is a string').catch(function(err){
    console.log("GOTCHA", err)
});
// or
start(Promise.reject(new Error('doomed to fail'))).catch();

but actually this pattern is still convoluted and much too complicated. Simply give your createAsync function a parameter (that might receive a promise if the user needs to delay passing the fun) and be done with it:

function createAsync(valu) {
    return Promise.resolve(val).then(function(fun) {
        if (typeof fun != 'function')
            throw Error('You must resolve a function as argument')
    }).catch(function(err){
       // Some internal api tasks...
       throw err;
    });
}
createAsync('This must be a function but is a string').catch(function(err) {
    console.log("GOTCHA", err)
});
// or
createAsync(new Promise(function(resolve) {
    // later
    resolve('This must be a function but is a string');
})).catch(function(err) {
    console.log("GOTCHA", err)
});

createAsync instance must be created internally. I can't allow to the user create the promise because I need the instance to resolve internally.

It seems you need to wait for the user to call resolve anyway, so there shouldn't be any difference? But if you absolutely have to, just use the pattern from the first two snippets.

It might help if you could share/link your real code.

First, two snippets do not allow user to reject. Real code is very complicated. The edited example is the most simple and accurate way to understand.

They do, see the last line of the second snippet.

javascript - Catch an error inside of Promise resolver - Stack Overflo...

javascript promise
Rectangle 27 2

On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using 'pick_event' callbacks) before continuing.

In order to block execution until the plot window is closed, I used the following:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

Note, however, that canvas.start_event_loop_default() produced the following warning:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

although the script still ran.

Thank you! Spyder imports -pylab at startup which is generally useful, but means show() won't block when ioff() - this allows you to fix this behaviour!

python - Is there a way to detach matplotlib plots so that the computa...

python matplotlib plot
Rectangle 27 2

On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using 'pick_event' callbacks) before continuing.

In order to block execution until the plot window is closed, I used the following:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

Note, however, that canvas.start_event_loop_default() produced the following warning:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

although the script still ran.

Thank you! Spyder imports -pylab at startup which is generally useful, but means show() won't block when ioff() - this allows you to fix this behaviour!

python - Is there a way to detach matplotlib plots so that the computa...

python matplotlib plot
Rectangle 27 63

I have often had a similar problem; Python programs I write frequently need to have the ability to execute some primary functionality while simultaneously accepting user input from the command line (stdin). Simply putting the user input handling functionality in another thread doesn't solve the problem because readline() blocks and has no timeout. If the primary functionality is complete and there is no longer any need to wait for further user input I typically want my program to exit, but it can't because readline() is still blocking in the other thread waiting for a line. A solution I have found to this problem is to make stdin a non-blocking file using the fcntl module:

import fcntl
import os
import sys

# make stdin a non-blocking file
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

# user input handling thread
while mainThreadIsRunning:
      try: input = sys.stdin.readline()
      except: continue
      handleInput(input)

In my opinion this is a bit cleaner than using the select or signal modules to solve this problem but then again it only works on UNIX...

Jesse's answer is not correct. According to Guido, readline doesn't work correctly with non-blocking mode, and it won't before Python 3000. bugs.python.org/issue1175#msg56041 If you want to use fcntl to set the file to non-blocking mode, you have to use the lower-level os.read() and separate out the lines yourself. Mixing fcntl with high-level calls that perform line buffering is asking for trouble.

The use of readline seems incorrect in Python 2. See anonnn's answer stackoverflow.com/questions/375427/

Please, don't use busy loops. Use poll() with a timeout to wait for the data.

replacing readline with read(buffer_size) seem to work perfectly...

Still helpful in 2016, thank you :D

io - Non-blocking read on a subprocess.PIPE in python - Stack Overflow

python io subprocess nonblocking
Rectangle 27 23

I would actually say that functional programming (F#) is much better tool for user interface programming than for example C#. You just need to think about the problem a little bit differently.

I discuss this topic in my functional programming book in Chapter 16, but there is a free excerpt available, which shows (IMHO) the most interesting pattern that you can use in F#. Say you want to implement drawing of rectangles (user pushes the button, moves the mouse and releases the button). In F#, you can write something like this:

let rec drawingLoop(clr, from) = async { 
   // Wait for the first MouseMove occurrence 
   let! move = Async.AwaitObservable(form.MouseMove) 
   if (move.Button &&& MouseButtons.Left) = MouseButtons.Left then 
      // Refresh the window & continue looping 
      drawRectangle(clr, from, (move.X, move.Y)) 
      return! drawingLoop(clr, from) 
   else
      // Return the end position of rectangle 
      return (move.X, move.Y) } 

let waitingLoop() = async { 
   while true do
      // Wait until the user starts drawing next rectangle
      let! down = Async.AwaitObservable(form.MouseDown) 
      let downPos = (down.X, down.Y) 
      if (down.Button &&& MouseButtons.Left) = MouseButtons.Left then 
         // Wait for the end point of the rectangle
         let! upPos = drawingLoop(Color.IndianRed, downPos) 
         do printfn "Drawn rectangle (%A, %A)" downPos upPos }

This is a very imperative approach (in the usual pragmatic F# style), but it avoids using mutable state for storing the current state of drawing and for storing inital location. It can be made even more functional though, I wrote a library that does that as part of my Master thesis, which should be available on my blog in the next couple of days.

Functional Reactive Programming is a more functional approach, but I find it somewhat harder to use as it relies on quite advanced Haskell features (such as arrows). However, it is very elegant in a large number of cases. It's limitation is that you cannot easily encode a state machine (which is a useful mental model for reactive programs). This is very easy using the F# technique above.

+1 This reflects our experience, having written several production GUIs in F# using combinator libraries and IObservable.

Has the comment on FRP changed since the introduction of reactive extensions to the .NET library?

Here's some research on Arrowized FRP and how effects and mutation can be embedded within Arrowized FRP without breaking the laws: haskell.cs.yale.edu/wp-content/uploads/2015/10/ (btw most FRP libraries use Monads or even Applicatives, so it's not correct that Arrows are required).

user interface - Is functional GUI programming possible? - Stack Overf...

user-interface haskell f# functional-programming