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);
}
}
}
Related
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
}
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")
}
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.
I have the following aspx and cs
<%# Page Language="C#" AutoEventWireup="true" CodeFile="cardPrintingBarcode.aspx.cs" Inherits="Reports_cardPrintingBarcode" %>
<!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>
ImpresiĆ³n de Tarjeta
</title>
<style type="text/css">
.style2
{
font-size: xx-small;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="Card">
<table>
<tr>
<td width="85px" align="center" valign="bottom">
<image ID="imgBarcode" Width="85px" Height="20px" />
<br />
<label ID="lblCardcode" Font-Bold="True" Font-Names="Arial" Font-Size="5pt" >
</label>
</td>
<td width="30px" />
<td width="40px" align="center" valign="bottom">
<label ID="lblCN" Font-Bold="True" Font-Names="Arial" Font-Size="7pt">
</label>
<br />
<image ID="imgQR" Width="37px" Height="37px" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
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;
using ClubCard.Core;
public partial class Reports_cardPrintingBarcode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["CHECKED_CARDS_ITEMS"] != null)
{
if (((List<int>)ViewState["CHECKED_CARDS_ITEMS"]).Count > 0)
{
LoadCards();
}
else
{
this.Response.Redirect("~/default.aspx");
//GET ME OUT OF HERE
}
}
}
private void LoadCards()
{
List<int> lstIdCards = (List<int>)ViewState["CHECKED_CARDS_ITEMS"];
foreach (int intIdCard in lstIdCards)
{
//Process Where I Want To Assign Data To 2 Labels and 2 images
ClubCard.Core.Card card = new ClubCard.Core.Card(intIdCard);
ClubCard.Core.Client client = new ClubCard.Core.Client(card.idClient);
Byte[] bcQR = QR.GetQRByteArray(card.cardCode);
string strBase64 = Convert.ToBase64String(bcQR, 0, bcQR.Length);
//lblCN.Text = client.number;
//lblCardCode.Text = card.number;
//imgBarcode.ImageUrl = "SOME URL";
//imgQR.ImageUrl = "SOME URL";
//PROBABLY HERE'S WHERE I HAVE TO CREATE ALL WEBCONTROLS...
//THEN WHEN THE FOREACH STARTS AGAIN, CREATE ANOTHER ONE...
}
}
}
The point here is to create the table seen in the aspx as many times as the (List)ViewState["CHECKED_CARDS_ITEMS"]).Count.
For instance... if (List)ViewState["CHECKED_CARDS_ITEMS"]).Count = 5, then I want to see the table and all of it's content 5 times (obviously, each will be different because server side I'm assigning different data to each, thus, the use of the foreach)
How can I clone those WebControls?
I've heard that I must not use runat="server" on those controls (however I'm not sure if in this example will work), some other sources claim that it should be inside a div, and clone the div.
You probably needs a ListControl e.g. <asp:DataList />, <asp:GridView etc.
Create a list of your cards
List<ClubCard.Core.Card> cards = new List<ClubCard.Core.Card>();
//cards.Add(...some cards...);
//cards.Add(...some cards...);
//cards.Add(...some cards...);
Bind your list to a ListControl
cardListControl.DataSource = cards;
cardListControl.DataBind();
Implementing this with a DataList:
<asp:DataList runat="server" ID="cardListControl">
<ItemTemplate>
<!-- Layout to display card here -->
<img src='<%# Eval("CardImageUrl")>' />
<span><%# Eval("CardName") %></span>
<!-- other card information -->
</ItemTemplate>
</asp:DataList>
DataList has a RepeatDirection property that let you display your cards Horizontally or Vertically
before I begin, there is another question with a similar title and it is unsolved but my situation is pretty different since I am using Ajax.
I recently added a label to my Ajax UpdateProgress control and for some reason my asp.net page is not reading it. My original goal was for the text of the label to be constantly be updating while the long method runs. I am using code behind, and I believe the label is declared. I will post my .cs page if anyone would like to read through it (its not too long), All my other labels work perfectly and even if I take the label OUT of the ajax control it will work fine (not the text updates though). Is there a certain Ajax label I need to use?
Im pretty confused why the error is occurring. The exact error message states : "The name 'lblProgress' does not exist in the current context. Im using c#, ajax controls, a asp.net page, and visual studio. This program uploads a file to a client and stores the information in a database. If anyone can help I would really appreciate it. Thanks in advance!
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Threading;
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
lblProgress.Visible = true;
lblProgress.Text = "Preparing System Checks...";
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
lblProgress.Text = "Locating Files...";
//bf.ReadyFilesForTransmission();
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
lblProgress.Text = "Sending Files to Kaplan...";
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
lblProgress.Text = "Uploading File Info to Database...";
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = true;
SuccessLabel.Visible = false;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
Here is my aspx code as well.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SendOrders.aspx.cs" Inherits="SendOrders" %>
<!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>Kaplan EDI Manager</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 220px;
height: 19px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="mainPanel">
<div>
<h3>Number of Batches Created Today: <asp:Label runat="server" style="display:inline;" ID="BatchesCreatedLbl"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<span class="red">COUNTDOWN TO SUBMISSION!</span>
<span id="timespan" class="red"></span>
</h3>
</div>
<div id="batchestoprocessdiv">
</div>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="BatchesToProcessLbl" runat="server" CssClass="green"
Height="22px" Text="THERE IS AN ORDER BATCH TO PROCESS."></asp:Label>
<asp:Label ID="NoBatchesToProcessLbl" runat="server" CssClass="red"
Text="There are no Order Batches to Process." Visible="false"></asp:Label>
<asp:Button ID="PutFTPButton" runat="server" onclick="Button_Click"
Text="Submit Orders" />
<asp:Label ID="SuccessLabel" runat="server" CssClass="green"
Text="Batch has been processed and uploaded successfully." Visible="false"></asp:Label>
<asp:Label ID="ErrorLabel" runat="server" CssClass="red" Text="Error: "
Visible="false"></asp:Label>
<asp:Label ID="lblProgress" runat="server" CssClass="green" Height="16px"
Text="Label" Visible="False"></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<br />
<img alt="" class="style1" src="images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</div>
<div id="OrdersInfoDiv" runat="server" visible="false">
<asp:GridView ID="BatchDetails" Caption="Details of orders ready to be sent" runat="server" AutoGenerateColumns="true"
CssClass="InfoTable" AlternatingRowStyle-CssClass="InfoTableAlternateRow" >
</asp:GridView>
</div>
<div id="OrdersSentDiv" class="mainPanel" runat="server" visible="false">
<h4>Sent Orders</h4>
</div>
</form>
<script src="js/SendOrders.js" type="text/javascript"></script>
</body>
</html>
If the Label is created inside the UpdateProgress control, then you will need to do something like this
((Label)upUpdateProgress.FindControl("lblProgress")).Text = "Uploading File...";
If the control is declared in markup and the code-behind doesn't recognize it, then your designer.cs file is probably out of sync. There are a few ways to fix this:
Close the form and reopen it, and remove and add lblProgress again
Add the Label to the designer.cs file manually
Here's how to add it manually:
/// <summary>
/// lblProgress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProgress;
EDIT
Just noticed that you're putting the UpdatePanel in an UpdateProgress control, in which case you'll need to reference it using FindControl (like #Valeklosse) suggested.