How can load file into file component from aspx.cs class? - c#

I'm building a simple page with ASPX.
In this page I display a file component. With this component, the user can select a local file:
<div class="row">
<form class="form-horizontal">
<div class="form-group">
<input type="file" id="selectFile" >
</div>
</form>
</div>
Now, I want to set this file programmatically. So from my Default.aspx.cs code I have this:
protected void Page_Load(object sender, EventArgs e)
{
String s = Request.QueryString["idEsame"];
//RECUPERO IL FILE ED IL PATH DEL FILE
string[] fileEntries = Directory.GetFiles("C:\\Users\\michele.castriotta\\Desktop\\deflate_tests");
foreach (string fileName in fileEntries)
{
// here i need to compare , i mean i want to get only these files which are having these type of filenames `abc-19870908.Zip`
if(fileName == "file")
{
}
}
}
Now if the filename is "file" then I want to load automatically this file on the page.
how can I do this?

STEP1: IN THE PAGE ( sample.aspx)
INSERT THE FOLLOWING CODE:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="sample.aspx.cs" Inherits="sample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Select File:
<asp:FileUpload ID="FileUploader" runat="server" />
<br />
<br />
<asp:Button ID="UploadButton" runat="server" Text="Upload" OnClick="UploadButton_Click" /><br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
</form>
</body>
</html>
STEP2:
in the code page say for example ( sample.aspx.cs)
INSERT THE FOLLOWING CODE:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
try
{
FileUploader.SaveAs(Server.MapPath("confirm//") +
FileUploader.FileName);
Label1.Text = "File name: " +
FileUploader.PostedFile.FileName + "<br>" +
FileUploader.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUploader.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}

If your pattern is "{3 letter}-{8 numbers}.{Zip}", you can simply filter the files using .Where(f => myRegex.IsMatch(f)):
RegexOptions options = RegexOptions.IgnoreCase;
string pattern = #"^\w{3}-\d{8}\.zip$";
string directoryPath = "C:\\Users\\michele.castriotta\\Desktop\\deflate_tests";
var fileEntries = Directory.GetFiles(directoryPath).Where(f => myRegex.IsMatch(f));
foreach (string fileName in fileEntries)
{
// Process
}

Related

i am trying to run a asp.net method with an html submit button but method would not run?

I want the method submit_click to be activated when the submit button on the HTML part is pressed
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" method="post" onsubmit="Submit_Click">
mail<br />
<asp:TextBox ID="mail" runat="server" Style="margin-left: 0px">mail</asp:TextBox>
<br />
name<br />
<asp:TextBox ID="name" runat="server" Width="117px">name</asp:TextBox>
<br />
last
<br />
<asp:TextBox ID="last" runat="server">name</asp:TextBox>
<p>
pass
</p>
<p>
<asp:TextBox ID="password" runat="server">password</asp:TextBox>
</p>
id <p>
<asp:TextBox ID="id1" runat="server">id</asp:TextBox>
</p>
<input id="Submit" type="submit" value="submit" onserverclick="Submit_Click()" />
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data source = " + Server.MapPath("") + "\\Database.accdb");
conn.Open();
string com = "INSERT into myusers (myid,myname,mymail,mypass,mylast) VALUES ('" + id1.Text + "," +name.Text + "," + mail.Text + "," +password.Text + "," + last.Text + "')";
OleDbCommand comm = new OleDbCommand(com, conn);
comm.ExecuteNonQuery();
conn.Close();
}
}
Actually why you're doing this , that i don't know because Asp Button will also converted like below on browser side, Still if you want to use it put runat="server", try below code.
<input id="Submit" runat="server" type="submit" value="submit" onserverclick="Submit_ServerClick" />
You are missing 'runat="server"'. Include it in the submit control.

Asp.net ListBox OnSelectedIndexChanged not firing

I created ListBox, set AutoPostBack="true" and enableEventValidation="false". When I click on any item in my ListBox, nothing changes despite OnSelectedIndexChange event. I set the message "Hello" must pop out OnSelectedIndexChanged but that does not happend.
WebForm1.aspx
<%# Page Language="C#" enableEventValidation="false" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="235px" Width="436px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
</form>
</body>
</html>
WebForm1.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient();
localhost.WebService1 asd = new localhost.WebService1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> igralci = new List<string>();
foreach (localhost.Igralec ig in asd.vrniVseIgralce())
{
igralci.Add(ig.id + ", " + ig.ime + ", " + ig.priimek + ", " + ig.letoRojstva + "\n");
}
ListBox1.DataSource = igralci;
ListBox1.DataBind();
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}

The name 'UName' does not exist in the current context

When trying to register to my database I am receiving the "The name 'UName' does not exist in the current context" error.
Register.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Registration Page</title>
</head>
<body>
<p>This is the registration page</p>
Home | Register
<form id="form1" runat="server">
<div>
<p>Enter First Name :</p>
<p>
<asp:TextBox ID="UName" runat="server" Width="271px"></asp:TextBox>
</p>
<p>
<asp:Button ID="registerButton" runat="server" Text="REGISTER" OnClick="registerEventMethod" />
</p>
</div>
</form>
</body>
</html>
Register.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Register : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO jamieobr_obecarrentals.users (Forename)" +
"VALUES('" + UName.Text + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
why am I getting this error? I have tried several solutions and all failed.
So I solved my own issue, the first initial issue was that I tried copying the .aspx file into a new solution, however this did not copy along the .aspx.designer.cs file therefore causing the problem.
However after trying to re write a fresh version manually which had a designer file with it I forgot to include the .cs file into the namespace of my solution therefore then generating a new problem.
However after including the .cs file into the namespace, hey presto, it worked!

I need to check whether the data entered in form exists in database or not and if it exists redirect it to another page

My short query is that i need to check the login form data that the value entered in name by user to be checked against all the values under column name in the database using LINQ query expression only and if it exists i want to select that particular row to which the name field matches with and redirect the user to another Dashboard page.
Below is the code which stores and selects the row if the record is found in the database into a variable query.Now it's not able to check whether the variable in query points to any row if selected or not of the database table.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SessionHandling.aspx.cs" Inherits="WebApplication5.SessionHandling" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
THIS IS LOGIN FORM
</h1>
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
<br />
E-mail:
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class SessionHandling : System.Web.UI.Page
{
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
tblContact tb = new tblContact();
var query = from x in db.tblContacts where x.name == txtName.Text select x;
}
}
}
Did you try this from your C# code?
if (query.Any())
{
Response.Redirect("http://www.microsoft.com")
}
else
{
Response.Redirect("http://www.google.com")
}

Get variable info from PowerShell to asp.net page

I'm currently working on a test asp.net page that will run a PowerShell script on a server.
The PowerShell script checks to see if a users input which I stored in variable $userinput, matches the variable $name.
I have managed to get variables over to the PowerShell script from the asp.net page. The Default.aspx.cs script does a find and replace on userinput and then saves the script as a modified version.
I would like to print out on the asp.net page the variable $result from the PowerShell script. I have defined an output label on the asp.net page called Output.
However when ran, the label does not display the information from the variable $result.
Thanks in advance
Test.ps1
$name = "test"
$userinput = "*userinput*"
if(($userinput) -eq $name)
{
$result = "Name $userinput already taken!"
}
else
{
$result = "Name $userinput availble!"
}
Default.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Compliant Cloud</title>
<link rel="stylesheet" href="stylesheets\style.css" type="text/css" />
</head>
<body>
<div id="logo">
<img src="images\logo.png" alt="logo" height="100" width="250"/>
</div>
<form id="form1" runat="server">
<table>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td>Enter Application Name</td></tr>
<tr><td>
<br />
</td><td>
<asp:TextBox ID="Input" runat="server" TextMode="SingleLine" Width="200px" Height="20px" ></asp:TextBox>
<asp:Label ID="Output" runat="server" Text="Output Text" Width="300px" Height="20px" ></asp:Label>
</td></tr>
<tr><td>
</td><td>
<asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />
</td></tr>
</table>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;
using System.IO;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExecuteCode_Click(object sender, EventArgs e)
{
// Clean the Result label
Output.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
string strContent = null;
using (StreamReader objReader = new StreamReader("C:\\Users\\sysadmin\\Desktop\\Test.ps1"))
{
strContent = objReader.ReadToEnd();
}
strContent = strContent.Replace("*userinput*", Input.Text);
File.WriteAllText("C:\\Users\\sysadmin\\Desktop\\Test_modified.ps1", strContent);
//this.executePowerShellCode(strContent);
// Add the script to the PowerShell object
shell.Commands.AddScript("C:\\Users\\sysadmin\\Desktop\\Test_modified.ps1");
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
Output.Text = Server.HtmlEncode(builder.ToString());
}
//string url = "testpage.html";
// Response.Redirect(url);
}
}
}

Categories

Resources