How do I add attachments without replacing the old one? - c#

I'm working on a messaging software, I'm working on the Attachements part,
I can attach the files but, when I try to add more, it replaces the old ones.
This is the code:
List<string> listaAnexos = new List<string>();
Archivo.Multiselect = true;
Archivo.ShowDialog();
int cAnex = 0;
string[] anexos = Archivo.FileNames;
foreach (string i in anexos)
{
listaAnexos.Add(i);
cAnex++;
}
lbAnexos.DataSource = listaAnexos;
txtCAnex.Text = cAnex.ToString();
Thanks

Assuming the above piece of code is called multiple times, you most likely need to declare listaAnexos outside of your method.
Every time you run the above method, you create a new instance of listAnexos to add files to, which you then assign to lbAnexos.DataSource, overwriting whatever was in there before.
Declare listaAnexos as a class instance, instead of inside your method.
public class YourClass
{
private List<string> listaAnexos = new List<string>();
private void YourMethod()
{
Archivo.Multiselect = true;
Archivo.ShowDialog();
...
foreach (string i in anexos)
{
listaAnexos.Add(i);
...

Related

Cannot add or insert the item in more than one place - ListView Error

I keep getting an error while attempting to add a range of items into my list view.
Error: "Cannot add or insert the item in more than one place"
Do keep in mind I have column headers.
Here is the example code:
private void OtherFunction()
{
// pulls info and had foreach loop
Add_To_List(Event_Date, Acc_Name, Client_IP, Event_DC, Failure_Code);
}
private void Add_To_List(string date, string user, string ip, string domain, string lockedout)
{
listView1.ListViewItemSorter = null;
// Add item to list view.
ListView.ListViewItemCollection new_row = new ListView.ListViewItemCollection(listView1);
new_row.Add(date);
new_row.Add(user);
new_row.Add(ip);
new_row.Add(domain);
new_row.Add(lockedout);
listView1.Items.AddRange(new_row);
// Clear data
new_row.Clear();
}
This was the code I was using before which worked but it wasn't quite how I wanted it.
string[] new_row = { user, ip, domain, lockedout };
listView1.Items.Add(date).SubItems.AddRange(new_row);
I was looking for an upgrade in speed.
I ended up using this:
string[] row = { Event_Date, Acc_Name, Client_IP, Event_DC, Failure_Code };
var NewListViewItem = new ListViewItem(row);
listView1.Items.Add(NewListViewItem);

How can I simulate user input from a console?

Im doing some challenges in HackerRank. I usually use a windows Form project in visualstudio to do the debug, but realize I lost lot of time input the test cases. So I want suggestion of a way I can easy simulate the console.ReadLine()
Usually the challenges have the cases describe with something like this:
5
1 2 1 3 2
3 2
And then is read like: using three ReadLine
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] squares_temp = Console.ReadLine().Split(' ');
int[] squares = Array.ConvertAll(squares_temp,Int32.Parse);
string[] tokens_d = Console.ReadLine().Split(' ');
int d = Convert.ToInt32(tokens_d[0]);
int m = Convert.ToInt32(tokens_d[1]);
// your code goes here
}
Right now I was thinking in create a file testCase.txt and use StreamReader.
using (StreamReader sr = new StreamReader("testCase.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
This way I can replace Console.ReadLine() with sr.ReadLine(), but this need have a text editor open, delete old case, copy the new one and save the file each time.
So is there a way I can use a Textbox, so only need copy/paste in the textbox and use streamReader or something similar to read from the textbox?
You can use the StringReader class to read from a string rather than a file.
the solution you accepted! doesn't really emulate the Console.ReadLine(), so you can't paste it directly to HackerRank.
I solved it this way:
.
.
Just paste this class above the static Main method or anywhere inside the main class to hide the original System.Console
class Console
{
public static Queue<string> TestData = new Queue<string>();
public static void SetTestData(string testData)
{
TestData = new Queue<string>(testData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.TrimStart()));
}
public static void SetTestDataFromFile(string path)
{
TestData = new Queue<string>(File.ReadAllLines(path));
}
public static string ReadLine()
{
return TestData.Dequeue();
}
public static void WriteLine(object value = null)
{
System.Console.WriteLine(value);
}
public static void Write(object value = null)
{
System.Console.WriteLine(value);
}
}
and use it this way.
//Paste the Console class here.
static void HackersRankProblem(String[] args)
{
Console.SetTestData(#"
6
6 12 8 10 20 16
");
int n = int.Parse(Console.ReadLine());
string arrStr = Console.ReadLine();
.
.
.
}
Now your code will look the same! and you can test as many data as you want without changing your code.
Note: If you need more complexes Write or WriteLine methods, just add them and send them to the original System.Console(..args)
Just set Application Arguments: <input.txt
and provide in input.txt your input text.
Be careful to save the file with ANSI encoding.

How to complete aspx connection string from text file

I must use a text file "db.txt" which inherits the names of the Server and Database to make my connection string complete.
db.txt looks like this:
<Anfang>
SERVER==dbServer\SQLEXPRESS
DATABASE==studentweb
<Ende>
The connection string:
string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
Unfortunatly we are only allowed to use Classic ASPX.net (C# 2.0) and not the web.config.
I've searched a lot, but found nothing close to help me.
Somebody got an Idea how to make it work?
Here is something to get you going.
In a nutshell, I put the DBInfo file through a method that reads the file line by line. When I see the line <anfang> I know the next line will be important, and when I see the line <ende> I know it's the end, so I need to grab everything in between. Hence why I came up with the booleans areWeThereYet and isItDoneYet which I use to start and stop gathering data from the file.
In this snippet I use a Dictionary<string, string> to store and return the values but, you could use something different. At first I was going to create a custom class that would hold all the DB information but, since this is a school assignment, we'll go step by step and start by using what's already available.
using System;
using System.Collections.Generic;
namespace _41167195
{
class Program
{
static void Main(string[] args)
{
string pathToDBINfoFile = #"M:\StackOverflowQuestionsAndAnswers\41167195\41167195\sample\DBInfo.txt";//the path to the file holding the info
Dictionary<string, string> connStringValues = DoIt(pathToDBINfoFile);//Get the values from the file using a method that returns a dictionary
string serverValue = connStringValues["SERVER"];//just for you to see what the results are
string dbValue = connStringValues["DATABASE"];//just for you to see what the results are
//Now you can adjust the line below using the stuff you got from above.
//string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
}
private static Dictionary<string, string> DoIt(string incomingDBInfoPath)
{
Dictionary<string, string> retVal = new Dictionary<string, string>();//initialize a dictionary, this will be our return value
using (System.IO.StreamReader sr = new System.IO.StreamReader(incomingDBInfoPath))
{
string currentLine = string.Empty;
bool areWeThereYet = false;
bool isItDoneYet = false;
while ((currentLine = sr.ReadLine()) != null)//while there is something to read
{
if (currentLine.ToLower() == "<anfang>")
{
areWeThereYet = true;
continue;//force the while to go into the next iteration
}
else if (currentLine.ToLower() == "<ende>")
{
isItDoneYet = true;
}
if (areWeThereYet && !isItDoneYet)
{
string[] bleh = currentLine.Split(new string[] { "==" }, StringSplitOptions.RemoveEmptyEntries);
retVal.Add(bleh[0], bleh[1]);//add the value to the dictionary
}
else if (isItDoneYet)
{
break;//we are done, get out of here
}
else
{
continue;//we don't need this line
}
}
}
return retVal;
}
}
}

C# Reading through CSV file to rename multiple files with new names

I would like to use a list of old and the corresponding new names in a CSV file(source of CSV is a Excel sheet), in order to rename files. Obviously replace the old name with the new name specified for each case.
For Example:
Find what Replace With
C:\Users\Documents\Pump Station.doc C:\Users\Documents\Awesome Pump Station.doc
C:\Users\Documents\Pump Selection.doc C:\Users\Documents\Great Pump Selection.doc
C:\Users\Documents\Pump Sizing Calc.xlsx C:\Users\Documents\Hectic Pump Sizing Calc.xlsx
I am very new to coding and I am having trouble finishing this off. This is what I have so far. I do not necessarily need to even put the list user interface (which it currently does). Ultimately I would like to loop through the rows in my CSV file, check if the old name specified exists and if so, rename it to the new name specified.
I really appreciate any help in advance and sorry for any rookie errors I may have made in my code below.
public class OldNew
{
public string oldFile { get; set; }
public string newFile { get; set; }
}
public static class OldNewService
{
public static new List<OldNew>ReadFile(string filepath)
{
var lines = File.ReadAllLines(filepath);
var data = from l in lines.Skip(1)
let split = l.Split(',')
select new OldNew
{
oldFile = split[0],
newFile = split[1],
};
return data.ToList();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = OldNewService.ReadFile(#"C:\Users\cch\Documents\Batch Edit\Lookup Table.csv");
}
}
}
In my opinion, a better solution would be to use a plain old foreach and not a call to ToList().ForEach().
var lines = File.ReadAllLines(filepath);
var data = from l in lines.Skip(1)
let split = l.Split(',')
select new OldNew
{
oldFile = split[0],
newFile = split[1],
};
foreach(var f in data)
{
if (File.Exists(f.oldFile)
{
File.Move(f.oldFile, f.newFile);
}
}
See: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx for an explanation.
From what I understand, you want to get the new value of the file if an old one exists. To get the new value of the file from your list, try something like:
data.ForEach(d =>
{
if (!string.IsNullOrEmpty(d.oldFile))
{
File.Move(d.oldFile, d.newFile);
}
});
Wouldn't it make sense to rename the old filename if a new one exists?
Hope this helps.

How can dynamically instantiate Page objects from a collection of page names (strings)?

In my ViewModel, I want to build a collection of Page objects from this list of page names:
private string[] pageNames = {
"Introduction.xaml",
"Slide1.xaml",
"Slide2.xaml"
};
How do I instantiate them dynamically, e.g. something like this:
foreach (string pageName in pageNames)
{
//PSEUDO CODE:
Page thePage = new &&pageName();
thePages.Add(thePage);
}
You can use XamlReader.Load :
foreach (string pageName in pageNames)
{
string xaml = File.ReadAllText(pageName);
Page thePage = XamlReader.Load(xaml);
thePages.Add(thePage);
}
(I'm not sure about the File.ReadAllText, it depends where your files are...)

Categories