C# Retrieve Values from URL and insert records - c#

In my code I have received, by way of a url, a comma delimited list of id's e.g.
12,13,14,15,16 etc..
I have got these into a string (Tools) which I have Split.
I now need to loop through each value and use it in an insert statement but I have got stuck can anyone help.
The C# below is based on an SDK so it is uses some functions that you may not have seen.
string userc = GetContextInfo("User", "UserId");
string tools = Dispatch.EitherField("selectedTools");
tools.Split(',');
string pID = Dispatch.EitherField("key16");
Record recRelTool = new Record("RelatedTools");
recRelTool.SetField("rato_CreatedBy", userc);
recRelTool.SetField("rato_Status", "active");
recRelTool.SetField("rato_server", pID);
recRelTool.SetField("rato_tool", tools);
recRelTool.SaveChanges();
Dispatch.Redirect(Url("1453"));
Where the ("rato_tools", tools) needs to be one of the tool id's in the value I have. I need to loop through until all of the tool id's have been used.

The call to split does not split your string, it returns an array of strings. You need to enumerate through this array to use one tool id at a time. Try the following:
string userc = GetContextInfo("User", "UserId");
string tools = Dispatch.EitherField("selectedTools");
string[] toolIds = tools.Split(',');
foreach (string toolId in toolIds)
{
Record recRelTool = new Record("RelatedTools");
recRelTool.SetField("rato_CreatedBy", userc);
recRelTool.SetField("rato_Status", "active");
recRelTool.SetField("rato_server", pID);
recRelTool.SetField("rato_tool", toolId);
recRelTool.SaveChanges();
}
Dispatch.Redirect(Url("1453"));

you have to assign your split return value:
var splitted = tools.Split(',');
http://msdn.microsoft.com/en-us/library/tabh47cf.aspx
and then you can iterate the collection:
foreach(string item in splitted)
{
//do something
}

Related

How to compare list of strings to a string where elements in the list might have letters be scrambled up?

I'm trying to write a lambda expression to compare members of a list to a string, but I also need to catch elements in the list that might have their letter scrambled up.
Here's code I got right now
List<string> listOfWords = new List<String>() { "abc", "test", "teest", "tset"};
var word = "test";
var results = listOfWords.Where(s => s == word);
foreach (var i in results)
{
Console.Write(i);
}
So this code will find string "test" in the list and will print it out, but I also want it to catch cases like "tset". Is this possible to do easily with linq or do I have to use loops?
How about sorting the letters and seeing if the resulting sorted sequences of chars are equal?
var wordSorted = word.OrderBy(c=>c);
listOfWords.Where(w => w.OrderBy(c=>c).SequenceEqual(wordSorted));

C# - check which element in a csv is not in an other csv and then write the elements to another csv

My task is to check which of the elements of a column in one csv are not included in the elements of a column in the other csv. There is a country column in both csv and the task is to check which countries are not in the secong csv but are in the first csv.
I guess I have to solve it with Lists after I read the strings from the two csv. But I dont know how to check which items in the first list are not in the other list and then put it to a third list.
There are many way to achieve this, for many real world CSV applications it is helpful to read the CSV input into a typed in-memory store there are standard libraries that can assist with this like CsvHelper as explained in this canonical post: Parsing CSV files in C#, with header
However for this simple requirement we only need to parse the values for Country form the master list, in this case the second csv. We don't need to manage, validate or parse any of the other fields in the CSVs
Build a list of unique Country values from the second csv
Iterate the first csv
Get the Country value
Check against the list of countries from the second csv
Write to the third csv if the country was not found
You can test the following code on .NET Fiddle
NOTE: this code uses StringWriter and StringReader as their interfaces are the same as the file reader and writers in the System.IO namespace. but we can remove the complexity associated with file access for this simple requirement
string inputcsv = #"Id,Field1,Field2,Country,Field3
1,one,two,Australia,three
2,one,two,New Zealand,three
3,one,two,Indonesia,three
4,one,two,China,three
5,one,two,Japan,three";
string masterCsv = #"Field1,Country,Field2
one,Indonesia,...
one,China,...
one,Japan,...";
string errorCsv = "";
// For all in inputCsv where the country value is not listed in the masterCsv
// Write to errorCsv
// Step 1: Build a list of unique Country values
bool csvHasHeader = true;
int countryIndexInMaster = 1;
char delimiter = ',';
List<string> countries = new List<string>();
using (var masterReader = new System.IO.StringReader(masterCsv))
{
string line = null;
if (csvHasHeader)
{
line = masterReader.ReadLine();
// an example of how to find the column index from first principals
if(line != null)
countryIndexInMaster = line.Split(delimiter).ToList().FindIndex(x => x.Trim('"').Equals("Country", StringComparison.OrdinalIgnoreCase));
}
while ((line = masterReader.ReadLine()) != null)
{
string country = line.Split(delimiter)[countryIndexInMaster].Trim('"');
if (!countries.Contains(country))
countries.Add(country);
}
}
// Read the input CSV, if the country is not in the master list "countries", write it to the errorCsv
int countryIndexInInput = 3;
csvHasHeader = true;
var outputStringBuilder = new System.Text.StringBuilder();
using (var outputWriter = new System.IO.StringWriter(outputStringBuilder))
using (var inputReader = new System.IO.StringReader(inputcsv))
{
string line = null;
if (csvHasHeader)
{
line = inputReader.ReadLine();
if (line != null)
{
countryIndexInInput = line.Split(delimiter).ToList().FindIndex(x => x.Trim('"').Equals("Country", StringComparison.OrdinalIgnoreCase));
outputWriter.WriteLine(line);
}
}
while ((line = inputReader.ReadLine()) != null)
{
string country = line.Split(delimiter)[countryIndexInInput].Trim('"');
if(!countries.Contains(country))
{
outputWriter.WriteLine(line);
}
}
outputWriter.Flush();
errorCsv = outputWriter.ToString();
}
// dump output to the console
Console.WriteLine(errorCsv);
Since you write about solving it with lists, I assume you can load those values from the CSV to the lists, so let's start with:
List<string> countriesIn1st = LoadDataFrom1stCsv();
List<string> countriesIn2nd = LoadDataFrom2ndCsv();
Then you can easily solve it with linq:
List<string> countriesNotIn2nd = countriesIn1st.Where(country => !countriesIn2nd.Contains(country)).ToList();
Now you have your third list with countries that are in first, but not in the second list. You can save it.

part of String contained in a List

Here's what I'm trying to do:
Create a list with some values from mysql.
Search this list with a variable ( I named it Existed )
If Existed contains a specific string, then do some actions.
Here's a sample of my list data:
List ( name users )
Facebook
Google
Yahoo
Strongman
Zombies
Stratovarius
If Existed inside users contains Strong, then perform some action.
My code so far is below. The problem is that it never enters the action and for some reason I believe it does not see "Strong" right.
List<string> users = dbm.FindManagers();
foreach (var Existed in users)
{
if (Existed.Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}
}
Can't reproduce. This works for me:
var rName_Add_User_result = " Strong ";
//List<string> users = dbm.FindManagers();
var users = new List<string>() {"Facebook", "Google", "Yahoo", "Strongman", "Zombies", "Stratovarius"};
foreach (var Existed in users.Where(u => u.ToUpper().Contains(rName_Add_User_result.ToUpper().Trim()))
{
//dbm.AddSubuser(Existed, rName_result);
Console.WriteLine(Existed);
}
Result:
Strongman
Not sure but could be because of case sensitivity. Try converting it to lower and then compare
if (Existed.ToLower().Contains(rName_Add_User_result))
{
dbm.AddSubuser(Existed, rName_result);
}

Trimming a string in a list

I have a list that contains string values. I need to trim the leading and ending values. Here is the code:
using EnterpriseDT.Net.Ftp;
public List<FTPFile> FileList = new List<FTPFile>();
FTP = new FTPConnection() { ServerAddress = _host, UserName = _user, Password = _password };
FTP.Connect();
FTP.TransferType = FTPTransferType.BINARY;
FTP.ChangeWorkingDirectory(_as400_directory);
FTP.LocalDirectory = _local_directory;
FileList.AddRange(FTP.GetFileInfos());
FTP.Close();
The FileList list contains following example values:
test 123 11/01/12 *STMF File1.csv somegarbagevalues
test 123 11/01/12 *STMF File2.csv somegarbagevalues
test 123 11/01/12 *STMF File3.csv somegarbagevalues
What I need to do is capture online the file name (ex. File1.csv, File2.csv ...) Is there a way to trim the unwanted values without looping through the list or trim when I do the FileList.AddRange statement?
LINQ makes this easy:
FileList.AddRange(FTP.GetFileInfos().Select(x => x.Trim()));
where Trim() would be a method (possibly an extension method) on FTPFile which returned an FTPFile with trimmed filename.
FTPFile is a class and has a property "Name". You were probably looking at the ToString() implementation of the FTPFile class that gave you all the properties at once.
See:
http://www.enterprisedt.com/products/edtftpnet/doc/api/EnterpriseDT.Net.Ftp.FTPFileMembers.html
Just use:
foreach(FTPFile f in FileList)
{
string name = f.Name;
// Do whatever you want with name.
}

Find string in SQL column

I have the next code(found here at stack overflow):
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
This code good for search string on array... i need to find string in sql column.
Let's say i have table ("Names"), and i want to find "Jhon".. how can i do that?
I don't need connectionstring or the whole method, that's i know to do, but i can't think on method to search specific string at sql table.
Will be great to see version of search: "Jh" and it will find "Jhon" if is there...
Well to avoid sql injection if target is user provided
string connectionString= ...
string target="jh";
using (var conn=new SqlConnection(connectionString)) {
conn.Open();
using (var cmd=conn.CreateCommand()) {
cmd.CommandText="select Name from Names where Name like '%'+#value+'%'";
cmd.Parameters.AddWithValue("#value",target);
using (var reader=cmd.ExecuteReader()) {
while (reader.Read()) {
Console.WriteLine(reader[0]);
}
}
}
}
Use like '%'+#value+'%' for contains
Use like #value+'%' for starts with
Use like '%'+#value for ends with
SELECT NAME
FROM NAMES
WHERE NAME='Jhon'
Is this what you're looking for?
If only a part of it needs to match:
...
WHERE NAME LIKE 'Jh%'
LIKE

Categories