|
That entirely depends on how you bind it to the data source. Are you using a data source control and setting the DataSourceID ? Are you setting the DataSource property in code and then calling DataBind ? Or are you adding the items manually through code on the server?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm working on Blazor server App project. I have the following codes for CustomAuthenticationStateProvider:
CustomAuthenticationStateProvider.cs
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ProtectedSessionStorage _sessionStorage;
private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
public CustomAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var userSessionStorageResult = await _sessionStorage.GetAsync<UserSession>("UserSession");
var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null;
if (userSession == null)
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim> {
new Claim(ClaimTypes.Name, userSession.Username),
new Claim(ClaimTypes.Role, userSession.UserRole),
new Claim(ClaimTypes.NameIdentifier, userSession.UserId.ToString())
}, "Jwt"));
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
catch (Exception)
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
}
public async Task UpdateAuthenticationState(UserSession userSession)
{
ClaimsPrincipal claimsPrincipal;
if (userSession != null)
{
await _sessionStorage.SetAsync("UserSession", userSession);
await _sessionStorage.SetAsync("Token", userSession.TokenText);
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name, userSession.Username),
new Claim(ClaimTypes.Role, userSession.UserRole),
new Claim(ClaimTypes.NameIdentifier, userSession.UserId.ToString())
}));
}
else
{
await _sessionStorage.DeleteAsync("UserSession");
claimsPrincipal = _anonymous;
}
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
}
UserSession.cs
public class UserSession
{
public int UserId { get; set; }
public string Username { get; set; }
public string UserRole { get; set; }
public string Name { get; set; }
public string TokenText { get; set; }
}
LoginController:
[Route("api/[controller]/[action]")]
[ApiController]
public class ApiLoginController : ControllerBase
{
private readonly SqliteContext _sqlServerContext;
private readonly IConfiguration _configuration;
private readonly IUserService _userService;
public ApiLoginController(SqliteContext sqlServerContext, IConfiguration configuration, IUserService userService)
{
_sqlServerContext = sqlServerContext;
_configuration = configuration;
_userService = userService;
}
[HttpPost]
public async Task<IActionResult> LoginSystem([FromBody] UserLoginVM loginModel)
{
var user = await _sqlServerContext.Users.Include(x => x.RoleRefNavigation)
.FirstOrDefaultAsync(x => x.Username == loginModel.Username && x.IsActive);
if (user == null)
{
return BadRequest("Invalid credentials.");
}
if (!MatchPasswordHash(loginModel.Password, user.Password, user.SaltPassword))
{
return BadRequest("Invalid credentials.");
}
if (!user.IsActive)
{
return StatusCode(403, "User is not active.");
}
if (user.IsLocked)
{
DateTime setDate = (DateTime)user.LockUntil;
DateTime current = DateTime.Now;
if (setDate > current)
{
return StatusCode(403, "User is restricted.");
}
await _userService.UnsetUserLimits(user.UserId);
}
user.RoleRefNavigation = await _sqlServerContext.Roles.FirstOrDefaultAsync(x => x.RoleId == user.RoleRef);
string token = CreateToken(user);
var data = new
{
tokenText = token,
username = user.Username,
userId = user.UserId.ToString(),
name = user.Name,
role = user.RoleRefNavigation.User_Role
};
await _userService.RegisterLoginTime(user.UserId);
return Ok(data);
}
private string CreateToken(User user)
{
List<Claim> claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, user.Username),
new Claim(ClaimTypes.Role, user.RoleRefNavigation.User_Role),
new Claim(type: "UserId", value: user.UserId.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("Jwt:Key").Value!));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var token = new JwtSecurityToken(
claims: claims,
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Issuer"],
expires: DateTime.Now.AddHours(8),
signingCredentials: creds
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
private bool MatchPasswordHash(string passwordText, byte[] password, byte[] passwordKey)
{
using (var hmac = new HMACSHA512(passwordKey))
{
var passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(passwordText));
for (int i = 0; i < passwordHash.Length; i++)
{
if (passwordHash[i] != password[i])
{
return false;
}
}
return true;
}
}
}
The problem is that when I check Context.User?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; in SignalR hub, Context.UserIdentifier is always null. How can I fix this?
modified 21-Jul-23 9:51am.
|
|
|
|
|
Quote:
private bool MatchPasswordHash(string passwordText, byte[] password, byte[] passwordKey)
{
using (var hmac = new HMACSHA512(passwordKey))
{
var passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(passwordText));
for (int i = 0; i < passwordHash.Length; i++)
{
if (passwordHash[i] != password[i])
{
return false;
}
}
return true;
}
} Not an answer to your question, but that code is potentially vulnerable to a timing attack[^].
Although the salt may render it harder for an attacker to exploit, it would be better to avoid the early return - you always want this function to compare the full length of the arrays, not just the first n bytes.
bool areEqual = true;
for (int i = 0; i < passwordHash.Length; i++)
{
if (passwordHash[i] != password[i])
{
areEqual = false;
}
}
return areEqual;
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I have an excel file with five (5) columns.
All the records in the second column are hyperlinked.
When I tried importing the file to SQL Server, the hyperlinks are gone.
I have spent almost 4 days googling to see if there is a way to do import this excel file with hyperlink either to a SQL Server DB or asp.net application but to no avail.
Wondering if any of you experts has an idea how to do solve this problem?
Many thanks in advance.
|
|
|
|
|
Without seeing your code it is impossible to guess what may be the problem.
|
|
|
|
|
There is no code sir.
I am just asking about importing excel with hyperlinks to sql server or asp.net applications.
|
|
|
|
|
Well you need to explain exactly how you are doing it and what actually happens when you do. We cannot be expected to guess what is going on.
|
|
|
|
|
LOL,
The only way I have done import from excel to SQL Server is to use the SQL Server import utility.
It always works. If you have imported files before to sql server, then nothing to guess there.
The only issue this time around is that when I imported the file, the hyperlinks on the values for one of the columns was removed.
Normally, this is not an issue for anyone who has encountered this type of problem.
All I have asked for is whether anyone has had similar issue and if yes, how did they resolved it.
Nothing really complicated about my question.
If I Have a code and I am having problem making it work, I post the code and ask for help which I have done many times here.
|
|
|
|
|
samflex wrote: The only way I have done import from excel to SQL Server is to use the SQL Server import utility. Which you omitted to mention in your original question, leaving us in the dark as to how you were doing it.
samflex wrote: nothing to guess there. Actually everything to guess.
samflex wrote: Nothing really complicated about my question. That's a matter of opinion.
Did you check Import data from Excel to SQL Server or Azure SQL Database - SQL Server | Microsoft Learn[^] ?
|
|
|
|
|
Sounds like someone who knows what the BCP Utility is because they use it regularly in their procedural code should be able to tell you why using various commandline options does what they're supposed to do ... or doesn't do what they're supposed to do.
I think the direct object of that sentence is "using" ... so yeah, does/doesn't ...
modified 18-Jul-23 14:25pm.
|
|
|
|
|
|
Hyperlinks are a feature of Excel. They are not a data type.
You can't store an Excel hyperlink in a database column. You can store the target address of a hyperlink, but not a hyperlink.
Is it the target address of the hyperlink that you are looking to store?
And what does show up in the SQL table when you import the file?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Hi,
I suppose that when you say target address of a hyperlink, you meant the location you are taking when you click on a hyperlink?
Here is what we are trying to accomplish.
We have directory on our server where several documents are stored.
Then the excel file contains hyperlinks to those documents.
For instance, one of the columns, called Director for example, the Director is hyperlinked Director.
On the excel file, it is clearly hyperlinked and when clicked, takes you to the Files directory and Director file.
There are over 600 of these records on excel.
What we are trying to do is import the contents of the excel file to the database then use our .net app to display these records on our site so users can visit the site search for any title info, find it, cick the hyperlink to take him/her to the file on the server.
So, after importing the file to the database, all you see now is the text Director. The hyperlink is stripped away.
|
|
|
|
|
Hi guys
I am writing a tool for meeting management in my organization so I use ews managed api to call the exchange server
What I need to do is showing the ad user emails just like when you press to button in the outlook
Anyone can help me with this
Help people,so poeple can help you.
|
|
|
|
|
Hallo
I have about 100 asp.net forms. I have a master page and many pages that refer to the master. The .aspx pages differ, but the .aspx.vb codebehind of all is essentially identical. The .aspx_vb has some parameter declarations and constants at the top, but the remainder of the .aspx_vb is identical generalised code - handling events like page_init, page_load etc.
Obviously this is inefficient to maintain.
Can someone offer advice of what techniques I should investigate to be able to centralise the common code into one code base and maintain it once.
I have written extensions to existing controls previously - for example I have written extensions that inherit GridView and DropDownList. I also use User Controls extensively.
Can someone point me to examples or articles to assist me solve this problem?
thanks, Grant
|
|
|
|
|
You can use Classes that are essential in object-oriented programming. These will have functions that you can call to in any of your pages. I found numerous tutorials by searching writing and using classes in aspx[^]
|
|
|
|
|
|
|
The "easiest" way (IMO) to get some reuse is to identify methods that can be made static; with ease; i.e. don't have dependencies that can't be easily made into "parms".
Those can be put in a static class / dll and shared that way. I have a lot of "builders" and "adapters" in that category.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Thanks Gerry. Helpful to know that there is no silver bullet. Based on this advice I'm isolating some functions out, and also building a class that inherits from the base.
|
|
|
|
|
Hi all,
We are currently having problem with data exported to excel.
When we review the exported file, some show values with exponential format.
To try to work around that, I have the code below with stringbuilder to fix the exponential format issue.
Public Sub GetExcel(ByVal dt As DataTable)
Dim fileName As String = "file" & DateTime.Now.ToString("MMddyyyy") & ".xls"
Response.AddHeader("content-disposition", "attachment;filename=" & fileName)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWriter As StringWriter = New StringWriter()
Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWriter)
Dim dtExportExcel As DataGrid = New DataGrid()
dtExportExcel.DataSource = dt
dtExportExcel.DataBind()
dtExportExcel.RenderControl(htmlWrite)
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.Append("<html xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:x=""urn:schemas-microsoft-com:office:xlExcel8"" xmlns=""http://www.w3.org/TR/REC-html40""> <head><style> table { mso-number-format:'0'; } </style></head> <body></html>")
sb.Append(stringWriter & "</body></html>")
Response.Write(sb.ToString())
Response.[End]()
End Sub
When I run the code, I get an error on this line:
sb.Append(stringWriter & "</body></html>")
The error says, Operator '&' is s not defined for types 'StringWriter' and 'String'
Any ideas what this means?
Thanks in advance
modified 5-Jul-23 21:43pm.
|
|
|
|
|
It means you cannot add a simple string to a StringWriter object, as it makes no sense. Furthermore you cannot append a StringWriter object to a StringBuilder . You can only append strings (or the string values of objects) to a StringBuilder. See StringWriter Constructor (System.IO) | Microsoft Learn[^] for the correct way to combine the two.
|
|
|
|
|
Ok, thank you very much for your response.
So, this would have been the correct way?
sb.Append("</body></html>")
|
|
|
|
|
Yes, You can only add strings, or "things" that can be expressed as strings.
|
|
|
|
|
Thank you. I saw a similar code but written in C# that has exact same code and users say it worked for them.
Thank you for your help. I will try this and hopefully, it works.
|
|
|
|