I need to grab all the FIELD and VALUES from a POST.
I have the follow which only return the FIELDs but no Values.
NameValueCollection authForm = Request.Form;
String[] a = authForm.AllKeys;
for (i = 0; i < a.Length; i++)
{
frm += ("Form: " + a[i] + " : " + "<br>");
}
Response.Write(frm);
What can I add this the frm string to show the VALUES ?
UPDATE:
I used the initial code of
NameValueCollection authForm = Request.Form;
foreach (string key in authForm.AllKeys)
{
frm += ("Key: " + key + ", Value: " + authForm[key] + "<br/>");
}
which worked great. I will try the new variation below.
NameValueCollection authForm = Request.Form;
StringBuilder sb = new StringBuilder();
foreach (string key in authForm.AllKeys)
{
sb.AppendFormat(
"Key: {0}, Value: {1}<br/>",
HttpUtility.HtmlEncode(key),
HttpUtility.HtmlEncode(authForm[key])
);
}
Response.Write(sb.ToString());
Related
This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 3 years ago.
I am trying to get a line foreach line in a webclient.DownloadString("pastebinsite"); but it says cannot convert type 'char' to 'string', so I add a string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
that does not work because it says cannot convert type 'string' to 'string[]' I am stuck and cannot find a answer online for this.
I have tried changing types
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("start?");
Console.ReadKey();
string[] lines = File.ReadAllLines(Directory.GetCurrentDirectory() + #"\Lines.txt");
WebClient wc = new WebClient();
int _checked = 0;
int _error = 0;
foreach(string line in lines)
{
++_checked;
//Pastebin text viewer
try
{
if (line.Contains("pastebin"))
{
var arac = line.Split('/');
//ERROR LINE CANNOT CONVERT TYPE 'STRING' TO 'STRING[]' Below
string[] downloaded = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
foreach(string line2 in downloaded)
{
if (line2.Contains(":")
{
//Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
Console.WriteLine(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
sb.Append(downloaded);
}
}
}
else
{
//Console.WriteLine("Not valid pastebin link!");
}
Console.Title = "Checked : " + _checked;
}
catch(WebException ex)
{
++_error;
Console.WriteLine("Error: " + _error);
}
}
File.WriteAllText(Directory.GetCurrentDirectory() + #"\Output " + _checked + ".txt", sb.ToString());
Console.Clear();
Console.WriteLine("FINISHED");
Console.ReadKey();
}```
wc.DownloadString(..)
returns a string and not a string[].
you need to split the string in order to get a string[]
possible solution if you need that the string[] will contain lines would be:
var stringResult = wc.DownloadString(arac[0] + arac[1] + #"//" + arac[2] + "/raw/" + arac[3]);
then one of the following:
var lines = stringResult.Split(new [] { '\r', '\n' });
var lines = Regex.Split(stringResult, "\r\n|\r|\n");
var lines = stringResult.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)
and finally
foreach(string line in lines) {...}
I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class
this my code
private DataTable ParseTable(string html)
{
HtmlDocument doc = new HtmlDocument();
DataTable dt = new DataTable();
String[] datasc;
String[] valueTemp = new String[30];
int index;
doc.LoadHtml("<table><tr><td><p><input id=\"ControlGroupScheduleSelectView_AvailabilityInputScheduleSelectView_RadioButtonMkt1Fare7\" type=\"radio\" name=\"ControlGroupScheduleSelectView$AvailabilityInputScheduleSelectView$market1\" value=\"0~N~~N~RGFR~~1~X|QG~ 885~ ~~BTH~05/19/2014 07:00~KNO~05/19/2014 08:20~\" />Rp.445,000 ( N/Cls;4 )</p></td></tr></table>");
for (int z = 0; z < 4; z++)
{
var getInputSchedule = doc.DocumentNode.SelectNodes("//table//input");
datasc = new String[getInputSchedule.Count];
for (int i = 0; i < getInputSchedule.Count; i = i+1)
{
string removeClassFare = string.Empty;
String[] selectValueSplit = getInputSchedule[i].Attributes["value"].Value.Split('|');
valueTemp[i] = selectValueSplit[1];
String[] getAlphaSC = selectValueSplit[0].Split('~');
try
{
index = getInputSchedule[i].ParentNode.InnerText.IndexOf("(");
if (index != -1)
{
removeClassFare = getInputSchedule[i].ParentNode.InnerText.Substring(0, index);
removeClassFare = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(removeClassFare)).Replace("??", "").Replace("Rp.", "").Trim();
}
}
catch (Exception e) {
//removeClassFare = getInputSchedule[i].ParentNode.InnerText;
}
if (!dt.Columns.Contains(getAlphaSC[1]))
{
dt.Columns.Add(getAlphaSC[1], typeof(string));
}
if (i == 0)
{
datasc[i] = "<div align=\"center\"><input <input onclick='faredetail(this.value, this.name)' id=\"" + getInputSchedule[i].Attributes["id"].Value + "\" type=\"radio\" value=\"" + getInputSchedule[i].Attributes["value"].Value + "\" name=\"" + getInputSchedule[i].Attributes["name"].Value + "\"><br>" + removeClassFare + "</div>";
}
else
{
if (selectValueSplit[1].Equals(valueTemp[i - 1],StringComparison.Ordinal))
{
datasc[i] = "<div align=\"center\"><input <input onclick='faredetail(this.value, this.name)' id=\"" + getInputSchedule[i].Attributes["id"].Value + "\" type=\"radio\" value=\"" + getInputSchedule[i].Attributes["value"].Value + "\" name=\"" + getInputSchedule[i].Attributes["name"].Value + "\"><br>" + removeClassFare + "</div>";
}
else
{
break;
}
}
getInputSchedule[i].Remove();
}
datasc = datasc.Where(x => !string.IsNullOrEmpty(x)).ToArray();
dt.Rows.Add(datasc);
}
return dt;
}
if i run, error message "Object reference not set to an instance of an object.", but if i remove the ID of element like
doc.LoadHtml("<table><tr><td><p><input type=\"radio\" name=\"ControlGroupScheduleSelectView$AvailabilityInputScheduleSelectView$market1\" value=\"0~N~~N~RGFR~~1~X|QG~ 885~ ~~BTH~05/19/2014 07:00~KNO~05/19/2014 08:20~\">Rp.445,000 ( N/Cls;4 )</p></td></tr></table>");
Everything works ok.
Why does the ID attribute cause my XPath to fail?
pleasee..help..
thank you
I stand corrected. SelectNodes does return null if it can't find any nodes.
But the behavior you are witnessing has nothing to do with the id attribute (in fact, removing the id attribute causes an exception to happen sooner), and everything to do with your code.
At the end of your inner loop, you are doing this:
getInputSchedule[i].Remove();
which removes the <input> element from the HTML document.
Your outer loop is set up to execute four times, so the second time it executes, the input element is already gone, and doc.DocumentNode.SelectNodes("//table//input") returns null, and that is the cause of your error.
I'm not really sure why you're removing the input elements from the document as you go through it, or why you're looping through the whole thing 4 times, but hopefully that gets you going in the right direction.
I am trying to access a dictionary nested inside another dictionary.
The code I wrote is:
foreach (var entry in source)
{
int i = 0;
str = str + i + ": key: " + entry.Key + "; value = " + entry.Value +"; ";
// do something with entry.Value or entry.Key
}
and for some elements the value is System.Collections.Generic.Dictionary`2[System.String,System.Object]
I would like to access this dictionary when the inner value has a given value, as "Department".
Any idea on how to do it?
I would like to access this dictionary when the inner key has a given
value, as "Department"
Assuming you have a dictionary like this:
var source = new Dictionary<string, Dictionary<String, Object>>();
foreach (var outerEntry in source)
{
foreach (var innerEntry in outerEntry.Value)
{
if(innerEntry.Key == "Department")
{
// do something
Console.WriteLine("Key:{0} Value:{1}", innerEntry.Key, innerEntry.Value);
}
}
}
If the Value is a dictionary you could loop through the underlying dictionary keys:
foreach (var entry in source)
{
int i = 0;
str = str + i + ": key: " + entry.Key + "; value = "
if (entry.Value is IDictionary)
}
str = str + " { ";
foreach (var innerentry in (entry.Key as IDictionary))
{
str = str + innerentry.Key + "; value = " + innerentry.Value +"; ";
}
str = str + " } ";
}
else
str = str + entry.Value +"; ";
// do something with entry.Value or entry.Key
}
Where can I find a good SQL Query builder class. I just need a simple class to build a SQL string and that is it. I will need it for C# and MySql. I really don't need anything like Linq or NHibernate. Thanks
Since Google leads me to this page,
I would suggest SqlKata, a simple but powerful SqlQuery Builder, that supports nested where conditions, subqueries and joins.
Currently it supports SqlServer, MySql and PostgreSql
var query = new Query("Users")
.LeftJoin("Countries", "Users.CountryId", "Countries.Id")
.Where("Status", "blocked")
.OrWhereIn("Id", new [] {10, 11, 12})
.OrWhere("LastLogin", ">", DateTime.UtcNow.AddMonths(-5));
Note: I am the owner of it
Difference between different compilers output
MySql: https://sqlkata.com/playground/mysql?code=var%20query%20=%20new%20Query(%22Posts%22).Limit(10).Offset(20)%3B
SqlServer: https://sqlkata.com/playground/sqlserver?code=var%20query%20=%20new%20Query(%22Posts%22).Limit(10).Offset(20)%3B
Oracle: https://sqlkata.com/playground/oracle?code=var%20query%20=%20new%20Query(%22Posts%22).Limit(10).Offset(20)%3B
I use this code..It Escapes the strings too i hope it Helps:
class Mysql
{
public static string INSERT(string INTO, NameValueCollection VALUES)
{
string queryString = "INSERT INTO " + INTO + " (";
for (int i = 0; i < VALUES.Count; i++)
{
queryString += VALUES.Keys[i] + (i + 1 == VALUES.Count ? "" : ",");
}
queryString += ") VALUES (";
for (int i = 0; i < VALUES.Count; i++)
{
queryString += Escape(VALUES[VALUES.Keys[i]]) + (i + 1 == VALUES.Count ? ("") : (","));
}
queryString += ");";
return queryString;
}
public static string DELETE(string FROM, NameValueCollection WHERE)
{
string queryString = "DELETE FROM " + FROM + " WHERE";
for (int i = 0; i < WHERE.Count; i++)
{
queryString += " " + WHERE.Keys[i] + "=" + Escape(WHERE[WHERE.Keys[i]]);
}
queryString += ";";
return queryString;
}
public static string UPDATE(string UPDATE, NameValueCollection SET, NameValueCollection WHERE)
{
string queryString = "UPDATE " + UPDATE + " SET";
for (int i = 0; i < SET.Count; i++)
{
queryString += " " + SET.Keys[i] + "=" + data.Escape(SET[SET.Keys[i]]) + (i + 1 == SET.Count ? ("") : (","));
}
queryString += " WHERE";
for (int i = 0; i < WHERE.Count; i++)
{
queryString += " " + WHERE.Keys[i] + "=" + data.Escape(WHERE[WHERE.Keys[i]]);
}
queryString += ";";
return queryString;
}
public static string SELECT(string[] SELECT, string FROM, NameValueCollection WHERE)
{
string queryString = "SELECT ";
for (int i = 0; i < SELECT.Length; i++)
{
queryString += SELECT[i] + (i + 1 == SELECT.Length ? ("") : (","));
}
queryString += " FROM " + FROM + " WHERE ";
for (int i = 0; i < WHERE.Count; i++)
{
queryString += " " + WHERE.Keys[i] + "=" + Escape(WHERE[WHERE.Keys[i]]);
}
queryString += ";";
return queryString;
}
public static string Escape(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.ToString();
}
}
}
}
You use it like this:
NameValueCollection nvc_for_SET_and_VALUES=new NameValueCollection();
NameValueCollection nvc_for_WHERE= new NameValueCollection();
nvc_for_WHERE.Add("arg1","value1");
nvc_for_WHERE.Add("AND arg2","value2");
nvc_for_WHERE.Add("OR arg2","value3");
nvc_for_SET_and_VALUES.Add("arg", "value");
nvc_for_SET_and_VALUES.Add("arg2", "value2");
string[] fieldsToSelect= { "arg1", "arg2" };
Mysql.DELETE("mytable", nvc_for_WHERE);
Mysql.INSERT("mytable", nvc_for_SET_and_VALUES);
Mysql.SELECT(fieldsToSelect, "mytable", nvc_for_WHERE);
Mysql.UPDATE("mytable", nvc_for_SET_and_VALUES, nvc_for_WHERE);
You could probably use the framework class CommandBuilder. Check out:
http://msdn.microsoft.com/en-us/library/tf579hcz.aspx
If you are using .NET 4 and don't mind using dynamics you can use Massive, created by Rob Conery, this single file Database requires no dlls, just drop the Massive.cs file and you ready to go.
You can use the Massive to build queries like this.
//grab all the products
var products = table.All();
//Or
var productsFour = table.All(columns: "ProductName as Name", where: "WHERE categoryID=#0",args: 4);
You can also run ad-hoc queries as needed:
var result = tbl.Query("SELECT * FROM Categories");
Mohammed Hadi, with DbExtensions your sample can be like this:
public static string InsertQuery(string into, NameValueCollection values)
{
var query = SQL
.INSERT_INTO(into + " (" +
String.Join(" ,", values.Keys.Cast<String>().ToArray()) +
")")
.VALUES(values.Keys.Cast<String>().Select(key => values[key]));
return query.ToString();
}