Fatal error encountered during program execution in c# asp.net - c#

Here i am trying to insert values from form to database.when i fill in the form and hit submit, i am getting a error window saying fatal error encountered during program execution.
here is my code.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
public partial class dashboard : System.Web.UI.Page
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submit_Click(object sender, EventArgs e)
{
var b = RadioButtonList1.SelectedItem.ToString();
try
{
conn.Open();
MySqlCommand cmdo = new MySqlCommand("Insert into application (applicant_fullname,applicant_age,applicant_dob,applicant_gender,applicant_residential_address) values (#Name,#password,#Email)", conn);
cmdo.Parameters.Clear();
cmdo.Parameters.AddWithValue("#fullname", fullname.Text);
cmdo.Parameters.AddWithValue("#age", age.Text);
cmdo.Parameters.AddWithValue("#dob", dateofbirth.Text);
cmdo.Parameters.AddWithValue("#gender",b);
cmdo.Parameters.AddWithValue("#resident", resident.Text);
cmdo.ExecuteNonQuery();
cmdo.Parameters.Clear();
cmdo.Dispose();
ShowMessage("Registered successfully......!");
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
finally
{
conn.Close();
}
}
void ShowMessage(string msg)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
}
}
asp code:
<form id="form1" runat="server">
<table class="applytable">
<tr><td>Full name</td><td><asp:TextBox ID="fullname" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Age</td><td><asp:TextBox ID="age" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Date Of Birth</td><td><asp:TextBox ID="dateofbirth" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Gender</td><td><asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Value="Male"></asp:ListItem>
<asp:ListItem Value="Female"></asp:ListItem>
</asp:RadioButtonList></td></tr>
<tr><td>Residential Address</td><td><asp:TextBox id="resident" TextMode="multiline" Columns="50" Rows="5"
runat="server" Height="58px" Width="194px" /></td></tr>
<tr><td>Permanant Address</td><td><asp:TextBox id="permenant" TextMode="multiline" Columns="50" Rows="5"
runat="server" Height="68px" Width="192px" /></td></tr>
<tr><td>Parent/Guardian name</td><td><asp:TextBox ID="parentname" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>E-mail Address</td><td><asp:TextBox ID="emailid" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td>Phone Number</td><td><asp:TextBox ID="phoneno" runat="server" Height="25px" Width="155px"></asp:TextBox></td></tr>
<tr><td></td><td><asp:Button ID="submitpage1" runat="server"
onclick="submit_Click" Text="Submit" /></td></tr>
</form>
How can i solve this? what am i doing wrong here?

I can clearly see your insert query is wrong.Your column and values does not match.
So I would recommend to run that query in mysql editor first to check insert query works.
Moreover you are adding values in parameter which are not mentioned in your queries.

Related

FileUpload1 does not exist in current context

I'm trying to create a site that allows the user to upload a song and download any song that was uploaded. I'm using MySQL to store any uploaded song. I think I have the HTML and C# code right but it keeps throwing me an error saying FileUpload1 does not exist in the current context, you can use a navigation bar to switch context. My C# code is as follows.
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.IO;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = "server=localhost;user id=root;database=music;persistsecurityinfo=True";
using (MySqlConnection con = new MySqlConnection(strConnString))
{
using (MySqlCommand command = new MySqlCommand())
{
con.Open();
string SQL = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
command.CommandText = SQL;
command.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
command.Parameters.AddWithValue("#ContentType", "audio/mpeg3");
command.Parameters.AddWithValue("#Data", bytes);
command.Connection = con;
command.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Here is my HTML for the site:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Music.aspx.cs" Inherits="Default3" %>
<asp:Content ID="music" runat="server" ContentPlaceHolderID ="ContentPlaceHolder1">
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click"/>
<hr/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" RowStyle-BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="FileName"/>
        <asp:TemplateField>
            <ItemTemplate>
                <object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
                    width="240" height="20" id="dewplayer">
                    <param name="wmode" value="transparent"/>
                    <param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
                </object>
            </ItemTemplate>
       </asp:TemplateField>
        <asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download"/>
   </Columns>
</asp:GridView>
</asp:Content>
Your code behind defines a partial class "Default3". I assume your aspx page is named "Default3", and visual studio has generated the code to instantiate the elements in that aspx page. That generated code is also a partial class "Default3", but you will notice in that generated code, that the partial class is defined under a namespace. Your code behind does not define the rest of that class under any namespace, so it does not have access to the same objects. Looks like at some point you deleted the namespace specification out of your code behind.

Issue in parsing HTML table to ASP.NET

I am using HtmlAgilityPack to parse a table on html page to ASP.NET but I am getting exception every time.
Code for ASP.NET Page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="httprequest_web.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<hr />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" MaxLength="6" TextMode="Number"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label3" runat="server" Text="Label" Visible="False"></asp:Label>
<hr />
<br />
<asp:Label ID="Label4" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
</div>
</form>
</body>
</html>
CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using HtmlAgilityPack;
namespace httprequest_web
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Text = "Train Running Status/ JSON Output";
Label2.Text = "Please enter Train No.:";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Generation of HTTP request from the train number specified in text box.
try
{
Label3.Visible = false;
//get request
string base_url = "http://railenquiry.in/runningstatus/";
string url_request = string.Concat(base_url, TextBox1.Text);
//using HtmlAgilityPack
WebClient rq = new WebClient();
string getdata = rq.DownloadString(url_request);
HtmlAgilityPack.HtmlDocument rec_data = new HtmlAgilityPack.HtmlDocument();
rec_data.LoadHtml(getdata);
List<List<string>> table = rec_data.DocumentNode.SelectSingleNode("//table[#class='table table-striped table-vcenter table-bordered table-responsive']")
.Descendants("tr").Where(tr => tr.Elements("td").Count() >= 1).Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList()).ToList();
}
catch
{
Label3.Visible = true;
Label3.Text = "Something went wrong. Please try again!";
}
}
}
}
HTML Page Source: Click Here
I am trying to parse running status information to display it on my webpage but every time I am getting an null object exception. Please tell me where I am doing it wrong. Thanks in advance!
HttpClient client = new HttpClient();
var html = await client.GetStringAsync("http://railenquiry.in/runningstatus/12736");
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
//Same as in your question
var table = doc.DocumentNode.SelectSingleNode("//table[#class='table table-striped table-vcenter table-bordered table-responsive']");
var result = table.Descendants("tr")
.Select(tr => tr.Descendants("td").Select(td => td.InnerText).ToList())
.Skip(1) //Skip headers
.Where(x => x.Count==11) //Skip the footer row
.ToList();
result will be List<List<string>> as you expect in your question.

How I can execute C# code using Roslyn in ASP.Net web form?

I have peice of code in ASP.Net for execute code of C# using roslyn compiler. However, I use ASP.Net web forms to build user interface for execute the code. So,I want to take code from one textbox and by "Compile" button I show the result in another textbox.
So, I have this controls:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Compiler Tool</h1>
</hgroup>
<p>
You can compile your source code of C# using Roslyn Compiler from Microsoft</p>
<br/>
<p>
<asp:TextBox ID="TextBox3" runat="server" Height="185px" Width="480px" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button2" runat="server" onclick="Button_Click" Text="Compile" ForeColor="Black" />
</p>
<p>
<asp:TextBox ID="TextBox2" runat="server" Height="138px" Width="390px" ></asp:TextBox>
</p>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
</asp:Content>
And here the Handler event for it using C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
var engine = new ScriptEngine();
var session = engine.CreateSession();
String code = TextBox3.Text;
session.Execute(code);
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
}
}
How could I show the result of execution of Code (TextBox3) in TextBox2??
Iam beginner in ASP.Net environment, Any help??
I'm afraid I'm not near a dev pc, so I can't test the code, but here's what comes to mind:
You're not using the result of session.Execute(code);, so if a user were to put in 3+3, it would get executed, and the return value would be 6, but since it's not captured, it simply would go out of scope. If instead, you did object result = session.Execute(code);, the output would be the integer 6; You could then call .ToString() on result and put that in your text box.
And of course be careful allowing users to execute arbitrary code on your webserver...

How to add controls to datalist in code behind, not in aspx design?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWeb.Data;
using MyWeb.Common;
using MyWeb.Business;
using AjaxPro;
using System.Text;
<asp:DataList ID="DataList1" runat="server" RepeatLayout="Flow">
<ItemTemplate>
<div class="m_status">
<div class="ava">
<a href="#">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("AvatarUS") %>'
CssClass="ava_medium"/></a>
</div>
<div class="sta_content">
<div class="sta_title">
<p class="sta_detail">
<asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Detail") %>'></asp:Literal>
</p>
<div class="function">
<a class="sta_like left" href="#">Thích</a>
<a class="sta_cmt left" href="#">Bình luận</a>
<a class="sta_share left" href="#">Chia sẻ</a>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:DataList>
I want to add a DataList like that in code behind(Default.aspx.cs)
How to make it?
In the row databound event of the data list you can add some control that will hold the place for the control that you want to add, example:
In the ItemTemplate add one control to hold the control that will be addeded.
<asp:Panel runat="server" ID="pnlPlaceHolder">
<!-- the control will be added here -->
</asp:Panel>
and in code behind, on RowDataBound of the data list do the following
Panel pnlPlaceHolder = (Panel)e.Item.FindControl("pnlPlaceHolder");
if (pnlPlaceHolder!= null)
{
// The new control, a button, by example
Button btn = new Button();
btn.Text = "Added dinamically";
pnlPlaceHolder.Controls.Add(btn);
}
This is it.
Problem when I add in code behide: Default.aspx.cs
namespace KetBanBonPhuong
{
[AjaxPro.AjaxNamespace("Default")]
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Default1));
if(!isPostBack)
{
DataList dl = new DataList();
dl.DataSource = GetList();
dl.DataBind();
this.liststatus.Controls.Add(dl);
dl.DataSource = GetList();
dl.RepeatLayout = RepeatLayout.Flow;
Literal ltr = new Literal();
ltr.Text = "kaldfs";
dl.Controls.Add(ltr);//Error here
}
}
}

how to display database information (evals? labels? literals?)

I have the following asp.net page
<form id="form1" runat="server">
<asp:Button id="display_button" runat="server" Text="Display" OnClick="Button1_Click" />
<asp:Button id="edit_button" runat="server" Text="Edit" OnClick="Button2_Click" />
<asp:Button id="save_button" runat="server" Text="Save" OnClick="Button3_Click" Visible="false" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View id="View1" runat="server">
<asp:FormView id="view_program" runat="server">
<ItemTemplate>
<tr>
<td class="add_border_bold" nowrap">Status</td>
<td width="100%" class="add_border">
<img src="images/<%# Eval("status").ToString().Trim() %>_light_16.gif" alt="status" />
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap">Short Title</td>
<td width="100%" class="add_border">
<%# Eval("short_title") %>
</td>
</tr>
</ItemTemplate>
</asp:FormView>
</asp:View>
<asp:View id="View2" runat="server">
<asp:FormView id="edit_program" runat="server">
<ItemTemplate>
<tr>
<td class="add_border_bold"nowrap">Status </td>
<td width="100%" class="add_border">
<asp:DropDownList id="p_status" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap">Short Title</td>
<td width="100%" class="add_border">
<asp:TextBox runat="server" id="short_title" />
</td>
</tr>
</ItemTemplate>
</asp:FormView>
</asp:View>
</form>
with the following code behind page
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
namespace TM_non_deploy
{
public partial class Program : System.Web.UI.Page
{
protected Label Label1;
protected Person myPerson;
protected TestProgram myProgram;
List<TestProgram> program = null;
protected void Page_Load(object sender, EventArgs e)
{
try
{
myPerson = new Person("user");
myProgram = new TestProgram("999");
//needs to be done to refresh info on page
program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
if (!IsPostBack)
{
//create controls and bind data
edit_program.DataSource = program;
edit_program.DataBind();
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
p_status.Items.Add(new ListItem("Green"));
p_status.Items.Add(new ListItem("Yellow"));
p_status.Items.Add(new ListItem("Red"));
p_status.SelectedValue = myProgram.Status.Trim();
TextBox short_title = edit_program.FindControl("short_title") as TextBox;
short_title.Width = 200;
short_title.Text = myProgram.Short_Title.Trim();
}
}
catch (Exception ex)
{
Response.Write(ex);
Label1.Text = ex.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
save_button.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DropDownList c_status = edit_program.FindControl("p_status") as DropDownList;
myProgram.Status = c_status.SelectedValue;
bool update = myProgram.SaveTestProgram();
if (update)
{
Label1.Text = "Saved!";
//needs to be done to refresh info on page
program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
else
{
Label1.Text = "Error Saving";
}
}
}
}
basically, it is one page that both displays the fields, and then on a button click displays the editable version of all those fields. my question is, should i be displaying all of the information like i am now, with evals? or should i switch to labels, or literals, or something else entirely? i want to know before i get too far and have to undo a lot of work.
there will end up being a ton of fields on this page, all types from checkboxes to dropdowns to multiline textboxes, so i want to make sure i pick the path that works best for displaying all of those different kinds of data, even though in this example i am only displaying small text information.
If you just need to display text, there's no reason not to just use your <%# Eval("title") %>
One thing that should be noted though, is that it's better to cast your DataItem and access the properties that way instead of Eval as Eval has to use reflection and is more costly (maybe to the being of actually being noticeable if you have a lot of stuff repeated).
Use: <%# (Container.DataItem as SomeObject).Title %> instead of <%# Eval("Title") %>
Kind of outside the scope of your question but just a side note. :)
I wouldn't go for ServerSide Controls (Labels/Literals) unless you need formatting or to change the control values in other server side events. They just add to ViewState (unless ViewState is disabled on those Controls).
Coming to whether it's the right approach, I would suggest you use EditItemTemplate of FormView instead of 2 FormViews in Different Views & a MultiView Control!

Categories

Resources