ASP.NET

125K

Solutions

28K

Contributors

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

Share tech news, updates, or what's on your mind.

Sign up to Post

Can you please tell me what this error means?

Error statement: sd = cmd.ExecuteReader();

screenshot.JPG
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDel
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Lenovo\Documents\Visual Studio 2012\Projects\InsertUpdateDel\InsertUpdateDel\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sd;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
                cmd.Connection = cn;
                loadlist();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "" & txtName.Text != "")
            {
                cn.Open();
                cmd.CommandText = "Insert into info(id, name) values ('" +txtID.Text+"', '" +txtName.Text+"')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record Inserted", "Programming");
                cn.Close();
                txtID.Text="";
                txtName.Text="";
                loadlist();
            }
        }

Open in new window

0
OWASP: Threats Fundamentals
LVL 13
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

I have a ticketing system which is written in KnockOut using template. Template structure is as below This template is repeated for multiple users on a page. In this parent.AssignedTickets is a list of Ticket Id assigned to users. So system has multiple TicketIDs and if it is assigned to user then it shows checked.

I want to change label color if checkbox is checked.

<script type="text/html" id="TicketAssignmentTemplate">
    <td>
        <label>
          <input type="checkbox" data-bind="checkedValue: TicketId, checked: $parent.AssignedTickets" />
        </label>
    </td>
    <td>
        <label data-bind="text: title"></label>
    </td>
</script>
<style>.success{background-color: #DFF0D8;}</style>

Open in new window



I tried data binding label css: {success: !$parent.AssignedTickets} but that did not work. Surprise! It can't be that simple. Any other thing I can try?

Part 2. Reason, I want this label highlighted is because supervisors who assign Tickets know which Tickets are already assigned. So this Label color should be highlighted in other TicketTemplate of other users too. I think that will require having a list defined across multiple users and updating it real time as tickets get assigned.
0
I have a checkbox panel and I am adding the text for check box like this

chkPanel.Controls.Add(new CheckBox { Text = "Savings" + "This text needs to be red and bold", Checked = true, Enabled = false });
chkPanel.Controls.Add(new LiteralControl("<br />"));
chkPanel.Controls.Add(new CheckBox { Text = "Checking" , Checked = false, Enabled = false });


where you see "This text needs to be red and bold"  i actually want that text to be red and bold.  is it possible. if yes how?
0
I have a C# ASP.NET Webform which fails on a Response.Redirect.  When I look at the resolved Url in variable myUrl it is "/WebForm1.aspx" whereas I would have expected that it would contain "C:/Users/PatClarke/source/repos/TiosClient/TiosClient". I am running this locally in debug mode. Why would ResolveUrl return Blank for the path ?


                try
                {
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    string myUrl = ResolveUrl("~/WebForm1.aspx");
                    Response.Redirect(ResolveUrl("~/WebForm1.aspx"));
                }
                catch (Exception ex)
                {
                    MyGlobals.logger2.Information("Error encountered: {error} ", ex);

                }

Open in new window


The exception ex contains "ExceptionState = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."

What am I doing wrong ? I have granted everyone permission to the directories in question.
0
Hi,

I recently ran a Nessus scan and have been working through the output, I'm trying to is how to fix one of the vulnerabilities

The web server running on the remote host appears to be using Microsoft ASP.NET, and may be affected by a denial of service vulnerability. Requesting a URL containing an MS-DOS device name can cause the webserver to become temporarily unresponsive. An attacker could repeatedly request these URLs, resulting in a denial of service. Additionally, there is speculation that this vulnerability could result in code execution if an attacker with physical access to the machine connects to a serial port.

Solution
Use an ISAPI filter to block requests for URLs with MS-DOS device names.

I have been researching how to resolve this but can't find the answer, do I need to install a Microsoft patch or something, any help would be appreciated

The server is running 201r2
0
Open a pop up and populate fields.  The following code opens the RunReport.aspx but the getElementById does not populate the value.
I suspect it might be that the desired field is not present and that a delay might be needed.  I used a delay function on another site and it worked.
On this site it does not work at all.  Question:  what are my options to autopopulate a field similar to the following:

var por = window.open ("http://servername/Finance/RunReport.aspx?Report=Timecard_Report_Employee_Copy&Parent=OS_DESKTOP&WizardLayout_ctl10_SERVER_IFPY_TC_IMP.IFPY_PER_CC_0=TEST&dt=" + new Date(), "mywindow","status=1,toolbar=1,width=1000,height=800");

por.document.getElementById("WizardLayout_ctl10_SERVER_IFPY_TC_IMP.IFPY_PER_CC_0").value = "TEST";
0
I have an ASP.NET Web Site built in .NET 4.7 using C#. In my web.config, I have the following Forms authentication (see web.config below) with the "domain" attribute set to ".mydomain.com" for my Production environment. Is there a way to dynamically change its value (via C#)  based on the environment, such as QA, Staging, etc. For example, if (Request.Url.AbsoluteUri.StartsWith("http://qa")), then I want to change the value of the "domain" attribute to ".myqadomain.com", and  if (Request.Url.AbsoluteUri.StartsWith("http://staging")), change the value to ".mystagingdomaincom".

Here's the <authentication> section of my web.config:
    <authentication mode="Forms">
      <forms path="/" name="MyWebSite_Auth" loginUrl="~/login.aspx" defaultUrl="~/customers/Default.aspx" protection="All" slidingExpiration="true" domain=".mydomain.com" timeout="350" cookieless="UseCookies"/>
    </authentication>

Please provide the necessary C# code to accomplish this.

Many thanks in advance.
0
I have an old MVC project that I want to upgrade/port to ASP.Net Core Web Applications. I've been reading some articles:

Ex: https://arghya.xyz/articles/porting-aspnet-apps-to-aspnet-core-2.0/

I created an ASP.Net Web Application Core. I run it and I get the first page. I click on Login and takes me to the login page. But, I don't see the login page in the project.
I did a search and I don't see it. I clicked on "show all files" but still don't see it.

See screenshots below:

e1.png
e2.png
0
Hello Experts,

I 'm new to JQuery and using Datatable(3rd party o plug-in) to show data(grid style) on the page. Once the record is inserted I want to update the grid(new record is inserted via button click which opens modal popup and later I'm refreshing the grid). But I'm getting "Not available" when destroying the datatable so I rebuild it again with new data. Below is the sample code.

HTML
<div class="table-responsive m-t-40">

                    <table id="dataTable" class="display nowrap table  dataTable" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>                               
                                <th>Phone</th>
                                <th>Email</th>                              
                            </tr>
                        </thead>
                        <tbody id="tblbody"></tbody>
                    </table>
                </div>

Open in new window


JavaScript
 $("#tblbody").empty();

                            data = JSON.parse(data);
                           $('#datatable').datatable().destroy(); -- Error here on  on Quick watch the value is "not available"
                            
                             -- Rest of the code doesn't execute due to error     
                            var html = '';
                            for (var i = 0; i < data.length; i++) {
                                var obj = data[i];

                                html += '<tr>'
                                html += '<td>' + obj.FirstName + '</td>';
                                html += '<td>' + obj.LastName + '</td>';                             
                                html += '<td>' + obj.PhoneNumber + '</td>';
                                html += '<td>' + obj.Email + '</td>';                                                                 
                                html += '</tr>'
                            }

Open in new window


If I comment $('#dataTable').DataTable().destroy() and try the above code I get a Warning message(popup) on the page and also tried $('#dataTable').DataTable().clear() it doesn't throw error but I got the same warning. Attached is the warning message.

Thanks,
ASPDEV
0
I am creating a hyperlink from my codebehind of asp.net. when i click on the link i want the other form to be opened as a pop up. how can i do that

this is how i create my hyperlink

var navigation = new TableCell();
navigation.Controls.Add(new HyperLink { Text = "Edit", NavigateUrl = "newpage.aspx?Account=" + dt.Rows[i].ItemArray[0] + "&ID=" + dt.Rows[i].ItemArray[1] + "&Period=" + dt.Rows[i].ItemArray[12] });
0
Learn SQL Server Core 2016
LVL 13
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

In c#, how to read all child, not one by one?

string xmlString = "<people><firstname>John</firstname><lastname>John</lastname></people>";            

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);
            foreach (XmlNode node in xmlDoc.SelectNodes("//people"))
            {
                //how to loop and read all child?
            }

Open in new window

0
I'm trying to post to an HttpHandler ashx file with parameters.

function sendClickData(methodName,paramValue) {
    
    try {
        // create web service param object
        var passUrl = "SetGridDefaults.ashx";

        // save data to web service using an ajax post method
        $.ajax({
            type: "POST",
            url: passUrl,
            data: "MethodName=SetDefaultGridView",
            success: function (data) {

            },
            error: function (error) {
                alert(error);
            }
        });
    } catch (e) { }

}

Open in new window


In the data row, I am passing values to be retrieved as query strings:

In my ProcessRequest, I am retrieving the value:

  Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim method As String = context.Request.QueryString("MethodName").ToString()

Open in new window


When I run it, it gives me an error that the MethodName is null on the request.querystring line of code:
>>An exception of type 'System.NullReferenceException' occurred

This code was from an original article here:
original code

The only thing I see different is that it says to include an older version of jquery - version 1, whereas I am using version 3.

Also, in addition, I would like to pass two values if possible.

And yes, I know I can use a web service or API, but I was hoping I could use this, since it's just a very simple request.

Thanks!

Starr
0
What I ultimately want is dynamically create controls depending upon the number I get from db.

 for (int intControlIndex = 0; intControlIndex < number returned from db; intControlIndex++)
{
add a label and hyperlink
add a panel
add few check boxes inside the panel
}

so if number returned from db = 2 I need the output something like this

I need the above items to be shown in same sequence that I have shown above.
0
I have a dataTable that I am building that switches between tile and list view. On the tile view I have inserted a row that is a new button which users can click to insert a new user. When the table is returning the number of records in the table it will include the NewButtonRow in the count.
For example, in the simplified table below I have one record, but the number of records returned will be 2 because of the NewButtonRow.
 <table id="TableTeamGrid">
            <thead>
                <tr>
                    <th>
                    </th>
                </tr>
            </thead>
            <tbody id="dataContainer" clientidmode="Static" runat="server">
                <tr id="NewButtonRow">
                               <td class="stylAddNewBtn"></td>
                </tr>
                <tr id="TileRow">
                               <td></td>
                </tr>
  </tbody>
 </table>

Open in new window

I need it to show 1(START) of 1(MAX or TOTAL) in the case of the simplified table above instead of 1(START) of 2(MAX or TOTAL).
I am using this dataTable here: https://datatables.net/.
These are the settings I have for the table:
$(document).ready(function () { 
  $('#TableTeamGrid').DataTable( {
"ordering": true,
"order": [ 1, 'asc' ],
"stateSave": false,
"serverside":   false,
"autoWidth": false,
"language": {
"lengthMenu": '<select>'+'<option value="10">10 per page</option>'+'<option value="20">20 per page</option>'+'<option value="30" selected>30 per page</option>'+'<option value="40">40 per page</option>'+'<option value="50">50 per page</option>'+ '<option value="-1">All</option>'+'</select>'  ,
"info": "_START_ of _MAX_"  ,
"paginate": {
"previous": "<<"  ,
"next": ">>" 
 }
 } ,
"pageLength": 30 ,
scrollResize: true,
scrollY: false,
scrollX: true,
scrollCollapse: true,
"dom": '<"stylTableMenu"filp>tB' 
});
});

Open in new window

0
I call the below function from my page_load section

 private void AddControls()
        {
            int checkBoxCount = 3;
            var newPanel = new Panel();
            var newLabel = new Label();
            var newTextbox = new TextBox();
           
            System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
           
           
            for (int intControlIndex = 0; intControlIndex < checkBoxCount; intControlIndex++)
            {

                // textbox needs a unique id to maintain state information
                createDiv.ID = "createDiv_" + intControlIndex;
                newTextbox.ID = "TextBox_" + intControlIndex;
                newPanel.ID = "newPanel_" + intControlIndex;
                newLabel.ID = "newLabel_" + intControlIndex;
                newLabel.Text = "New Label";
                form1.Controls.Add(createDiv);

                // add the label and textbox to the panel, then add the panel to the form
                newPanel.Controls.Add(newLabel);
                newPanel.Controls.Add(newTextbox);
                createDiv.Controls.Add(newPanel);

            }

        }



--- This is what gets created when i run my code


    <div id="createDiv_2"><div id="newPanel_2">
      <span id="newLabel_2">New Label</span><input name="TextBox_2" type="text" id="TextBox_2">
</div></div></form>


as you can see only one div is …
0
Create a RESTful service (called News-API) using asp.net web api

TODO
● Create a Web-API .NET Core project for a RESTful service
● On startup, create a database by using EF Core (from nuget) containing the table “News”:
○ Id INTEGER PRIMARY KEY
○ Title VARCHAR(100) NOT NULL
○ Content text NULL
● Populate the table with a few dummy records (5 max)
● Add an API-Controller with the name “NewsController”
● Add an action to get all the records
● Add an action to get a specific record (primary key)
● Add an action to add a record
● Add an action to update a record
● Add an action to delete a record
0
I have a pop up aspx form in which I want to show multiple checkbox lists.

The number of checkboxlists that I need to show depends upon the number of rows that are returned from database

 if (dt.Rows.Count ==  5)
{
show 5 different checkboxlists
}

 if (dt.Rows.Count ==  2)
{
show 1 different checkboxlists
}
0
Hello,

I am getting the following error when attempting to add more than one record to a table.

System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK__AOP6__3214EC075FC67488'. Cannot insert duplicate key in object 'dbo.AOP6'. The duplicate key value is (0).
The statement has been terminated.'

Any ideas what is causing this error?

I am using ASP.NET MVC.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DataLibrary.DataAccess
{
    public static class SqlDataAccess
    {
        public static string GetConnectionString(string connectionName = "MVCDemoDB")
        {
            return ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
        }

        public static List<T> LoadData<T>(string sql)
        {
            using (IDbConnection cnn = new SqlConnection(GetConnectionString()))
            {
                return cnn.Query<T>(sql).ToList();
            }
        }

        public static int SaveData<T>(string sql, T data)
        {
            using (IDbConnection cnn = new SqlConnection(GetConnectionString()))
            {
                return cnn.Execute(sql, data); *****ERROR Line*****
            }
        }
    }
}



Thanks,

Victor
0
I have the following piece of code

 <td style="cursor: auto; text-align: center" onmouseover="ShowAccount('vv<%# Eval("acct_nbr") %>','<%# Eval("acct_nbr") %>' );"
                                onmouseout="ShowAccount('vv<%# Eval("acct_nbr") %>','<%# Eval("acct_nbr_mask") %>' );">
                                <div id="vv<%# Eval("acct_nbr") %>">
                                    <asp:Label ID="lblAccountNbr" runat="server"><a href='AccountExceptionUpload.aspx'><%# Eval("acct_nbr_mask")%></a></asp:Label>
                                </div>
                            </td>

as you can see I am masking hte account number and on mouse hover you can see the account number. what I am trying to do is when i hover my mouse on account number i also want it converted to a hyper link . i tried putting <a> in the label but that did not help.
0
CompTIA Security+
LVL 13
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

In my javascript I want to check if a button is enabled or disabled. how can i do that.
0
I have a pop up screen with save and cancel button.
When the user clicks on cancel button I want to do the following

if (allconditionstrue)
{
show confirm message box.
if the user clicks yes , close the pop up
if user clicks no, close the message box and keep pop up open.
}
else
{
close pop up
}
0
Editing an ASP.Net webpage.

Everyone, We are trying to edit this webpage, please see the attached images.
This is a checkout page and we are trying to put the "Zip Code" text box on the same
line as the "City and State" text boxes. We want to move the highlighted box which is
the zip code box, one row up to be on the same line as "city" and "state". The "State"
text box is the "Drop Down" box. I also included the image with the Code. I know a little bit of HTML and CSS, but nothing really about ASP.Web Page DesignWeb Page Source
Thanks in advance for your help.
0
I am working on an ASP.NET application.

The Design window of VS2019 does not render correctly CSS3, like grid or flexbox. Or it only understands the old CSS. (?)

While this may not be important (one can view page in browser), still I may be missing some setting... Is there a way or option I can set for CSS3 in VS2019?
0
Hello Experts,

I have an issue with C# List, when I add values it showing the duplicates data.

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		Student std = new Student();
		List<Student> studentList = new List<Student>();
		
		std.ID = 1;
		std.Name = "John";
		studentList.Add(std);
		
		
		std.ID = 2;
		std.Name = "Doe";
		studentList.Add(std);	
		
		
		Console.WriteLine(studentList.Count);//count
		
		Console.WriteLine(studentList[0].ID); //ID
		Console.WriteLine(studentList[0].Name); //Name
	}
}

public class Student
{ 
	public int ID { get; set; }
	public string Name { get; set; }
}

Open in new window


Output:
2
2
Doe

The count was correct, but I was expecting below output and the list shows duplicates:

2 -- >Count
1 --> ID
John -- > Name

Please help, what I was doing incorrect.

Thanks,
ASPDEV
0
My HiddentFields are getting document.getElementById are not working as expected inside javascript in asp.net. Everytime I tried set a value for hidden field I get the following error

Uncaught TypeError : Cannot ready property 'value" of null


In the below code there is a javascript function loadfile().
This is the line where i am getting the error : document.getElementById("hAction").value = "";
if I move past that error the next step where i have to read/update value for a variable I am getting the above mentioned error. So looks like somewhere the variables are not getting set correctly

Here is my aspx code :

<%@ Page Language="C#"  MasterPageFile="~/MasterPage2.master" AutoEventWireup="true" CodeBehind="A.aspx.cs" Inherits="A" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<%@ MasterType VirtualPath="~/MasterPage2.master" %>

<asp:Content ID="Content2" ContentPlaceHolderID="CP1" runat="Server">


<meta http-equiv="Pragma" content="nocache">
<meta http-equiv="Expires" content="-1">
<title>Account Exception Upload</title>
<%--<script type="text/javascript" src="ccr_scripts.js"></script>--%>
<script type="text/javascript" src="/apps/jfunctions.js"></script>
<script type="text/javascript" src="/apps/jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="/apps/commonStyles.css" />

<script type="text/javascript">

var timerID = -1;

function cancelProcessing()
{
	if (confirm("Are you 

Open in new window

0

ASP.NET

125K

Solutions

28K

Contributors

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications