Trouble getting my button to call my class - c#

I have a Windows Form application. What this application does, is let the user browse to a drive/folder they wish to have files renamed for. This app renames files that have "invalid" characters (that are defined in a RegEx pattern).
What i want to happen here is, after the user decides which drive/folder to use, a datagridview pops up showing the user files in the drive/folder that are going to be renamed. The user then clicks a button to actually rename the files. I'm having trouble though getting the code for my button in DriveRecursion_Results.cs set up. Can anybody help me? Code plz -- i'm extremely new to this and need syntax to look at to understand.
Form1 code:
namespace FileMigration2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.Empty;
//Now, we want to use the path information to population our folder selection initial location
string initialPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion_Results dw = new DriveRecursion_Results();
dw.Show();
dw.DriveRecursion(retPath);
result = retPath;
}
return result;
}
}
}
DriveRecursion_Results.cs code: [the button is in here that i need help with!]
namespace FileMigration2
{
public partial class DriveRecursion_Results : Form
{
public DriveRecursion_Results()
{
InitializeComponent();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DriveRecursion(string retPath)
{
//recurse through files. Let user press 'ok' to move onto next step
// string[] files = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
//string replacement = "";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(retPath, "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
dataGridView1.Rows.Clear();
try
{
foreach (string fileNames in fileDrive)
{
if (regEx.IsMatch(fileNames))
{
string fileNameOnly = Path.GetFileName(fileNames);
string pathOnly = Path.GetDirectoryName(fileNames);
DataGridViewRow dgr = new DataGridViewRow();
filePath.Add(fileNames);
dgr.CreateCells(dataGridView1);
dgr.Cells[0].Value = pathOnly;
dgr.Cells[1].Value = fileNameOnly;
dataGridView1.Rows.Add(dgr);
filePath.Add(fileNames);
}
else
{
DataGridViewRow dgr2 = new DataGridViewRow();
dgr2.Cells[0].Value = "No Files To Clean Up";
dgr2.Cells[1].Value = "";
}
}
}
catch (Exception e)
{
StreamWriter sw = new StreamWriter(retPath + "ErrorLog.txt");
sw.Write(e);
}
}
private void button1_Click(object sender, EventArgs e)
{
//What do i type in here to call my FileCleanUp method???
}
}
SanitizeFileNames.cs code:
namespace FileMigration2
{
public class SanitizeFileNames
{
public static void FileCleanup(List<string>filePath)
{
string regPattern = "*[\\~#%&*{}/<>?|\"-]+*";
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception ex)
{
//write to streamwriter
}
}
}
}
}
}
Any help is appreciated!
Thanks :)

Put
public partial class DriveRecursion_Results : Form {
List<string> filePath;
and in driveRecursion method, just use
filePath = new List<string>();
and in the action button method, why don't you do
if(filePath != null)
SanitizeFileNames.FileCleanup(filePath);
You call filePath.Add twice ?
Your 'else' is in the wrong place too.
What is dgr2?

Related

MethodInvoker is repeating once, and displaying output Twice

I'm trying to get specific data from an .ini file and display it in GridView. The .ini file is updated with information from the last cut a saw made, and every time the file is updated I want the new information displayed in a new row. The problem I keep running into is that the method I have for populating the grid viewer is repeating once every time the file is changed. Sometimes it displays the correct information twice, and sometimes it displays incorrect information once, and then the second time the correct information is displayed.
I added a check using a bool variable to try to stop this, but that hasn't stopped it from outputting twice.
using System.Text.RegularExpressions;
namespace outputViewer
{
public partial class outputViewer : Form
{
//Declare variables for filepath and create a new dictionary
private string iniFilePath;
private string vjob = "";
private string vpart = "";
private string vname = "";
private string vlength = "";
private string vwidth = "";
private string vheight = "";
private string vgrade = "";
private string vcenterLine = "";
bool populate = false; //If PopulateIniDataGrid has been called turn true
public outputViewer()
{
InitializeComponent();
}
//Watch .ini file for changes
public void Watch()
{
var watcher = new FileSystemWatcher(Path.GetDirectoryName(iniFilePath), Path.GetFileName(iniFilePath))
{
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite
};
watcher.Changed += OnFileChanged;
}
//On file change reset bool variable and call ReadIniFile method
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
populate = false;
ReadIniFile();
}
//Reads .ini file using WriteSafeReadAllLines Method, and extracts data for Output
private void ReadIniFile()
{
var iniFileLines = WriteSafeReadAllLines(iniFilePath);
var currentSection = "";
foreach (var line in iniFileLines)
{
//Code sorting through data for output
}
//Check if PopulateIniDataGridView has been called
if (!populate)
{
PopulateIniDataGridView();
populate = true;
}
}
//Set filepath of .ini file
private void setFilePathToolStripMenuItem_Click(object sender, EventArgs e)
{
//Create new openFileDialog object
var openFileDialog = new OpenFileDialog
{
//File type filters for openFileDialog and set default directory to MyDocuments
Filter = "INI files (*.ini)|*.ini|All files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
//If Successful
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
iniFilePath = openFileDialog.FileName;
selectedIniFileLabel.Text = iniFilePath;
}
Watch();
}
//Convert method converts mm to feet-inches-sixteenths
private void Convert(ref string imperial)
//Allow reading file when open by another application
public string[] WriteSafeReadAllLines(string path)
private void PopulateIniDataGridView()
{
//Convert metric to imperial
Convert(ref vwidth);
Convert(ref vheight);
Convert(ref vlength);
Convert(ref vcenterLine);
Invoke(new MethodInvoker(delegate
{
scOutputGridView.Rows.Add(vjob, vname, vpart, vlength, vwidth, vheight, vgrade);
}));
}
}
}

Listbox Item holds data

Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}

Why doesn't my class write to a text file?

Here is my AddReservation Form code. Notice that I call the Piper.WritePiper() method and pass in the Name and Seat that the user enters. I'm not sure why this isn't working. I'm not getting any errors or anything. I am simply just wanting a user to be able to enter their name and seat that they would like to take on the plane and then update the file. Please tell me what I am doing wrong... Thank you in advance!!
public partial class frmAddReservation : Form
{
public frmAddReservation()
{
InitializeComponent();
}
List<Seating> piperSeating = new List<Seating>();
List<Seating> cessnaSeating = new List<Seating>();
private void frmAddReservation_Load(object sender, EventArgs e)
{
piperSeating = Piper.GetPiperReservations();
cessnaSeating = Cessna.GetCessnaReservations();
}
private void btnShowPiper_Click(object sender, EventArgs e)
{
listFlight.Items.Add("Piper Seating Chart:");
listFlight.Items.Add("");
//loop through all the seats
foreach (Seating plane in piperSeating)
{
// add the name of plane to the listbox
listFlight.Items.Add(plane.Name + " " + plane.Seat);
}
}
private void btnAddPiper_Click(object sender, EventArgs e)
{
string Name;
int Seat;
if (DataValid())
{
Name = txtName.Text;
Seat = Convert.ToInt16(txtSeat.Text);
Piper.WritePiper(Name, Seat);
}
}
private bool DataValid()
{
bool isOK = false;
if (CheckSeat(txtSeat))
{
isOK = true;
}
return isOK;
}
private bool CheckSeat(TextBox tbox)
{
bool isOK = true;
try
{
Convert.ToDouble(tbox.Text);
}
catch
{
isOK = false;
}
return isOK;
}
}
Here is my Piper.cs class:
public static class Piper
{
private const string dir = #"Z:\Desktop\Windows 7 Files\C#.net\Reservations\Reservations\Reservations\";
private const string path = dir + "PiperDat.txt";
public static List<Seating> GetPiperReservations()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.Open, FileAccess.Read));
List<Seating> personList = new List<Seating>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split(',');
Seating person = new Seating();
person.Name = columns[0];
person.Seat = Convert.ToInt16(columns[1]);
personList.Add(person);
}
textIn.Close();
return personList;
}
public static void WritePiper(string Name, int Seat)
{
List<Seating> piperSeating = new List<Seating>();
piperSeating = Piper.GetPiperReservations();
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Open, FileAccess.Write));
foreach (Seating plane in piperSeating)
{
Name = plane.Name;
Seat = plane.Seat;
textOut.Write(Name + ",");
textOut.WriteLine(Seat);
}
}
}
Look at the WritePiper method.
It just reads the file and then writes it back, without any changes. The values in the parameters are ignored, the parameters are just used as temporary storage for the data when it is written to the file.
You need to include the values in the parameters as an item, either by adding it to the list, or by writing it to the file along with the items in the list.
Example:
Seating person = new Seating();
person.Name = Name;
person.Seat = Seat;
piperSeating.Add(person);
I think the cause of your issue might be having forgotten the closure of the file, in alternative you might force the text to flush with textOut.Flush().
Try adding textOut.Close() at the end of the WritePiper(...) method.

Output not being written to the DGV in my code

I'm not exactly sure what's going on here--I tried to debug but couldn't really come up with any explanation as to why nothing is being written to my datagridview.
Anybody have any idea?
public partial class CleanPathResults : Form
{
public CleanPathResults()
{
InitializeComponent();
}
public void RenameFolder(string folderName)
{
string regPattern = (#"[~#&$!%+{}]+");
string replacement = "";
List<string> normal = new List<string>();
Regex regExPattern = new Regex(regPattern);
dataGridView1.Rows.Clear();
List<string> cleanDirNames = new List<string>();
try
{
if (regExPattern.IsMatch(folderName))
{
string cleanup = regExPattern.Replace(folderName, replacement);
System.IO.Directory.Move(folderName, cleanup);
DataGridViewRow grid = new DataGridViewRow();
grid.CreateCells(dataGridView1);
grid.Cells[0].Value = folderName;
grid.Cells[1].Value = cleanup;
dataGridView1.Rows.Add(grid);
folderName = cleanup;
cleanDirNames.Add(cleanup);
}
else
{
normal.Add(folderName);
}
}
catch(Exception e)
{
throw;
}
DirectoryInfo di = new DirectoryInfo(folderName);
DirectoryInfo[] diArr = di.GetDirectories();
List<string> subdirectories = new List<string>();
try
{
foreach (DirectoryInfo subdir in diArr)
{
subdirectories.Add(subdir.ToString());
}
}
catch(Exception e)
{
throw;
}
try
{
foreach (string folder in subdirectories)
{
string sF = folder;
RenameFolder(folderName + "\\" + sF);
}
}
catch(Exception e)
{
throw;
}
}
private void button1_Click_1(object sender, EventArgs e)
{
Application.Exit();
}
}
I'm not hitting any errors--the app does what it's supposed to do (in this case, make sure folder names do not contain the invalid chars defined in the regex)...however it's just an issue of output not displaying on the dgv.
Any help would be appreciated.
Probably there's no match for your regex... this way no row is being created and added to dataGridView1.
Have you debugged the code? Try to insert a breakpoint within the if statement right after regExPattern.IsMatch. See if the debugger stops there. This way you can assert that a new row is being created.
I'll try to help you more if that holds true.
actually nevermind. figured out that b/c my method keeps calling itself, the datagridview1.Rows.Clear() would clear out everything, everytime the method called itself. Hence no output. Thanks for all your help though Leniel!

MOSS 2007, C#, Web Part - Log Retrievel using LinkButtons

Technology: SharePoint/MOSS 2007 --
IDE: Visual Studio 2008 --
Language: C#
I have created a SharePoint/MOSS 2007 web part that displays a list of log files.
The log files are rendered on screen as LinkButtons. The LinkButtons are within a DataTable that is set as the data source of a SPGridView and bound to it.
This SPGridView object is then added to the 'Controls' within the overridden "CreateChildControls()" method of the web part.
I am utilising the following "DownloadAssistant" helper class to display a specified file.
It's "DownloadFile" method is called from the '.Click' event of each LinkButton.
using System;
using System.Web;
/// <summary>
/// A class that helps to build download buttons/links on the fly
/// </summary>
static public class DownloadAssistant
{
static public void DownloadFile(string filePath)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Concat("attachment; filename=", filePath));
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(filePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
}
After one LinkButton is clicked on screen, I receive the download pop up window as expected and can go ahead and open the first log file. However after this first log file is opened, i.e. after the first LinkButton click event is triggered, I cannot trigger any other .Click event - it is as it I need to post back to the screen. When I click on any of the other LinkButtons nothing happens?
The Web Part code:
namespace LogRetrievalWebPart
{
[Guid("fd243ec2-83e3-4bad-af5e-c5c16acbc6dd")]
public class LogRetrievalWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
// Member variables prefixed with "m_"
private Label m_InfoLbl;
private SPGridView m_GridView;
private DataTable m_LogFileDataTable;
private DropDownList m_DirectoryDropDown;
private const String DROPDOWN_OPTION_DEFAULT = "---";
private const String DROPDOWN_OPTION_TRACE_LOGS = "Trace Logs";
private const String DROPDOWN_OPTION_BATCH_LOGS = "Batch Logs";
private const String DROPDOWN_OPTION_OTHER_LOGS = "Other Logs";
public LogRetrievalWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected override void CreateChildControls()
{
EnsureChildControls();
base.CreateChildControls();
m_InfoLbl = new Label();
Label dropDownLbl = new Label();
dropDownLbl.Text = " Please select a directory: ";
this.Controls.Add(dropDownLbl);
m_DirectoryDropDown = new DropDownList();
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_DEFAULT);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_TRACE_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_BATCH_LOGS);
m_DirectoryDropDown.Items.Add(DROPDOWN_OPTION_OTHER_LOGS);
m_DirectoryDropDown.TextChanged += new EventHandler(directoryDropdown_TextChanged);
m_DirectoryDropDown.AutoPostBack = true;
m_LogFileDataTable = new DataTable("LogFiles");
AddColums();
m_GridView = new SPGridView();
m_GridView.AutoGenerateColumns = false;
BoundField idField = new BoundField();
idField.DataField = "ID";
idField.HeaderText = "ID";
m_GridView.Columns.Add(idField);
TemplateField colName = new TemplateField();
colName.HeaderText = "Log File Name";
colName.SortExpression = "LogFileName";
colName.ItemTemplate = new LinkTemplate("LogFileName", "Path");
m_GridView.Columns.Add(colName);
this.Controls.Add(m_DirectoryDropDown);
this.Controls.Add(m_InfoLbl);
this.Controls.Add(m_GridView);
this.Load += new EventHandler(LogRetrievalWebPart_Load);
this.PreRender += new EventHandler(LogRetrievalWebPart_PreRender);
}
void LogRetrievalWebPart_Load(object sender, EventArgs e)
{
EnsureChildControls();
}
protected void directoryDropdown_TextChanged(object sender, EventArgs e)
{
ViewState["LogRetrieval"] = null;
String selectedDirectoryName = m_DirectoryDropDown.SelectedItem.Text;
if (DROPDOWN_OPTION_TRACE_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** TRACE Logs: *** ";
GetLogFiles("LogFiles/TraceLogs");
}
else if (DROPDOWN_OPTION_BATCH_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** BATCH Logs: *** ";
GetLogFiles("PortalExecutables/Logs");
}
else if (DROPDOWN_OPTION_OTHER_LOGS.Equals(selectedDirectoryName))
{
m_InfoLbl.Text = " *** OTHER Logs: *** ";
GetLogFiles("PortalExecutables/GMExecutables");
}
else
{
m_InfoLbl.Text = " *** No Logs to display for this selection!!! *** ";
}
ViewState["LogRetrieval"] = m_LogFileDataTable;
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
private void GetLogFiles(string aSelectedDirectory)
{
string directoryPath = HttpContext.Current.Server.MapPath(ResolveUrl("/LogFiles/" + aSelectedDirectory));
DirectoryInfo directory = new DirectoryInfo(directoryPath);
FileInfo[] files = directory.GetFiles();
int count = 1;
foreach (FileInfo fileInfo in files)
{
string fullFileName = fileInfo.FullName;
string fileName = fileInfo.ToString();
AddRow(count, fileName, fullFileName);
count++;
}
}
private void AddRow(int id, string logFileName, string fullFileName)
{
DataRow newRow = m_LogFileDataTable.Rows.Add();
newRow["ID"] = id;
newRow["LogFileName"] = logFileName;
newRow["Path"] = fullFileName;
}
private void AddColums()
{
DataColumn idCol = m_LogFileDataTable.Columns.Add("ID", typeof(Int32));
idCol.Unique = true;
m_LogFileDataTable.Columns.Add("LogFileName", typeof(String));
m_LogFileDataTable.Columns.Add("Path", typeof(String));
}
public void LogRetrievalWebPart_PreRender(object sender, EventArgs e)
{
if (this.Page.IsPostBack)
{
if (ViewState["LogRetrieval"] != null)
{
m_LogFileDataTable = (DataTable)ViewState["LogRetrieval"];
m_GridView.DataSource = m_LogFileDataTable;
m_GridView.DataBind();
}
}
}
public class LinkTemplate : ITemplate
{
string logFileName;
string logFilePath;
public LinkTemplate(string fieldName, string path)
{
logFileName = fieldName;
logFilePath = path;
}
public void InstantiateIn(Control container)
{
LinkButton link = new LinkButton();
container.Controls.Add(link);
link.DataBinding += new EventHandler(link_DataBinding);
link.Click += new EventHandler(link_Click);
}
private void link_DataBinding(Object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DataRowView dataRow = (DataRowView)((SPGridViewRow)link.NamingContainer).DataItem;
link.Text = dataRow[logFileName].ToString();
link.CommandArgument = dataRow[logFilePath].ToString();
}
private void link_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
DownloadAssistant.DownloadFile(link.CommandArgument);
}
}
}
}
I found a solution.
I had to:
Set the button's client-side click event to: "exportRequested=true;"
Register the some JavaScript: For exact details, refer to:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/55136e4e-e1f7-4a79-9b75-be09cd5594c2

Categories