|
Stick your Page_load code inside a !Postback and see what happens.
if (!IsPostBack)
{
}
Jack of all trades, master of none, though often times better than master of one.
|
|
|
|
|
When I do that the dropdowns don't get refreshed at all. Isn't that what's expected? When the user chooses an entry from the dropdown is issues a postback, so Page_Load won't do anything unless !IsPostBack is True, which it won't be.
|
|
|
|
|
Ron is absolutely correct, When the page is loaded for the first time, the 'Page_Load' event is triggered, and the 'ddlCategory_SelectedIndexChanged' event is not fired because the 'AutoPostBack' property is set to True. However, when you select the first item in the dropdown, the page is posted back to the server, and the 'Page_Load' event is triggered again. This causes the selected index to be reset, and the 'ddlCategory_SelectedIndexChanged' event is not fired.
You should only populate the dropdown list during the initial page load and not on subsequent 'postbacks'. You can do this by wrapping your code inside the 'Page_Load' event with a check for '!IsPostBack' -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = "In Page Load selected index is " + ddlCategory.SelectedIndex.ToString();
XXXDbSupport objDBSupport = new XXXDbSupport();
DbCommand objDBCommand = objDBSupport.CreateDbCommand();
objDBCommand.CommandType = CommandType.Text;
string sSQL = "select distinct isnull(Category,'(blank)') as ProdCat from xxx_product order by isnull(Category,'(blank)')";
objDBCommand.CommandText = sSQL;
DataTable objDBTable = objDBSupport.FillDataTable(objDBCommand);
if (objDBTable.Rows.Count > 0)
{
ddlCategory.DataTextField = "ProdCat";
ddlCategory.DataValueField = "ProdCat";
ddlCategory.DataSource = objDBTable;
ddlCategory.DataBind();
}
else
{
ddlCategory.Text = "n/a";
}
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = "The selected index changed to " + ddlCategory.SelectedIndex.ToString();
XXXDbSupport objDBSupport = new XXXDbSupport();
DbCommand objDBCommand = objDBSupport.CreateDbCommand();
objDBCommand.CommandType = CommandType.Text;
string sSQL = "select distinct isnull(SubCategory,'(blank)') as SubCat from xxx_product ";
if (ddlCategory.Text == "(blank)")
{
sSQL = sSQL + "where isnull(Category,'(blank)') = '(blank)' order by isnull(SubCategory,'(blank)')";
}
else
{
sSQL = sSQL + "where Category = '" + ddlCategory.Text + "' order by isnull(SubCategory,'(blank)')";
}
objDBCommand.CommandText = sSQL;
DataTable objDBTable = objDBSupport.FillDataTable(objDBCommand);
if (objDBTable.Rows.Count > 0)
{
ddlSubcategory.DataTextField = "SubCat";
ddlSubcategory.DataValueField = "SubCat";
ddlSubcategory.DataSource = objDBTable;
ddlSubcategory.DataBind();
}
else
{
ddlSubcategory.Text = "n/a";
}
}
|
|
|
|
|
|
OK, I'll put this in as few words as possible, and please bear with me if I am not clear, I'm still relatively new to this stuff:
So my company has a website we roll out to our customers, and the developers provided a base class to the consultants to use to create custom web parts. The website has a "design mode" built into it where an admin can divide the page up into sections, and basically assign a custom web part to that section of the page. The ascx and dll for the web part obviously have to be on the IIS server where the website can "see" it. I'm not sure exactly how that works technologically, i.e. if it's a master page with individual pages or if it's like a div or whatever.
Anyway, I tried to create a simple webpart with two dropdowns, one of which depends on the other, and a button. The labels and dropdowns appear to be initializing correctly. When I click the button, it correctly updates the label but it clears the dropdowns. Changing the selection in either dropdown appears to re-initialize the entire form including clearing the dropdowns.
Lastly, I could be wrong but I don't believe that the code in ddlCategory_SelectedIndexChanged is getting fired as a result of the dropdown getting clicked - I think it's only getting ran when I call it explicitly. Again, I could be wrong, but I feel like any time a "postback" is issued, only Page_Load is getting fired off, and the controls are all getting cleared/initialized before any of the code in Page_Load is actually run.
I'll pause there for a moment - does anyone see anything in *my* code that could be causing this incorrect result? Before I talk about how I could troubleshoot it within the framework of the rest of my company's website let's establish that.
Thanks
DTXCF
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="First2023WebUserControl.ascx.cs" Inherits="First2023Control.UserControls.First2023WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Hello Year 2023"></asp:Label>
<p>
</p>
Category:<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged">
</asp:DropDownList>
<p>
Subcategory:
<asp:DropDownList ID="ddlSubcategory" runat="server" AutoPostBack="True">
</asp:DropDownList>
</p>
<p>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</p>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Custom1.Custom2.Web.Framework;
namespace First2023Control.UserControls
{
//public partial class First2023WebUserControl : System.Web.UI.UserControl
public partial class First2023WebUserControl : Custom1.Custom2.Web.Framework.UserControlBase
{
[Property(DisplayName = "Message Text")]
public string MessageText
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
ddlCategory.Items.Add("FirstCat");
ddlCategory.Items.Add("SecondCat");
ddlCategory_SelectedIndexChanged(sender, e);
}
else
{
Label1.Text = "I posted back";
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = "The selected index changed";
if (ddlCategory.SelectedValue == "FirstCat")
{
ddlSubcategory.Items.Clear();
ddlSubcategory.Items.Add("FirstCatFirstSubCat");
ddlSubcategory.Items.Add("FirstCatSecondSubCat");
}
else
{
ddlSubcategory.Items.Clear();
ddlSubcategory.Items.Add("SecondCatFirstSubCat");
ddlSubcategory.Items.Add("SecondCatSecondSubCat");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label3.Text = "Someone clicked the button";
}
}
}
|
|
|
|
|
Your issue might be related to the page lifecycle and the way ASP.NET handles postbacks.
The key part of your issue is likely in your 'Page_Load' method where you are clearing and populating the dropdown list only if it's not a postback. The 'Page_Load' event occurs before the 'Button1_Click' event, so when you click the button, the 'Page_Load' event is triggered again before the button click event, and the dropdowns are reinitialized, you can change the behaviour -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCategory.Items.Add("FirstCat");
ddlCategory.Items.Add("SecondCat");
ddlCategory_SelectedIndexChanged(sender, e);
}
else
{
Label1.Text = "I posted back";
}
}
|
|
|
|
|
Thanks for the reply.
So Page_Load always re-initializes controls every time it's invoked, and any postback always triggers Page_Load?
If it's clearing and re-populating the dropdowns every time it posts back, how is it possible to code it in such a way that the SubCategory dropdown's values depend on the selected value of Category?
Again, sorry if I'm not asking the right questions, I hope this makes sense.
Thanks
DTXCF
|
|
|
|
|
Yes, the 'Page_Load' event is triggered on every request to the page, including postbacks. This means that any code within the 'Page_Load' method will execute during each page load, whether it's an initial request or a postback.
You can try and use the 'SelectedIndexChanged' event of your Category dropdown 'ddlCategory' to dynamically populate the 'SubCategory' dropdown named 'ddlSubCategory'' based on the selected value of Category, similar to -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCategory.Items.Add("FirstCat");
ddlCategory.Items.Add("SecondCat");
ddlCategory_SelectedIndexChanged(sender, e);
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCategory = ddlCategory.SelectedValue;
ddlSubCategory.Items.Clear();
if (selectedCategory == "FirstCat")
{
ddlSubCategory.Items.Add("SubCat1A");
ddlSubCategory.Items.Add("SubCat1B");
}
else if (selectedCategory == "SecondCat")
{
ddlSubCategory.Items.Add("SubCat2A");
ddlSubCategory.Items.Add("SubCat2B");
}
}
|
|
|
|
|
When I try to build my project with azure pipeline (or even my PC), using that command line:
dotnet.exe publish C:\..\Produce.csproj --configuration Release -r win-x64 --self-contained true --output C:\..\Produce5
I got same version number as my computer and this error, all the time, almost immediately:
MSBuild version 17.7.1+971bf70db for .NET
...
C:\Program Files\dotnet\sdk\7.0.400\Sdks\Microsoft.NET.Sdk.BlazorWebAssembly\targets\Microsoft.NET.Sdk.BlazorWebAssembly.6_0.targets(325,5)
error MSB4018:
The "GenerateBlazorWebAssemblyBootJson" task failed unexpectedly. [C:\...\Parts.Production.Blazor.csproj]
System.IO.IOException: The process cannot access the file 'C:\..\Parts.Production.Blazor\obj\Release\net7.0\blazor.boot.json' because it is being used by another process. [C:\..\Parts.Production.Blazor.csproj]
The funny thing is, the whole thing build fine with visual studio!
Any idea what's wrong, or what I could do?
Perhaps, Visual Studio 2022 is not using Microsoft.NET.Sdk.BlazorWebAssembly.6_0.targets and I too can avoid it with the command line?
REMARK
adding -maxcpucount:1 to the command line fixes this build job step, but it's a lot slower (obviously) and the whole solution pipeline build job still fails because it's now taking more than an hour...
modified 6-Sep-23 23:21pm.
|
|
|
|
|
Well.. Turns out it's just dotnet publish having an issue with dependencies...
We had A depending on B and C and B depending on C like so
ProjectA
--> ProjectB --> ProjectC
--> ProjectC
Where ProjectC was the Blazor project, and ProjectA was the entry web project being compiled.
Normally this is not a problem, but for Blazor it is, for some reason. So removed ProjectC as an explicit reference of ProjectA and it now compiles!
|
|
|
|
|
I have an existing MVC app, to which I added some Blazor components on some pages.
I.e. instead of starting a new fully Blazor app, I am trying to extend the functionality of an existing app.
I am using WebAssembly rendering, particularly as they are interactive components (updating the UI, doing web service calls, etc..)
It's all working very well except... I can't use breakpoint / debug the components!
Any clue on how to enable debugging of Blazor component on an MVC view?
modified 23-Aug-23 20:28pm.
|
|
|
|
|
In the end, I am loading some debug razor (blazor?) Page from the Blazor project.
When the whole page is a blazor page, debugging works fine again!
|
|
|
|
|
How cam i keep the data source of htmlselect control after postback ?
( I have 14 select controls and don ot wantto load data from db)
**I need the control to not do postback when changed and have both server and client script there for I diddn't use
|
|
|
|
|
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.
|
|
|
|
|