ASP.NET Identity AllowOnlyAlphanumericUserNames - asp.net

Can someone please help me how can i use special characters in ASP.Net identity?
The problem is that my users cannot register with special characters: č,ć,š,ž,đ.
When you try to enter this characters in registration, i get following error:
User name Krešo is invalid, can only contain letters or digits.
Where and how can i change this.
Here is the code:
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Pages_Account_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrijava_Click(object sender, EventArgs e)
{
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["SeminariConnectionString3"].ConnectionString;
UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
IdentityUser user = new IdentityUser();
user.UserName = txtKorisnickoIme.Text;
if(txtLozinka.Text == txtPotvrdaLozinke.Text)
{
try
{
IdentityResult result = manager.Create(user, txtLozinka.Text);
if(result.Succeeded)
{
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
Response.Redirect("Pocetna.aspx");
}
else
{
litStatus.Text = result.Errors.FirstOrDefault();
}
}
catch (Exception ex)
{
litStatus.Text = ex.ToString();
}
}
else
{
litStatus.Text = "Lozinke moraju biti identične.";
}
}
}

You should be able to change this behaviour as follows:
var manager = new UserManager<IdentityUser>(userStore); // existing code
var validator = manager.UserValidator as UserValidator<ApplicationUser>;
if (validator != null) validator.AllowOnlyAlphanumericUserNames = false;
Should validator turn out to be null, then debug a little to find the actual type used at runtime.

Related

Search bar by using LinQ

I want to show the results only that match the user input, but this code will show the whole table, do you know what is the problem? For example, if the user enters "233442" id it will only show him the users that their id "233442". The user could search by id, name, or username.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace SearchBarLinQ
{
public partial class SearchBarLinQ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
DataClasses1DataContext db = new DataClasses1DataContext();
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData();
}
void LoadData()
{
var st = from s in db.SearchTable2s select s;
GridView1.DataSource = st;
GridView1.DataBind();
}
}
}
Function btnsearch_Click is processing the search, but the value you found is not displayed. You need to assign the value found to the data source of girdview.
Refer to the sample code(Customize the param object of the LoadData function to be compatible with the view):
protected void btnsearch_Click(object sender, EventArgs e)
{
var st = (from s in db.SearchTable2s where s.ID == int.Parse(TxtID.Text) select s).First();
TxtName.Text = st.Name;
TxtUsername.Text = st.Username;
LoadData(st);
}
void LoadData(object param)
{
GridView1.DataSource = param;
GridView1.DataBind();
}

cross site request forgery - in .net using web forms in vs2013

With the auto generated code for VS 2013 for web forms, it adds CSRF protection. Do I need to do anything else to get it to work?
It says the token is added to Page.ViewStateUserKey. How am I suppose to check the ViewState? The debugger says it's null.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication12
{
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I downloaded Asp.net ViewState Helper. And because I was using 4.5 framework uses a different cyprtoscheme, I had to edit the web.config.
I added this:
<system.web>
<machineKey compatibilityMode="Framework20SP1" />
</system.web>
Then I was able use Fiddler and decrypt the View State and confirmed that the XSRF token is added.

Consuming pipl api in asp.net

i am having trouble configuring this API
https://pipl.com/dev/
i have this code in page load event, but the problem is that it keep on loading the page once i click on "veiw page in browser".
protected void Page_Load(object sender, EventArgs e)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
SearchAPIRequest req = new SearchAPIRequest(email: "clark.kent#example.com");
SearchAPIResponse resp = await req.SendAsync();
Console.Out.WriteLine(resp.Image.GetThumbnailUrl(200, 100, true, true));
Console.Out.WriteLine(resp.Name);
Console.Out.WriteLine(resp.Education);
Console.Out.WriteLine(resp.Username);
Console.Out.WriteLine(resp.Address);
var jobs = resp.Person.Jobs.Select(j => j.ToString());
Console.Out.WriteLine(String.Join(", ", jobs));
Console.Out.WriteLine();
var relationships = resp.Person.Relationships.Select(r => r.Names[0]);
Console.Out.WriteLine(String.Join(", ", relationships));
Console.Out.WriteLine();
}
Am i missing some code ? or any thing else.. please guide.
PS: I have already installed their package with "PM> Install-Package piplclient"
The ASPX page needs to have "Async=true" in order to use an async method. The following is an example backend C# file:
using Pipl.APIs.Search;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : Page
{
protected async void Page_Load(object sender, EventArgs e)
{
SearchAPIRequest request = new SearchAPIRequest(email: "clark.kent#example.com");
try
{
var response = await request.SendAsync();
Response.Write(response.Name.ToString());
}
catch (SearchAPIError ex)
{
Console.Out.WriteLine(e.ToString());
}
catch (IOException ex)
{
Console.Out.WriteLine(e.ToString());
}
}
}
}

asp.net - object reference not set to an instance of an object for master page cs file

This is the code to my Master Page cs file. For some reason when I run my default page, I get an error that says "object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Theming.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string selectedTheme = Page.Theme;
HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
if (preferredTheme != null)
{
selectedTheme = preferredTheme.Value;
}
if (!string.IsNullOrEmpty(selectedTheme))
{
ListItem item = ThemeList.Items.FindByValue(selectedTheme);
if (item != null)
{
item.Selected = true;
}
}
}
switch (Page.Theme.ToLower())
{
case "darkgrey":
Menu1.Visible = false;
TreeView1.Visible = true;
break;
default:
Menu1.Visible = true;
TreeView1.Visible = false;
break;
}
}
protected void ThemeList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie preferredTheme = new HttpCookie("PreferredTheme");
preferredTheme.Expires = DateTime.Now.AddMonths(3);
preferredTheme.Value = ThemeList.SelectedValue;
Response.Cookies.Add(preferredTheme);
Response.Redirect(Request.Url.ToString());
}
}
}
The error appears to be at the switch statement but I can't figure out why. I've read on other posts that the value is assigning to the variable as null but I don't know why; I've got dark grey as an app theme. If anyone could please help me it would be very much appreciated.
I don't see Menu1 or TreeView1 defined anywhere in your markup. If those are in a content page, you can't access those in the MasterPage code-behind (there may be a way, but you can't directly access them the way you're trying to).

System.FormatException: Input string was not in a correct format

In the following code, when I try to add an Item to an ASP DropDownList, System.FormatException: Input string was not in a correct format, is thrown.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class ScheduleExam : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String connection = System.Configuration.ConfigurationManager.ConnectionStrings["TYCConnection"].ConnectionString;
String branch = Request.Form["ctl00$ctl00$MainContent$AdminMainContent$BranchDropDownList"];
if (!String.IsNullOrWhiteSpace(branch))
{
if (!branch.Equals("00"))
{
SqlConnection sqlConn = new SqlConnection(connection);
String semQuery = "select totalSem from branchTable where branchId='" + branch + "'";
SqlCommand semCommand = new SqlCommand(semQuery, sqlConn);
sqlConn.Open();
SqlDataReader semReader = semCommand.ExecuteReader();
semReader.Read();
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = true;
//ListItem list = new ListItem("Select");
SemesterDropDownList.Items.Add(new ListItem("select"));
for (int sem = 1; sem <= totalSem; sem++)
{
//SemesterDropDownList.Items.Add(sem.ToString());
}
sqlConn.Close();
}
else
{
SemesterDropDownList.Items.Clear();
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
else
{
SemesterDropDownList.Enabled = false;
//SemesterDropDownList.Items.Add("First Select Branch");
}
}
protected void RegisterButton_Click(object sender, EventArgs e)
{
}
}
However, when I comment all such lines there is no exception thrown.
What could be the problem and its possible solution?
Instead of
int totalSem = Int32.Parse(semReader["totalSem"].ToString());
try
int totalSem;
Int32.TryParse(semReader["totalSem"].ToString(),totalSem);
and if that takes care of the exception then look into addressing the issues with that field.

Resources