Binding output from powershell script to gridview in asp.net c# - c#

I'm very new to c# and I expect what I'm trying to do is quite simple-ish but I'm not able to find or follow other examples where output from a powershell array populates a gridview for further manipulation / execution of another script. The process on page load is to run a powershell script, which creates an array of session details which populate a gridview. A second script can then be initiated to interact wit that session (e.g. force a logoff) by way of selection of the gridview row.
Using other examples I have managed to initiate the first powershell execution, which throws the data to a form via:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<h1>PowerShell Harness<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
</h1>
<asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="1000px" Height="400px" runat="server"></asp:TextBox>
</div>
</asp:Content>
CodeBehind
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;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
Label1.Text = User.Identity.Name;
else
Label1.Text = "No user identity available.";
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
// shell.Commands.AddScript(Input.Text);
// shell.Commands.AddScript("D:\\Local_Scripts\\sessioncall.ps1");
shell.Commands.AddCommand("c:\\Local_Scripts\\sessioncall.ps1");
// Add Params
// shell.Commands.AddParameter(null,User.Identity.Name);
// shell.Commands.AddParameter("Username", Label1.Text);
shell.Commands.AddArgument(User.Identity.Name);
// 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 < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
}
}
}
Sessioncall.ps1
$SessionUser = "$($args[0])"
set-brokersite -AdminAddress UKSite
$a = #(Get-BrokerSession -BrokeringUserName $SessionUser | Select-Object UserFullName, BrokeringTime, ClientName,DesktopGroupName, sessionstate, uid, machinename,#{Name='ENV';Expression={'UK'}})
#Pull US Sessions into array
Set-brokersite -AdminAddress USSite
$a += #(Get-BrokerSession -BrokeringUserName $SessionUser | Select-Object UserFullName, BrokeringTime, ClientName,DesktopGroupName, sessionstate, uid, machinename,#{Name='ENV';Expression={'US'}})
If ($a -ne $null){
Write-Output $a | out-string
}
Else {
Write-Output "No User session! Username was $SessionUser"
}
Currently the output is thrown to the textbox as an out-string. I'm struggling in even how to start to data-bind that array output as rows within a gridview. Just need a little hand-holding to get this started!
Thanks in advance!
Paul.

It's been a while since I've dabbled with WebForms, but I found a way to do what you're after...
First off, let's change your PowerShell script slightly. Rather than return a string (which is what | out-string is doing), we can simply return the objects. The shell.Invoke() method in the C# code knows how to extract fully-fledged objects from the output of the script so we don't need to serialize to a string inside the PowerShell script and then try to deserialize that again back to objects inside our C# code.
Ignoring your line-of-business logic for a minute, my script simply returns an array of PSCustomObjects and looks like this:
MyScript.ps1
write-output #(
(new-object PSCustomObject -Property ([ordered] #{
"MyProperty1" = "MyValue1.1"
"MyProperty2" = "MyValue2.1"
"MyProperty3" = "MyValue3.1"
})),
(new-object PSCustomObject -Property ([ordered] #{
"MyProperty1" = "MyValue1.2"
"MyProperty2" = "MyValue2.2"
"MyProperty3" = "MyValue3.2"
}))
);
Now, my C# Page_Load method does this:
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Initialize PowerShell engine
var powershell = PowerShell.Create();
// Add the script to the PowerShell object
var script = "c:\\temp\\MyScript.ps1";
powershell.Commands.AddCommand(script);
// Execute the script
var results = powershell.Invoke();
...
and results contains a System.Collections.ObjectModel.Collection<PSObject>. We can't databind that directly to a GridView because the properties are tucked away inside key-value pairs in the Properties member of each PSObject, but if we create a new class it's pretty easy to extract the values into something we can databind:
MyClass.cs
public class MyClass
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public string MyProperty3 { get; set; }
}
and our Page_Load can convert the PSObjects into instances of this class:
Default.aspx.cs
...
var objects = results.Select(
r => new MyClass
{
MyProperty1 = (string)r.Properties["MyProperty1"].Value,
MyProperty2 = (string)r.Properties["MyProperty2"].Value,
MyProperty3 = (string)r.Properties["MyProperty3"].Value,
}
);
this.ResultGrid.DataSource = objects;
this.ResultGrid.DataBind();
}
Then, to display the data you just need a GridView added to your Default.aspx with whatever columns and formatting you want defined:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<h1>PowerShell Harness<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label></h1>
<asp:GridView ID="ResultGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="MyProperty1" HeaderText="My Property 1" />
<asp:BoundField DataField="MyProperty2" HeaderText="My Property 2" />
<asp:BoundField DataField="MyProperty3" HeaderText="My Property 3" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
Run that and you should see something like this on the page:
Note
You might find your Get-BrokerSession cmdlet returns a collection of a specific type of object already rather than PSCustomObject, in which case you could possibly skip the conversion step and databind directly to the results object, so you might have to play with that to see. Hopefully the above will give you some pointers if there are any differences.
Hope this helps.

Many thanks for the guidance. Gridview now populates.
protected void Page_Load(object sender, EventArgs e)
{
// Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
Label1.Text = User.Identity.Name;
else
Label1.Text = "No user identity available.";
// Clean the Result TextBox
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
// shell.Commands.AddScript(Input.Text);
// shell.Commands.AddScript("D:\\Local_Scripts\\sessioncall.ps1");
shell.Commands.AddCommand("c:\\Local_Scripts\\sessioncall.ps1");
// Add Params
// shell.Commands.AddParameter(null,User.Identity.Name);
// shell.Commands.AddParameter("Username", Label1.Text);
shell.Commands.AddArgument(User.Identity.Name);
// 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 results2 = shell.Invoke();
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
var UserFullName = (psObject.Members["UserFullName"]);
var BrokeringTime = (psObject.Members["BrokeringTime"]);
var ClientName = (psObject.Members["ClientName"]);
var DesktopGroupName = (psObject.Members["DesktopGroupName"]);
var SessionState = (psObject.Members["SessionState"]);
var Uid = (psObject.Members["Uid"]);
var MachineName = (psObject.Members["MachineName"]);
var ENV = (psObject.Members["ENV"]);
// builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
this.ResultGrid.DataSource = results2;
this.ResultGrid.DataBind();
}
}
Returns
[![enter image description here][1]][1]
However this method throws an exception error when you then define a datakeyname.
<asp:GridView ID="ResultGrid" runat="server" DataKeyNames="uid" AutoGenerateColumns="False" OnSelectedIndexChanged="ResultGrid_SelectedIndexChanged">
<Columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="View"
text="View"/>
<asp:BoundField DataField="UserFullName" HeaderText="UserFullName" />
<asp:BoundField DataField="BrokeringTime" HeaderText="BrokeringTime" />
<asp:BoundField DataField="ClientName" HeaderText="ClientName" />
<asp:BoundField DataField="DesktopGroupName" HeaderText="DesktopGroupName" />
<asp:BoundField DataField="SessionState" HeaderText="SessionState" />
<asp:BoundField DataField="Uid" HeaderText="Uid" />
<asp:BoundField DataField="MachineName" HeaderText="MachineName" />
<asp:BoundField DataField="ENV" HeaderText="ENV" />
</Columns>
</asp:GridView>
code behind
protected void ResultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
// Determine the RowIndex of the Row whose Button was clicked.
//int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;
String key = ResultGrid.SelectedDataKey.Value.ToString();
//Get the value of column from the DataKeys using the RowIndex.
//int id = Convert.ToInt32(ResultGrid.DataKeys[rowIndex].Values[01]);
// Response.Write("IM_RAA_657x_Date.aspx?Day=" + ResultGrid.SelectedDataKey.Value(0) + "&BusinessCategory=" + ResultGrid.SelectedDataKey.Values(1).ToString())
}
This throws an exception error at
this.ResultGrid.DataBind();
"System.Web.HttpException: 'DataBinding: 'System.Management.Automation.PSObject' does not contain a property with the name 'uid'.'"
I'm not clear if the method is now the issue or something outside of that. I'm confused as it must see inside PSObjects correctly in order for the variables to be defined and populate the gridview?! Hmm.
Wow; OK; I just realised this entire section is ignored! Case in point; it can be commented out! So clearly adjust the output from the powershell script!
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
//var UserFullName = (psObject.Members["UserFullName"]);
//var BrokeringTime = (psObject.Members["BrokeringTime"]);
//var ClientName = (psObject.Members["ClientName"]);
//var DesktopGroupName = (psObject.Members["DesktopGroupName"]);
//var SessionState = (psObject.Members["SessionState"]);
//var Uid = (psObject.Members["Uid"]);
//var MachineName = (psObject.Members["MachineName"]);
//var ENV = (psObject.Members["ENV"]);
// builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
Forgive me but I'm almost there!
r => new MyClass
{
UserFullName = (string)r.Properties["UserFullName"].Value,
BrokeringTime = (DateTime)r.Properties["BrokeringTime"].Value,
ClientName = (string)r.Properties["ClientName"].Value,
DesktopGroupName = (string)r.Properties["DesktopGroupName"].Value,
//SessionState = (string)r.Properties["SessionState"].Value,
Uid = (Int64)r.Properties["Uid"].Value,
//MachineName = (string)r.Properties["MachineName"].Value,
//ENV = (string)r.Properties["ENV"].Value,
}
);
this.ResultGrid.DataSource = objects;
this.ResultGrid.DataBind();
}
}
protected void ResultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write(ResultGrid.SelectedValue.ToString());
}
}
internal class MyClass
{
public string UserFullName { get; set; }
public DateTime BrokeringTime { get; set; }
public string ClientName { get; set; }
public string DesktopGroupName { get; set; }
public String SessionState { get; set; }
public Int64 Uid { get; set; }
public string MachineName { get; set; }
public string ENV { get; set; }
}
So I'm now correctly populating the gridview; Some columns are still being problematic and are not being treated as strings BUT I'm almost there!
Looks like Get-member type:
BrokeringTime NoteProperty datetime BrokeringTime=28/02/2020 06:56:39
ClientName NoteProperty string ClientName=clientname
DesktopGroupName NoteProperty string DesktopGroupName=desktopgroupname
ENV NoteProperty System.String ENV=UK
MachineName NoteProperty string MachineName=machinename
SessionState NoteProperty SessionState SessionState=Active
Uid NoteProperty long Uid=12345678
UserFullName NoteProperty string UserFullName=username
C# Does seem to like system.string.

Related

How to add both input and validation control from codebehind

I am working within a CMS known as RiSE built in iMIS (I don't recommend)
I am building a plugin type thing which will allow the administrator from the backend of the program to build a contact form. (really simple right!?!?!?)
So, I don't know what, or how many form inputs will be present to process.
the process is for each added input
add its "id" to a list to be used when the form is submitted
build the input and add attributes based on administrator selected options
add the validator
The following code is the piece the adds the inputs to the page. The idea is simple, the administrator "creates" the input and chooses their options (name, label, placeholder, readonly, etc)
The codebehind would then take these options and build the input and corosponding input validation control.
I keep getting this error
Unable to find control id 'text_9d8f153' referenced by the 'ControlToValidate' property of 'val_9d8f153'.
here are the files;
EmailFormTextBoxDisplay.ascx
<%# Control Language="C#" AutoEventWireup="True" CodeBehind="EmailFormTextBoxDisplay.ascx.cs" Inherits="EmailForm.EmailFormTextBoxDisplay" %>
<%# Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<%# Register TagPrefix="asiweb" Assembly="Asi.Web" Namespace="Asi.Web.UI.WebControls" %>
<div onprerender="buildMe" runat="server"></div>
EmailFormTextBoxDisplay.ascx.cs
using System
...
protected void buildMe(object sender, EventArgs e)
{
HtmlGenericControl div = (HtmlGenericControl)sender;
if (EmailForm.formProcessed)
{
div.Visible = false;
}
else
{
String id = inputEmailLabel.Replace(" ", "-") + "_" + randId;
// add this input to the list
EmailForm.inputs.Add(new String[]
{
id,
inputType,
inputEmailLabel
});
// if label is not empty, add it
if (inputLabel != "")
{
HtmlGenericControl label = new HtmlGenericControl("label");
label.InnerText = inputLabel + " ";
label.TagName = "label";
div.Controls.Add(label);
}
// build and add the input
HtmlInputGenericControl input = new HtmlInputGenericControl("input");
// get each setting and add attributes to the input
input.Attributes.Add("type", inputType);
input.Attributes.Add("id", id);
input.Attributes.Add("placeholder", inputPlaceholder);
if (inputValue != "") input.Attributes.Add("value", inputValue);
if (inputDisabled) input.Attributes.Add("disabled", "disabled");
if (inputReadOnly) input.Attributes.Add("readonly", "readonly");
if (inputRequired)
{
input.Attributes.Add("required", "required");
AsiRequiredFieldValidator required = new AsiRequiredFieldValidator();
required.ControlToValidate = id;
required.ID = "val_" + randId;
required.Text = "This is Required";
div.Controls.Add(required);
}
if (inputRegEx != "" && inputRegEx != null)
{
AsiRegularExpressionValidator regEx = new AsiRegularExpressionValidator();
regEx.ValidationExpression = inputRegEx;
regEx.ControlToValidate = id;
regEx.ID = "regExVal_" + randId;
regEx.Text = inputRegExMsg;
div.Controls.Add(regEx);
}
div.Controls.Add(input);
}
}
I have tried breaking the validation part out into it's own method, and calling the first part (making the input) onLoad and then adding the validators onPreRender but I get the same error.
I also tried using Control.AddAt(2, input) to ensure the <input /> is before the validator, but to no avail.
How can I build an input & validation dynamically?
You need to use reference the ID generated by aspnet, not the one set by an Attribute. THis is because the ID will be renamed by aspnet client side, so the actual ID in html might become something like this ctl00_PlaceHolder1_myID
HtmlInputGenericControl input = new HtmlInputGenericControl("input");
input.ID = id;
and then the Validator
required.ControlToValidate = input.ID;
You could also use "real" aspnet Controls.
TextBox tb = new TextBox();
tb.ID = "myTextBox" + i;
RequiredFieldValidator val = new RequiredFieldValidator();
val.ControlToValidate = tb.ID;
val.ErrorMessage = "Required field";
Literal lit = new Literal();
lit.Text = "<br>";
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(val);
PlaceHolder1.Controls.Add(lit);
ControlToValidate requires the server side id of the control you want to validate. You will need to set the id of the control like this:
input.ID = "MY_ID";
Then use the inputs id to validate:
required.ControlToValidate = input.ID;

how to get Eval value to string in ItemTemplate

I need to receive data from Eval function to make comparisons, so i've tried this but can't receive anything from Eval, or Bind.
<ItemTemplate>
<%
string auc_id = ((string)Eval("Item_BelongToAuction"));
Guid id = Guid.Empty;
Guid.TryParse(auc_id, out id);
try
{
using (ModeloEntities modelo = new ModeloEntities())
{
var auction_name = (from auctions in modelo.Auctions
where auctions.Auction_ID == id
select auctions).First();
Response.Write(auction_name.Auction_Name);
}
}
catch { }
%>
</ItemTemplate>
Move your logic to the code behind, like this:
protected string GetAuctionName(string auctionId)
{
Guid id = Guid.Empty;
Guid.TryParse(auctionId, out id);
using (ModeloEntities modelo = new ModeloEntities())
{
var auction_name = (from auctions in modelo.Auctions
where auctions.Auction_ID == id
select auctions).First();
return auction_name.Auction_Name;
}
}
<ItemTemplate>
<%# GetAuctionName((string)Eval("Item_BelongToAuction") %>
</ItemTemplate>
Note that Eval is used inside <%# %>, not <% %>.

Can I check a query string in an anchor tag before the anchor tag is clicked on the parent page? If so, how?

In my application FirstPage.aspx I am using a repeater to create a series of links:
<a href="MySecondPage.aspx?id=<%#DataBinder.Eval(Container.DataItem, "ValueID")%>">
<%#DataBinder.Eval(Container.DataItem, "ValueName")%></a>
Normally, in the page load of MySecondPage.aspx I would get the value of the QueryString like:
string OldID = Request.QueryString["id"];
num SkulloID = Convert.ToInt(SkulloID);
if(SkulloID > 5)
{
Response.Write("Hello World");
}
Instead of this, what I want to do is somehow on FirstPage.aspx get the value of the querystring in the anchor tag to do some logic on just as in the case of MySecondPage.aspx. Is something like this possible?
Edited to test solutions presented
#CodingBiz I tried the solution you presented and I am having trouble. Here is what I have tried.
In the Page_Load i added the following code to set the CommandArgument of the link button
//Error: The name containder does not exist in the current context
lbnTestLink.CommandArgument = DataBinder.Eval(container.DataItem, "ValueID");
In the asp:LinkButton click command
MyID = DataBinder.Eval(container.DataItem, "ValueID");
using (SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
SqlCommand cmdzero = new SqlCommand(#"SELECT [num] FROM [My_Table] Where [ValueID] = #MyID AND [IsSubItem] = 1 AND [FiscalYear] = #FiscalYear", conn2);
cmdzero.Parameters.AddWithValue("#MyID", MyID);
cmdzero.Parameters.AddWithValue("#FiscalYear", strFiscalYear);
conn2.Open();
int countzero = (int)cmdzero.ExecuteScalar();
int myArgument = countzero;
if (MyID = myArgument)
{
strListLink = "FistPage.aspx";
}
else
{
strListLink = "SecondPage.aspx?id=<%#DataBinder.Eval(Container.DataItem, \"ValueID\")%>";
}
}
I don't understand where the querystring is supposed to get set here.

How can I create SQL Query which Takes Parameters from URL in asp.net C#

my link is like
http://localhost/default.aspx?phone=9057897874&order=124556
Here Is my basic Page for passing Parameter In URL from ASP.net
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<!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 method="get" action="default.aspx">
<label>Phone No</label>
<input type="text" name="phone" />
<br />
<label>Order No</label>
<input type="text" name="order" />
<br />
<input type="submit" value="submit" />
<br />
</form>
my c# file where I can store the prameters in Variables
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strQuery;
string phone = Request.QueryString["phone"];
if (phone != null)
{
Response.Write("phone no is ");
Response.Write(phone);
}
else
{
Response.Write("You phone number is not correct");
}
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
//How I can Connect to Mysql Server
strQuery = "SELECT order_status where orde01=''" + order_no + "'' and phone01=''" + phone + "''";
Response.Write(strQuery);
}
}
I'm trying to doing something like this but it's only give me whole query as string.
I am new on this topic.
Any help will be appreciate
Thanks
First off, concatenating a sql statement based on input that the user can change, especially when stored as a string is how SQL Injection Vulnerabilities are created. Don't be that guy.
as for tokenalizing your query string, use named parameters. assume this is your query string
?orderid=777&phone=777-777-7777
Response.QueryString["orderid"]
would return '777' and
Response.QueryString["phone"]
woudl return '777-777-7777'
as for your sql injection issue, you have a couple options. one is a parameterized sql statement, see the C# example here: http://rosettacode.org/wiki/Parametrized_SQL_statement
or use a stored procedure with parameters. the least desirable but minimally acceptable option is to regex validate your input parameters strictly, especially killing characters like '=;% -- and a few others.
EDIT: now that I've had some time to work up a sample, check this out. This sample needs to be customized to your database, but its working on my mysql DB with a test table. you will need to install the MySQLConnector pack and add a project reference to 'MySql.Data' before the code will compile correctly.
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
//define some regex patterns for validating our data.
const string PHONEREGEX = #"((\(\d{3}\))|(\d{3}-))\d{3}-\d{4}";
const string ORDERNUMREGEX = #"\d*";
bool isValid = true;
string phone = Request.QueryString["phone"]; //read phone from querystring.
//validate that arg was provided, and matches our regular expression. this means it contains only numbers and single hyphens
if(!string.IsNullOrWhiteSpace(phone) && System.Text.RegularExpressions.Regex.IsMatch(phone, PHONEREGEX)){
Response.Write(HttpUtility.HtmlEncode(string.Format("The phone number is {0}", phone))); //HTML Encode the value before output, to prevent any toxic markup.
} else {
Response.Write("Phone number not provided.");
isValid = false;
}
string orderStr = Request.QueryString["order"]; //read ordernum from querystring
long order = long.MinValue;
//validate that order was provided and matches the regex meaning it is only numbers. then it parses the value into 'long order'.
if(!string.IsNullOrWhiteSpace(orderStr) && System.Text.RegularExpressions.Regex.IsMatch(orderStr, ORDERNUMREGEX) && long.TryParse(orderStr, out order)){
Response.Write(HttpUtility.HtmlEncode(string.Format("The order number is {0}", order))); //use 'long order' instead of orderStr.
} else {
Response.Write("Order number not provided.");
isValid = false;
}
//if all arguments are valid, query the DB.
if (isValid) {
Response.Write(GetOrderStatus( phone, order));
}
}
private static string GetOrderStatus(string phone, long order) {
string status = "";
//create a connection object
string connstring = "SERVER=<YOUR MYSQL SERVER>;DATABASE=<YOUR DATABASE>;UID=<YOUR USER>;PASSWORD=<YOUR PASSWORD>-";//this is a connection string for mysql. customize it to your needs.
MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connstring); //put your connection string in this constructor call
//create a SQL command object
using (MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand()) { //use a using clause so resources are always released when done.
cmd.Connection = conn;
cmd.CommandText = "SELECT `Order_Status` FROM `<YOUR TABLE>` WHERE `Order` = #order AND `Phone` = #phone"; //this needs a From statement
//add parameters for your command. they fill in the #order and #phone in the sql statement above. customize these to match the data types in your database.
cmd.Parameters.Add("order", MySql.Data.MySqlClient.MySqlDbType.Int64,11).Value = order; //do not use # sign in parameter name
cmd.Parameters.Add("phone", MySql.Data.MySqlClient.MySqlDbType.VarChar, 50).Value = phone;
//execute the command, read the results from the query.
cmd.Connection.Open();
using (MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
status = reader.GetString("Order_Status");
}
cmd.Connection.Close();
}
}
return status;
}
}
}
You should be using
Request.Form["phone"]
Request.Form["order"]
instead of
Request.QueryString["phone"]
Request.QueryString["order"]
The reason for this is, you are doing a postback and never redirect to a url with those values set as a querystring
However your question title would suggestion your have a url which contains something like
http://yourdomain.com?phone=0123456789&order=17

Using Programmatic Images in Nivo SLider with asp.net and c#

"Only images or images wrapped in links are allowed in the slider div. Any other HTML will break the slider."
What would be the best way to programatically insert images from a database in c#?
I was using a label inside the div id="slider" tag but then realized the label would create the images within a span tag and therefore break the slider.
lblSlider.Text += "<img src=\"" + URL + "\" alt=\"" + address + "\" title=\"<a href='Featured/" + address" + address + ", " + city + "</a>\" />";
Use markup like this...
<img src='ImageHandler.ashx?ProductID=<%# Eval("ProductID")%>'
alt="<%# Eval("ProductName") %>" title="<%# Eval("ProductName") %>" />
... in conjunction with an image HttpHandler class like this (adapt for your own particular DB schema):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["productID"] != null)
{
try
{
string ProductID = context.Request.QueryString["ProductID"];
if (Convert.ToInt32(ProductID) > 0)
{
const string CONN
= "Initial Catalog=xxx;Data Source=xxx;Integrated Security=SSPI;";
string selectQuery
= "SELECT Photo FROM dbo.Products WHERE dbo.Products.ProductID="
+ ProductID.ToString();
SqlConnection conn = new SqlConnection(CONN);
SqlCommand cmd = new SqlCommand(selectQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
dr.Close();
conn.Dispose();
// context.Response.End();
// caused an "Abort thread" error
// - this is correct and is a special exception
}
}
catch (Exception ex)
{
ErrorReporting.LogError(ex);
}
}
else
throw new ArgumentException("No ProductID parameter specified");
}
public bool IsReusable
{
get
{
return true; // multiple images otherwise false
}
}
}
Okay, I haven't tried the other solution but I did this and it works:
Here are some global c# variables:
protected int count;
protected string[] arr = new string[20];
Then I assign values to the string array from my database in the Page_Load method.
And then I just write the nivo slider with javascript on my page:
<script type="text/javascript">
document.write("<div id='slider' class='nivoSlider'>");
var count = <%= count %>;
var myArray = <% = new JavaScriptSerializer().Serialize(arr) %>;
for(var i = 0; i < count; i++) {
document.write(myArray[i]);
}
document.write("</div>");
</script>
This solution seems easier to me, but if anyone thinks I should use the other solution over this one, let me know. Oh, and don't forget the namespace System.Web.Script.Serialization
I have same requirement and tried the below code to accomplish the dynamic loading of images basing on category. These image loaded from my database. I am new to ASP.Net please let me know if I did anything wrong or did any blunders :).
in ASP.Net file:
I am using nivo slider append method
<script type="text/javascript">
$(window).load(function() {
$('#slider').append('<img id="ad5" src=<%=__ad1ImageUrl %> />');
$('#slider').append('<img id="ad6" src=<%=__ad2ImageUrl %> />');
$('#slider').append('<img id="ad7" src=<%=__ad3ImageUrl %> />');
$('#slider').append('<img id="ad8" src=<%=__ad4ImageUrl %> />');
$('#slider').nivoSlider();
});
</script>
My table looks like this:
<table style="height: 183px; width: 100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="left">
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div class="ribbon">
</div>
<div id="slider" class="nivoSlider">
<!-- note that no images added here -->
</div>
</div>
</div>
</td>
</tr>
</table>
In the code behind:
Use variable to store image url(s). You can now get the URL(s) from DB and get populated. In my code i have used these variables (can use array also) to capture url path. You can get the paths from any source like Database, Xml or ...
public string __ad1ImageUrl = "";
public string __ad2ImageUrl = "";
public string __ad3ImageUrl = "";
public string __ad4ImageUrl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
__ad1ImageUrl = "UserControls/Images/mainBanner1.jpg";
__ad2ImageUrl = "UserControls/Images/mainBanner2.jpg";
__ad3ImageUrl = "UserControls/Images/mainBanner3.jpg";
__ad4ImageUrl = "UserControls/Images/mainBanner4.jpg";
}
}

Categories