I am trying to cast a htmlinputtext to a htmlgenericcontrol

file.aspx :

<form runat="server" class="probootstrap-form">         
  <div class="form-group" style="margin-top: 20px">
    <label for="name">Markt Name:</label>
    <div class="form-field">
      <input type="text" id="name" runat="server" required="required" class="form-control" />
    </div>
  </div>
</form>

file.aspx.cs :

HtmlGenericControl name = (HtmlGenericControl)Form.FindControl("name");

Error: System.InvalidCastException: Can't cast an object of the typ "System.Web.UI.HtmlControls.HtmlInputText" into "System.Web.UI.HtmlControls.HtmlGenericControl"

How can I read the machine name or ip when I am listening the website. Tried with basic powershell code but unable to retrieve the information.

$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://localhost:8080/Demo/")
$listener.Start()
$context=$listener.GetContext()
$Machinename=$context.Request.UserHostAddress
$IPinformation=$context.Request.RemoteEndPoint

Any suggestions or do I need to write something else to fetch the information. Can any one help in this situation.

I'm currently working on a .NET Core MVC app that requires the user to login (via cookie auth) then once logged in the user is redirected to a cookie protected full framework MVC app.

My question is, how I can share the cookie between them? The reason I'd like to do it this way is the majority of our sites are full framework apps with the .NET Core one being an exception.

From the research I've done it appears there's an interop library that will enable full framework applications to read .NET Core cookies, but I've seen nothing on doing it the other way around - making the .NET Core application create a cookie using the old full framework mechanism.

Is this possible?

When a page opens I want to show a popup in that page after 2 minutes. In the same page I have 3 buttons. When I revisit the page in less than 2 minutes and I click any one button I want to reset the timer. See the explanation below.

  1. I have index.html. In that page I have 3 buttons like so button1, button2 and button 3.

  2. If the user does not click any button in that page within 2 minutes popup will appear with a message "Your time is over".

  3. If the user click any button within the 2 minutes, the timer should be reset to 0.

Can anyone please help me? I tried different code but it's not useful.

I have an asp.net mvc async method waiting for 10 second. The problem is IIS Express (production IIS also) stops processing incoming requests until that async method finishes. I thought await keyword frees current thread for new incoming request. But it seems that I missed something.

public async Task<ActionResult> AsyncMethod()
{
    using (DeliveryPortalEntities context = new DeliveryPortalEntities())
    {
        await context.Database.ExecuteSqlCommandAsync("WAITFOR DELAY '00:00:10'");
    }
    return Json(new { status = "ok" });
}

I'm trying to implement OpenID OAuth 2.0 server with ASP.NET Framework 4.7.2 Web API. It will be used to protect resource APIs with JWT Access/Refresh tokens.

I'm fairly new to OpenID and OAuth so I'm looking for advice/guidelines/libray that I can use to implement this Authorization server.

The Auth server needs to be implemented by using ASP.NET Framework 4.7.2, there is no option for Core at the moment. The resource APIs will be written in ASP.NET Core 2.X.

I've followed the awesome Taiseer's tutorials (Part 1, Part 3, Part 5, and JWT Setup), and currently have OAuth server which can generate JWT Tokens, and Core API which can validate the token.

Here is the code that I currently have.

Auth Server:

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext<SecurityUserManager>(SecurityUserManager.Create);

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true, 
            TokenEndpointPath = new PathString("/oauth2/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), 
            Provider = new SmAuthorizationServerProvider(),
            RefreshTokenProvider = new SmRefreshTokenProvider(),
            AccessTokenFormat = new SmJwtFormat("http://localhost:7814"),
            ApplicationCanDisplayErrors = true,
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

SmAuthorizationServerProvider.cs

public class SmAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        string clientId = string.Empty;
        string clientSecret = string.Empty;
        Client client = null;

        if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
        {
            context.TryGetFormCredentials(out clientId, out clientSecret);
        }

        if (context.ClientId == null)
        {
            //Remove the comments from the below line context.SetError, and invalidate context 
            //if you want to force sending clientId/secrects once obtain access tokens. 
            context.Validated();
            //context.SetError("invalid_clientId", "ClientId should be sent.");
            return Task.FromResult<object>(null);
        }

        using (AuthRepository _repo = new AuthRepository())
        {
            client = _repo.FindClient(context.ClientId);
        }

        if (client == null)
        {
            context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
            return Task.FromResult<object>(null);
        }

        if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential)
        {
            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("invalid_clientId", "Client secret should be sent.");
                return Task.FromResult<object>(null);
            }
            else
            {
                if (client.Secret != Helper.GetHash(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret is invalid.");
                    return Task.FromResult<object>(null);
                }
            }
        }

        if (!client.Active)
        {
            context.SetError("invalid_clientId", "Client is inactive.");
            return Task.FromResult<object>(null);
        }

        context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
        context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
        SecurityUser user = null;

        if (allowedOrigin == null) allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        using (AuthRepository _repo = new AuthRepository())
        {
            user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        string scopes = null;

        if (context.Scope.Count > 0)
        {
            scopes = string.Join(" ", context.Scope.Select(x => x.ToString()).ToArray());
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

        // Add the user id as claim here 
        // Keep the claims number small, the token length increases with each new claim
        identity.AddClaim(new Claim("sid", user.Id.ToString()));

        // add the client id as claim 
        if (!string.IsNullOrEmpty(context.ClientId))
        {
            identity.AddClaim(new Claim("client_id", context.ClientId));
        }

        var props = new AuthenticationProperties(new Dictionary<string, string>
        {
            {
                "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
            },
            {
                "as:scope", (scopes == null) ? string.Empty : scopes
            },
            {
                "userName", context.UserName 
            }
        });


        var ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }

        return Task.FromResult<object>(null);
    }

    public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
        var currentClient = context.ClientId;

        // check if the token is created with specified client_id
        if (!string.IsNullOrEmpty(currentClient) && !string.IsNullOrEmpty(originalClient))
        {
            if (originalClient != currentClient)
            {
                context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
                return Task.FromResult<object>(null);
            }
        }

        var newIdentity = new ClaimsIdentity(context.Ticket.Identity);

        // Change auth ticket for refresh token requests if needed
        // newIdentity.AddClaim(new Claim("newClaim", "newValue"));

        var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
        context.Validated(newTicket);

        return Task.FromResult<object>(null);
    }

    public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
    {
        Client client; 

        using (AuthRepository _repo = new AuthRepository())
        {
            client = _repo.FindClient(context.ClientId);
        }

        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        oAuthIdentity.AddClaim(new Claim("client_id", client.Id));

        var props = new AuthenticationProperties(new Dictionary<string, string>
        {
            {
                "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
            }
        });

        var ticket = new AuthenticationTicket(oAuthIdentity, props);
        context.Validated(ticket);
        return base.GrantClientCredentials(context);
    }

}

SmJwtFormat.cs

public class SmJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
    private const string AudiencePropertyKey = "as:scope";
    private readonly string _issuer = string.Empty;
    private AuthRepository authRepo;
    private SecurityKey signingKey;

    private string secret = "P@ssw0rd-7BBF8546-C8C1-44D9-A404-9E1CAF80EC9D-F2FEC38D-2041-499E-9FAA-218C8B1EEC7B";

    public SmJwtFormat(string issuer)
    {
        _issuer = issuer;
        authRepo = new AuthRepository();

        // Generating the signingKey
        string symmetricKeyAsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));

        var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

        signingKey = new SymmetricSecurityKey(keyByteArray);
    }

    public string Protect(AuthenticationTicket data)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        // The token audience from the JWT terminology is the same as the token Scope in OAuth terminology. 
        string scope = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;

        if (string.IsNullOrWhiteSpace(scope)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience/scope");

        var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature);

        var issued = data.Properties.IssuedUtc;
        var expires = data.Properties.ExpiresUtc;

        if (scope != null)
        {
            var scopesList = scope.Split(' ').ToList();

            var audClaims = scopesList.Select(s => new Claim("aud", s));

            data.Identity.AddClaims(audClaims);
        }

        var token = new JwtSecurityToken(_issuer, null, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);


        var handler = new JwtSecurityTokenHandler();

        var jwt = handler.WriteToken(token);

        return jwt;
    }

    public AuthenticationTicket Unprotect(string protectedText)
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = _issuer,
            IssuerSigningKey = signingKey,

        };

        var handler = new JwtSecurityTokenHandler();
        SecurityToken token = null;

        // Unpack token
        var pt = handler.ReadJwtToken(protectedText);
        string t = pt.RawData;

        var principal = handler.ValidateToken(t, tokenValidationParameters, out token);

        var identity = principal.Identities;

        return new AuthenticationTicket(identity.First(), new AuthenticationProperties());
    }
}

Here is my resource ASP.NET Core 2.2 API Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddAuthorization();

        // identity http://localhost:7814
        // resource https://localhost:44337

        var key = "P@ssw0rd-7BBF8546-C8C1-44D9-A404-9E1CAF80EC9D-F2FEC38D-2041-499E-9FAA-218C8B1EEC7B";
        string symmetricKeyAsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
        var keyByteArray = Convert.FromBase64String(symmetricKeyAsBase64);
        var securityKey = new SymmetricSecurityKey(keyByteArray);

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(o =>
        {
            o.Authority = "http://localhost:7814/";
            o.RequireHttpsMetadata = false;

            o.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidIssuer = "http://localhost:7814",
                ValidateAudience = true,
                ValidAudiences = new List<string>()
                {
                    "api1" 
                },

                //IssuerSigningKey = securityKey
            };
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseAuthentication();

        app.UseMvc();
    }
}

Currently I'm able to generate tokens by posting to http://localhost:7814/oauth2/token with the following parameters:

grant_type=password

username=user1

password=p@ssw0rd

client_id=smLocalhost

client_secret=secret

scope=api1 api2

After that the token can be used to access secured endpoints in the resource API.

I've researched IdentityServer4, OpenIdDict and AspNet.Security.OpenIdConnect.Server, but they seems to be working only with ASP.NET Core.

So after all this stuff, my questions are:

1. How to add OpenID on top of that?

2. Is there a library that I can use?

3. Could you please give me tutorial/advice what can I do to implement it?

4. How to implement discovery document endpoint (.well-known/openid-configuration) and rotate the public keys for asymmetric token signing?

Thanks in advance!

I want to open Windows command prompt from C# code and want to execute batch file from it containing few commands. I tried with simple "echo" and "dir" command on trial basis and it is not working. I am neither getting error nor expected output. At least cmd window should open then arguments can be passed.

I tried two options - runnind cmd.exe and running batch file. I am not able to find the mistake I am making in the code. Thanks in advance for the help.

    var baseDirectory = "~/App_Data/TestRoot";
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.UseShellExecute = false;
    processStartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath(baseDirectory);
    processStartInfo.CreateNoWindow = false;
    processStartInfo.WindowStyle = ProcessWindowStyle.Maximized;

    //running cmd.exe then .bat as argument
    processStartInfo.FileName = HttpContext.Current.Server.MapPath(baseDirectory + "/cmd.exe");
    processStartInfo.Arguments = HttpContext.Current.Server.MapPath(baseDirectory + "/test.bat");

    Process process = Process.Start(processStartInfo);

I changed FileName and removed Arguments property for option second, please refer code below.

processStartInfo.FileName = HttpContext.Current.Server.MapPath(baseDirectory + "/test.bat");

The test.bat file contains just one line echo hello. When I tried to run this directly from CMD and double click, it is working fine in both the cases. I am facing issue only in case of invoking it from C# code.

As part of moving our applications from one to another server. We tried to host one our application in IIS and tried to open the application in the browser that time we are facing this issue:

Could not load file or assembly 'Microsoft.SqlServer.SQLTask' or one of its dependencies. An attempt was made to load a program with an incorrect format.

No idea how to deal with this error, should I have to install any dependencies related to MS SQL Server? Seeking for help out here, Any suggestions or solutions are appreciated.

FYI:IIS version on Destination machine and MS SQL Server 2012 using.

There is no DLL in this location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL. Will it affect the loading of the assembly?

I want to be able to read in a single date plus a range of dates from a datepicker and store them in a variable.

So then i can use this variable to do a parameterized query against MySQL DB. I cant find code anywhere to do this. Any help is appreciated as the deadline approaching fast.

Thanks in Advance !!

I am sure this question has been asked before. I am looking for some functionality to be able to copy a row from Excel and paste the result in a column in a web <asp:GridView>, first off is it possible. I have been scouring the web and have not managed to find something web related.

I am trying to scrape the "Read More" links from multiple search result pages of this website: https://www.cgg.com/en/31

There is no canonical link to any particular page of the search results. When you navigate to page 2, the URL remains https://www.cgg.com/en/31.

Upon inspection of the underlying HTML and JavaScript, I see that the pagination links trigger a JavaScript function when clicked.

<a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$ctl00$Layout-7-main-partial2$TmsPager1$ctl02$ctl00','')">NEXT</a>

Here is the function that gets called:

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

So by clicking "NEXT" the browser is redirected to the same URL but with different content.

I'd like to scrape the "Read More" links from the next page after clicking the "NEXT" button. How would I do this using AngleSharp since clicking the "NEXT" button actually submits a form and reloads the page?

Here's what I have so far: https://dotnetfiddle.net/3f6XZC

I have a bulleted list in a grid. It is databound. I return some folder paths in this list. If the path is a share on a server all works find as example 1.

In example 1 the spaces are replace by %20.

But for some reason in Example 2 when the actual drive letter is used the spaces are replaced by %2520 which then does not work.

  1. file://server1/scanned/ASB/DE/AGOPSOWICZ,%20DANIEL/AGOPSOWICZ,%20DANIEL%202018%2011%2014

  2. file:///Q:/ASB/DE/AGOPSOWICZ,%2520DANIEL/AGOPSOWICZ,%2520DANIEL%25202019%252002%252021

What causes this %2520 to happen? Is this only in a bulletedlist?

If so how can I fix this as this is not what is being passed back by my data.

Thanks,

Roger

On the page I placed a RadWindow which hase several RadCombobobxes and RadGrid. When I open this window, I see all the elements that it contains, BUT if I open it in Internet Explorer, I cannot interact with this elements.

RadComboBoxes, RadButton, RadGrid is not available. Found that in some way, that the RadWindow itself covers all its content.

And if I reduce this window so that all its content will be outside the RadWindow - only then I will be able to interact with the content - RadComboboxes, RadGrid and etc.

How can fix this in IE? Version of IE: 11.0.9600.18977

<telerik:RadWindowManager RenderMode="Lightweight" runat="server" Overlay="false" ID="rw_customConfirm3" Modal="true">
            <Windows>
                <telerik:RadWindow RenderMode="Lightweight" ID="rw_customConfirm2" Behaviors="Close, Move" Width="800px" Height="800px" runat="server">
                    <ContentTemplate>
                          <asp:Panel runat="server" ID="Window_Panel_Grid" Visible="true" HorizontalAlign="Center">
                                <telerik:RadGrid ID="RadGrid2" runat="server"  RenderMode="Lightweight" AutoGenerateColumns="False" Culture="ru-RU" GroupPanelPosition="Top" OnNeedDataSource="RadGrid2_NeedDataSource" ShowGroupPanel="True" BorderStyle="Solid" AllowPaging="True" PageSize="5" EnableLinqExpressions="false" OnPreRender="RadGrid2_PreRender" AllowFilteringByColumn="True"  FilterType="CheckList" AllowMultiRowSelection="True">
                                    <...>
                                </telerik:RadGrid>
                            </asp:Panel>
                            <div>
                                <telerik:RadButton RenderMode="Lightweight" runat="server" ID="CloseMiniGrid" Text="Выбрать договора" Width="100px" OnClientClicked="closeCustomConfirm2" OnClick="CloseMiniGrid_Click" AutoPostback="true">
                                </telerik:RadButton>
                            </div>
                    </ContentTemplate>
                </telerik:RadWindow>
            </Windows>
        </telerik:RadWindowManager>

I'm trying to hide a LinkButton in a GridView if a field in my database row is empty. There are no errors but the row is not hidden either. Is this method possible or must I use OnRowDataBound to accomplish this?

Here is the aspx page:

<asp:GridView ID="tblDownload" runat="server" AutoGenerateColumns="false" ClientIDMode="Static">
    <Columns>
        <asp:BoundField DataField="Description" HeaderText="Description" />                        
        <asp:TemplateField HeaderText="Download Link" SortExpression="Download Link">
            <ItemTemplate>
                <asp:LinkButton ID="ID" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("ID") %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

and here is the c#:

    public void BindTable()
    {
        try
        {                
            string constr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))

            {
                using (SqlCommand cmd = new SqlCommand("dbo.spAllRows", con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;

                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        tblDownload.DataSource = dt;
                        tblDownload.DataBind();                           
                    }
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        sdr.Read();
                        var FileName = sdr["FILE_NAME"].ToString();
                        con.Close();

                        if (FileName == "" || FileName == null)
                        {
                            LinkButton DownloadLink = tblDownload.FindControl("ID") as LinkButton;
                            DownloadLink.Visible = false;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {

        }
    }

I tried adding a vue project to a sub-folder in my asp.net 4.6 website project using vue cli.

I would edit the vue app using vs code.

The problems I ran into:

  1. I can't use the npm server (npm run serve) address since I need to make calls to webapi in asp.net website. First the cors problem, and even after intsalling AspNet cors I have the webforms authentication problem. This is why I run the vue app with vs 2017 from the sub-folder using iis express Like so 'http://localhost:1234/vue-subfolder', which brings me to the next problem

  2. I would have to run npm run build every time I made any change to vue app. Running npm run serve would not update the vue app running on iis express.

  3. I'm also using TFS for source control. Each time I would run `npm run build' I would get file does not exist errors since js files get deleted and created.

Is there a way create and edit the vue app in vs 2017 and have it auto built on saving changes?

I have a screen with a table that can have any number of input fields within it depending on the filters that limit the records shown. Next to each input field is a link that the user will hit to save the data for that record to the database. What I am trying to do is when the user clicks on a save button for any given row, I want the cursor to move to the next input field on the next row if it exists. I know that the postback will erase my current cursor location so I have been trying to work on saving it within a variable with no luck. Any help would be appreciated. The javascript based on my understanding is supposed to get the element and store it into a hidden field. The result I get back though is the URL of my site. Only when I store the field into the test2 field do I get the actual element stored. Should I try to somehow get the coordinates of the element and store that? But if I do that then how would I get the next input field available in the table?

Table Definition and JavaScript Below:

$('.checklistequipmentinsertlink').mousedown(function () {
    document.getElementById('savedelement').value = document.querySelector("a:active");
    var test2 = document.querySelector("a:active");
    var test = document.getElementById('savedelement').value;
});
<div id="scrollbox" class="tablediv" onscroll="javascript:document.getElementById('scrollposition').value = this.scrollTop">
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayName("Equipment/Location")
                </th>
                <th>
                    @Html.DisplayName("Category")
                </th>
                <th>
                    @Html.DisplayName("Expected Count/Checkoff")
                </th>
                <th>
                    @Html.DisplayName("Actual Count/Checkoff")
                </th>
            </tr>
        </thead>
        <tbody>
            @if (Model.postChecklistEqupmentList != null)
            {
                @foreach (var item in Model.postChecklistEqupmentList)
                {
                    <tr>
                        <td class="hiddentd">
                            @Html.DisplayFor(modelitem => item.Checklist_ID)
                        </td>
                        <td class="hiddentd">
                            @Html.DisplayFor(modelitem => item.Checklist_Equipment_ID)
                        </td>
                        <td>
                            @Html.DisplayFor(modelitem => item.Checklist_Equipment_Desc)
                        </td>
                        <td>
                            @Html.DisplayFor(modelitem => item.Equipment_Category_Desc)
                        </td>
                        <td id="expectedcount">
                            @Html.DisplayFor(modelitem => item.Equipment_Count_Or_Checked)
                        </td>
                        <td>
                            @Html.TextBoxFor(modelitem => item.Actual_Count_Or_Checked, new
                             {
                                htmlAttributes = new
                                  {
                                     @class = "form-control"
                                  },
                                autofocus = "autofocus"
                            })
                        </td>
                        <td>
                            <a href="#" class="checklistequipmentinsertlink">Save</a>
                        </td>
                    </tr>
                }
            }

        </tbody>
    </table>
</div>

I have a textbox in 1 panel

Then in another panel I have

<asp:Panel ID="pnlPopUpInfo" runat="server" CssClass="modalPopupImpact" Width="1000px" style = "align-items:center; text-align: center; display:none;">

<a class="hoverIDcard" href="#" userID="12345">MyID</a>

How can I replace 12345 in the line above with the value in the textbox? I tried:

<a class="hoverIDcard" href="#" userID=textbox.Text>MyID</a>

But it didn't work

I'm developing an app that requires a fairly complex authentication scenario.

The app it self is an Angular 7 app with ASP.NET Core 2.2 backend. I have implemented Azure Active directory authentication for the app and backend services, which works well.

I also have a requirement for a few of the web API methods to be invoked by sensors (raspberry pi running Windows IoT Core and a UWP App). I can't think of an approach at the moment and looking for recommendations? Is it possible to mix and match authentication mechanisms in ASP.NET core, and say add authentication based on Certificate or something similar?

This is how my razor code looks like

<form asp-action="Save" asp-controller="ClassesHeld" method="post">
    <input asp-for="ClassHeldId" value="@Model.ClassHeldId" hidden />
    <div class="form-group">
        <label>Student</label>
        <input asp-for="@Model.Student" value="@Model.Student" class="form-control" readonly />
    </div>

    <div class="form-group">
        <label>Grade</label>
        <input id="Grade"asp-for="Grade" type="number" value="@Model.Grade" class="form-control" min="0" max="5" />
    </div>

    <div class="form-group">
        <label>Attendance</label>
        <input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
    </div>

    <button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>

<script>
    $("#Attendance").on("change", function () {
        $("#Grade").attr("disabled", this.checked);
    });
</script>

Yet for some reason, clicking on the checkbox does nothing at all. I have tried this with simple script as well, and that didn't work either.

    document.getElementById('Attendance').onchange = function () {
    document.getElementById('Grade').disabled = this.checked;
}; 

Neither of these worked.

I have even copied some solutions from here (one of them is that last simple scrip with document.getElementbyId, and none of it worked. I have to be missing something simple, but I've been looking at this for the past hour and I still can't figure it out.

I apologize if the question is stupid or noob-level. But I am getting desperate.

EDIT: Simply to add more information, this form works perfectly fine when submitting data, controller saves the stuff to the database... Everything works fine, just not the part where it disables the ability to edit the Grade if the student has not attended.

So the objective, is to disable the input field when the checkbox for "attendance" is checked

I am trying to make a "click here to print page"

<script type="text/javascript">
function PrintElem ()
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head>');
    mywindow.document.write(document.head.innerHTML)
    mywindow.document.write('</head><body >');
    mywindow.document.write(document.body.children[1].innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();
}
</script>

<a onClick="printElem()" href="#"> print a div! </a>

All the stylings is included in Head, but for some reason are these skipped, when i click the print a div! link, but inlcuded when i click it with DevTools open?

Why?

I'm trying to use a report viewer control, within a razor view, in the mvc 5 framework. But it don not know the correct way to do that can any one help me please