deleteing a list of values sent from client - c#

I am trying to delete a list of values from database.I create a list with JQ and send it to server. my problem is how can I extract the values with request method my JQ code looks like this :
$("#del").click(function () {
var dellist = "";
$(".del:checked").each(function () {
dellist += "'" + $(this).val() + "',";
})
dellist += "''";
$.get("mem.aspx?cmd=del&dellist=" + dellist, function () { });
})
and the C# part is like this :
if(CMD == "del")
{
}
I use entity framework.

You have to use Request.QueryString as you are making query string in get method.
string del = Request.QueryString["del"].ToString();
string dellist = Request.QueryString["dellist"].ToString();
You can use string.Split to extract values from server.
string []listValues = Request.QueryString["dellist"].ToString().Split(',');

you can use
string cmd=Request["cmd"];
string dellist = Request["dellist"];

try this
String[] dellist = Request.QueryString["dellist"].Split(',');
since you have string with comma separated you can split that string with , character as above. String.Split method return array of strings.

Related

Put single quote in each values inside a string in C#

I am trying to put a single quote in each values in a string that is separated by comma to include it in an SQL query (ex. "AND STAT IN ('11', '12'). Please help me if you have any ideas.
Sample data: string sStatus = "10,20,30,40";
I have already tried splitting each of the values.
if (!String.IsNullOrEmpty(sStatus))
{
string[] sStatList = sStatus.Split(',');
foreach (string p in sStatList)
{
}
sFilter = String.Format(" AND STAT IN ({0})", sStatList);
}
You can use Select().
string[] sStatList = sStatus.Split(',');
var res = string.Join(",", sStatList.Select(s => $"'{s}'"));
This requires using System.Linq;.
try this:
string[] sStatList = sStatus.Split(',');
string sFilter= "";
foreach (string p in sStatList)
{
sFilter = sFilter+ ("'" + p + "',");
}
if(sFilter.EndsWith(","))
{
sFilter = sFilter.Substring(0,sFilter.Length-1);
}
sFilter = " AND STAT IN (" + sFilter + ")";
#oika's answer is on the right track but it's not quite right for what you're trying to do. However Select is the answer here... like this though:
You'll need to add a reference to Linq:
using System.Linq;
Then
var sStatuses = sStatus.Split(',');
var parsedsStatuses = string.Join(",", sStatuses.Select(x => $"'{x}'"));
var sql = $"AND STAT IN ({ parsedsStatuses })";
Of course you do want to be careful doing this, as it opens up a vulnerability for SQL Injection.
You can either use the string.Join like this:
var status = "10,20,30,40";
if (!string.IsNullOrEmpty(status))
{
var sStatList = status.Split(',');
filter = $"'{string.Join("','", sStatList)}'";
}
Another option you have, would be to use the string.Replace:
var status = "10,20,30,40";
filter = $"'{status.Replace(",","','")}'";
Either way, you need to validate the input to avoid SQL Injection. Consider following:
status = "10,20,30');/*,*/ DROP TABLE Users;//";
Dapper for example supports this directly:}
var sql = "SELECT * FROM table WHERE Id IN #ids"
var results = connection.Query(sql, status.Split(','));
and there are alternative orms that will handle parameterisation.
As a side note: avoid using the Hungarian notation in C# as microsoft also recommends. The Hungarian notation where you specify the variable type using a prefix is useless information and adds noise, especially VS and VS Code will tell you the type anyway.

Convert List Combo into Comma-Separated String in c#

My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)

Convert list to string with single quotes

I am trying to create a string from List
This is my code
List<string> SelectedSalesmen = new List<string>();
and I am adding selected salesmen from listBox like this
foreach (ListItem lst in lstBoxSalesmen.Items)
{
if (lst.Selected)
{
SelectedSalesmen.Add(lst.Value);
}
}
finally I am storing that value to a string like this
string SalesManCode = string.Join(",", SelectedSalesmen.ToArray());
But I am getting like this
SLM001,SLM002,SLM003
but I need Output like this
'SLM001','SLM002','SLM003'
Try this:
string SalesManCode = string.Join(",", SelectedSalesmen
.Select(x=>string.Format("'{0}'",x)));
it will wrap all your elements with ' and then join them using , as separator
What about this:
string output = "'" + string.Join("','", SelectedSalesmen) + "'";
Though this'll return '' for an empty input.
Same as the answer from #wudzik but with string interpolation
var salesManCode = string.Join(",", selectedSalesmen.Select(x => $"'{x}'"));
Just use the above one with split like below:
string.Join(",", SelectedSalesmen.Split(',').Select(x => string.Format("'{0}'", x)));
which will give you:
"'SLM001','SLM002','SLM003'"
you can do something like this:
"'" + string.Joing("',", SelectedSalesmen.ToArray() + "'");

Azure Mobile Services - Passing arrays through Custom Parameters

I'm using Azure Mobile Services with a C# client. I have a table of "Scores" that have a Facebook Id for each score. What I need to do is pass in an array of friends for a user and return all scores in that list of friends.
So I tried this on the client:
return _client.GetTable<Score>().WithParameters(new Dictionary<string, string>
{
{ "Level", level.ToString() },
//aggregate our string[] to a comma-delimited string
{ "Friends", friends.Aggregate(new StringBuilder(), (b, s) => b.Append(s).Append(',')).ToString() }
}).ToListAsync();
Which is weird I only have the option to pass in strings for custom parameters.
So I did this on the server's read:
function read(query, user, request) {
query.where({ Level: request.parameters.Level, UserId: request.parameters.Friends.split(',') });
request.execute();
}
It doesn't seem like a comma-delimited list is going to work. I get this error on the server:
Error in script '/table/Score.read.js'. Error: Unsupported literal value chucknorris,bobloblaw,
NOTE: I passed chucknorris and bobloblaw as Facebook ids for a test.
Is there another way to make this work? The "Level" value filters just fine if I take out the string delimited stuff.
Your usage of the mssql object definitely works, but you can also use a function in the query.where call, with the function returning the condition you want:
function read(query, user, request) {
query.where(function(level, userIds) {
return this.Level === level && this.UserId in userIds;
}, request.parameters.Level, request.parameters.Friends.split(','));
request.execute();
}
Notice that the in operator in this function doesn't behave quite exactly like the in operator in JavaScript. Instead, it's used exactly to have an 'or' grouping of equality statements, which you were creating "by hand" to pass to the SQL object.
Got it working with this server-side script:
function read(query, user, request) {
var innerSql = '';
var friends = request.parameters.Friends.split(',');
var parameters = new Array(friends.length + 1);
parameters[0] = request.parameters.Level;
for (var i = 0; i < friends.length; i++) {
if (i !== 0) {
innerSql += ' or ';
}
innerSql += 'UserId = ?';
parameters[i + 1] = friends[i];
}
mssql.query('select * from Score where Level=? and (' + innerSql + ')', parameters, {
success: function (results) {
request.respond(statusCodes.OK, results);
}
});
}
I'll keep this answer open for a few days if someone has a cleaner solution.

C# DataRow all itemarrays to single string, appending | to each array

DataTable tblData = new DataTable();
MySQLProcessor.dtTable(pullDataQuery, out tblData);
foreach (DataRow columnRow in tblData.Rows)
{
//do string work here
}
columnRow looks like this
[0]Apple
[1]Pear
[2]Mango
I want to turn it into a string that looks like Apple|Pear|Mango
without doing a foreach loop in the array.
Soryr for not making it clear, each table comes out with a different amount of arrayitems.
Try doing
object[] arr = new object[] {"1", "2" };
string joinedStr = string.Join("|",arr.Select(p => p.ToString()).ToArray());
So, your code could become
DataTable tblData = new DataTable();
string myStr = string.Empty;
MySQLProcessor.dtTable(pullDataQuery, out tblData);
foreach (DataRow columnRow in tblData.Rows)
{
myStr = string.Join("|",columnRow.ItemArray.Select(p => p.ToString()).ToArray());
//do whatever you want
}
Consider String.Join. The columns values in question must be extracted first, perhaps...
var cols = row.ItemArray
.Select(i => "" + i) // Not i.ToString() so when i is null -> ""
.ToArray(); // For .NET35 and before, .NET4 Join takes IEnumerable
var res = string.Join("|", cols);
...or similar.
Happy coding.
Mike you can do something like this
string finalString=string.Empty;
foreach (DataRow columnRow in tblData.Rows)
{
finalString+=columnRow["ColumnName"]+"|";
}
if(finalyString.length>0)
{
finalyString=finalString.Substring(0,finalString.length-1) // this removes extra "|" at the end
}
//Without Using LINQ. In case you use old DotNet (Eg.2.0)
string ArrToStr(DataRow r,string separator)
{
string temp = "";
Object[] o = r.ItemArray;
foreach(Object oo in o)
{
temp += oo.ToString() + separator;
}
return temp;
}
//So you can use like this.
string value="";
foreach (DataRow row in combine.Rows)
{
value += ArrToStr(row, ",") ;
}
[Edited]:
You can get all the values of DataRow by it's property ItemArray.
ItemArray is array of values which data types are types of object.
You can pass this array to function string.Join() which concatenates all the elements of array, using the specified separator between each element.
Be carefull because if your DataRow contains DBNull.Value in any of the columns, function string.Join() will implicity convert DBNull.Value into empty string (""). So in the end you can get something like this A||B.
To avoid this situation I used in my example LINQ function Where() to get rid of empty values of DataRow and turn it into array again by using LINQ function ToArray(). More about DBNull.Value.ToString() you can find here msdn source .
In foreach loop you can notice that I have used dollar sign - $ (special character which identifies interpolated string), which is used for string interpolation.
"String interpolation is the process of evaluating a string literal
containing one or more placeholders, yielding a result in which the
placeholders are replaced with their corresponding values"
In this case placeholder is enclosed in a pair of curly brackets {}.
By using string interpolation I got rid of another + sign operator for concatenating string literal "\r\n".
string str = "";
foreach (DataRow columnRow in tblData.Rows)
{
str += $"{string.Join("|", columnRow.ItemArray.Where(val => val != DBNull.Value).ToArray())}\r\n";
}
Try this:
string record = columnRow[0].ToString() + "|" + columnRow[1].ToString() + "|" + columnRow[2].ToString();

Categories

Resources