Search Results

Search found 266 results on 11 pages for 'fileinfo'.

Page 6/11 | < Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Simple Excel Export with EPPlus

    - by Jesse Taber
    Originally posted on: http://geekswithblogs.net/GruffCode/archive/2013/10/30/simple-excel-export-with-epplus.aspxAnyone I’ve ever met who works with an application that sits in front of a lot of data loves it when they can get that data exported to an Excel file for them to mess around with offline. As both developer and end user of a little website project that I’ve been working on, I found myself wanting to be able to get a bunch of the data that the application was collecting into an Excel file. The great thing about being both an end user and a developer on a project is that you can build the features that you really want! While putting this feature together I came across the fantastic EPPlus library. This library is certainly very well known and popular, but I was so impressed with it that I thought it was worth a quick blog post. This library is extremely powerful; it lets you create and manipulate Excel 2007/2010 spreadsheets in .NET code with a high degree of flexibility. My only gripe with the project is that they are not touting how insanely easy it is to build a basic Excel workbook from a simple data source. If I were running this project the approach I’m about to demonstrate in this post would be front and center on the landing page for the project because it shows how easy it really is to get started and serves as a good way to ease yourself in to some of the more advanced features. The website in question uses RavenDB, which means that we’re dealing with POCOs to model the data throughout all layers of the application. I love working like this so when it came time to figure out how to export some of this data to an Excel spreadsheet I wanted to find a way to take an IEnumerable<T> and just have it dumped to Excel with each item in the collection being modeled as a single row in the Excel worksheet. Consider the following class: public class Employee { public int Id { get; set; } public string Name { get; set; } public decimal HourlyRate { get; set; } public DateTime HireDate { get; set; } } Now let’s say we have a collection of these represented as an IEnumerable<Employee> and we want to be able to output it to an Excel file for offline querying/manipulation. As it turns out, this is dead simple to do with EPPlus. Have a look: public void ExportToExcel(IEnumerable<Employee> employees, FileInfo targetFile) { using (var excelFile = new ExcelPackage(targetFile)) { var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A1"].LoadFromCollection(Collection: employees, PrintHeaders: true); excelFile.Save(); } } That’s it. Let’s break down what’s going on here: Create a ExcelPackage to model the workbook (Excel file). Note that the ‘targetFile’ value here is a FileInfo object representing the location on disk where I want the file to be saved. Create a worksheet within the workbook. Get a reference to the top-leftmost cell (addressed as A1) and invoke the ‘LoadFromCollection’ method, passing it our collection of Employee objects. Behind the scenes this is reflecting over the properties of the type provided and pulling out any public members to become columns in the resulting Excel output. The ‘PrintHeaders’ parameter tells EPPlus to grab the name of the property and put it in the first row. Save the Excel file All of the heavy lifting here is being done by the ‘LoadFromCollection’ method, and that’s a good thing. Now, this was really easy to do, but it has some limitations. Using this approach you get a very plain, un-styled Excel worksheet. The column widths are all set to the default. The number format for all cells is ‘General’ (which proves particularly interesting if you have a DateTime property in your data source). I’m a “no frills” guy, so I wasn’t bothered at all by trading off simplicity for style and formatting. That said, EPPlus has tons of samples that you can download that illustrate how to apply styles and formatting to cells and a ton of other advanced features that are way beyond the scope of this post.

    Read the article

  • C# file Decryption - Bad Data

    - by Jon
    Hi all, I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Thank you

    Read the article

  • Pack URI how to get contents of folder

    - by Konrad
    I have the following directory structure (all files as resources): Project \Maps +map.xml ... +something.xml To get to every file I use following syntax: "pack://application:,,,/Maps/map.xml" My question is - how to get contents of pack://application:,,,/Maps/ as FileInfo [] or List.

    Read the article

  • Slow performance when utilizing Interop.DSOFile to search files by Custom Document Property

    - by Gradatc
    I am new to the world of VB.NET and have been tasked to put together a little program to search a directory of about 2000 Excel spreadsheets and put together a list to display based on the value of a Custom Document Property within that spreadsheet file. Given that I am far from a computer programmer by education or trade, this has been an adventure. I've gotten it to work, the results are fine. The problem is, it takes well over a minute to run. It is being run over a LAN connection. When I run it locally (using a 'test' directory of about 300 files) it executes in about 4 seconds. I'm not sure even what to expect as a reasonable execution speed, so I thought I would ask here. The code is below, if anyone thinks changes there might be of use in speeding things up. Thank you in advance! Private Sub listByPt() Dim di As New IO.DirectoryInfo(dir_loc) Dim aryFiles As IO.FileInfo() = di.GetFiles("*" & ext_to_check) Dim fi As IO.FileInfo Dim dso As DSOFile.OleDocumentProperties Dim sfilename As String Dim sheetInfo As Object Dim sfileCount As String Dim ifilesDone As Integer Dim errorList As New ArrayList() Dim ErrorFile As Object Dim ErrorMessage As String 'Initialize progress bar values ifilesDone = 0 sfileCount = di.GetFiles("*" & ext_to_check).Length Me.lblHighProgress.Text = sfileCount Me.lblLowProgress.Text = 0 With Me.progressMain .Maximum = di.GetFiles("*" & ext_to_check).Length .Minimum = 0 .Value = 0 End With 'Loop through all files in the search directory For Each fi In aryFiles dso = New DSOFile.OleDocumentProperties sfilename = fi.FullName Try dso.Open(sfilename, True) 'grab the PT Initials off of the logsheet Catch excep As Runtime.InteropServices.COMException errorList.Add(sfilename) End Try Try sheetInfo = dso.CustomProperties("PTNameChecker").Value Catch ex As Runtime.InteropServices.COMException sheetInfo = "NONE" End Try 'Check to see if the initials on the log sheet 'match those we are searching for If sheetInfo = lstInitials.SelectedValue Then Dim logsheet As New LogSheet logsheet.PTInitials = sheetInfo logsheet.FileName = sfilename PTFiles.Add(logsheet) End If 'update progress bar Me.progressMain.Increment(1) ifilesDone = ifilesDone + 1 lblLowProgress.Text = ifilesDone dso.Close() Next lstResults.Items.Clear() 'loop through results in the PTFiles list 'add results to the listbox, removing the path info For Each showsheet As LogSheet In PTFiles lstResults.Items.Add(Path.GetFileNameWithoutExtension(showsheet.FileName)) Next 'build error message to display to user ErrorMessage = "" For Each ErrorFile In errorList ErrorMessage += ErrorFile & vbCrLf Next MsgBox("The following Log Sheets were unable to be checked" _ & vbCrLf & ErrorMessage) PTFiles.Clear() 'empty PTFiles for next use End Sub

    Read the article

  • Beginner - C# iteration through directory to produce a file list

    - by dassouki
    The end goal is to have some form of a data structure that stores a hierarchal structure of a directory to be stored in a txt file. I'm using the following code and so far, and I'm struggling with combining dirs, subdirs, and files. /// <summary> /// code based on http://msdn.microsoft.com/en-us/library/bb513869.aspx /// </summary> /// <param name="strFolder"></param> public static void TraverseTree ( string strFolder ) { // Data structure to hold names of subfolders to be // examined for files. Stack<string> dirs = new Stack<string>( 20 ); if ( !System.IO.Directory.Exists( strFolder ) ) { throw new ArgumentException(); } dirs.Push( strFolder ); while ( dirs.Count > 0 ) { string currentDir = dirs.Pop(); string[] subDirs; try { subDirs = System.IO.Directory.GetDirectories( currentDir ); } catch ( UnauthorizedAccessException e ) { MessageBox.Show( "Error: " + e.Message ); continue; } catch ( System.IO.DirectoryNotFoundException e ) { MessageBox.Show( "Error: " + e.Message ); continue; } string[] files = null; try { files = System.IO.Directory.GetFiles( currentDir ); } catch ( UnauthorizedAccessException e ) { MessageBox.Show( "Error: " + e.Message ); continue; } catch ( System.IO.DirectoryNotFoundException e ) { MessageBox.Show( "Error: " + e.Message ); continue; } // Perform the required action on each file here. // Modify this block to perform your required task. /* foreach ( string file in files ) { try { // Perform whatever action is required in your scenario. System.IO.FileInfo fi = new System.IO.FileInfo( file ); Console.WriteLine( "{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime ); } catch ( System.IO.FileNotFoundException e ) { // If file was deleted by a separate application // or thread since the call to TraverseTree() // then just continue. MessageBox.Show( "Error: " + e.Message ); continue; } } */ // Push the subdirectories onto the stack for traversal. // This could also be done before handing the files. foreach ( string str in subDirs ) dirs.Push( str ); foreach ( string str in files ) MessageBox.Show( str ); }

    Read the article

  • .NET Impersonate and file upload issues

    - by Jagd
    I have a webpage that allows a user to upload a file to a network share. When I run the webpage locally (within VS 2008) and try to upload the file, it works! However, when I deploy the website to the webserver and try to upload the file through the webpage, it doesn't work! The error being returned to me on the webserver says "Access to the path '\05prd1\emp\test.txt' is denied. So, obviously, this is a permissions issue. The network share is configured to allow full access both to me (NT authentication) and to the NETWORK SERVICE (which is .NET's default account and what we have set in our IIS application pool as the default user for this website). I have tried this with and without impersonation upon the webserver and neither way works, yet both ways work on my local machine (in other words, with and without impersonation works on my local machine). The code that does the file upload is below. Please note that the code below includes impersonation, but like I said above, I've tried it with and without impersonation and it's made no difference. if (fuCourses.PostedFile != null && fuCourses.PostedFile.ContentLength > 0) { System.Security.Principal.WindowsImpersonationContext impCtx; impCtx = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate(); try { lblMsg.Visible = true; // The courses file to be uploaded HttpPostedFile file = fuCourses.PostedFile; string fName = file.FileName; string uploadPath = "\\\\05prd1\\emp\\"; // Get the file name if (fName.Contains("\\")) { fName = fName.Substring( fName.LastIndexOf("\\") + 1); } // Delete the courses file if it is already on \\05prd1\emp FileInfo fi = new FileInfo(uploadPath + fName); if (fi != null && fi.Exists) { fi.Delete(); } // Open new file stream on \\05prd1\emp and read bytes into it from file upload FileStream fs = File.Create(uploadPath + fName, file.ContentLength); using (Stream stream = file.InputStream) { byte[] b = new byte[4096]; int read; while ((read = stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, read); } } fs.Close(); lblMsg.Text = "File Successfully Uploaded"; lblMsg.ForeColor = System.Drawing.Color.Green; } catch (Exception ex) { lblMsg.Text = ex.Message; lblMsg.ForeColor = System.Drawing.Color.Red; } finally { impCtx.Undo(); } } Any help on this would be very appreciated!

    Read the article

  • .NET Impersonate not working!

    - by Jagd
    I have a webpage that allows a user to upload a file to a network share. When I run the webpage locally (within VS 2008) and try to upload the file, it works! However, when I deploy the website to the webserver and try to upload the file through the webpage, it doesn't work! The error being returned to me on the webserver says "Access to the path '\05prd1\emp\test.txt' is denied. So, obviously, this is a permissions issue. The network share is configured to allow full access both to me (NT authentication) and to the NETWORK SERVICE (which is .NET's default account and what we have set in our IIS application pool as the default user for this website). I have tried this with and without authentication, and neither one works on the webserver, yet both ways works on my local machine. The code that does the file upload is below. Please note that the code below includes impersonation, but like I said above, I've tried it with and without impersonation and it's made no difference. if (fuCourses.PostedFile != null && fuCourses.PostedFile.ContentLength > 0) { System.Security.Principal.WindowsImpersonationContext impCtx; impCtx = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate(); try { lblMsg.Visible = true; // The courses file to be uploaded HttpPostedFile file = fuCourses.PostedFile; string fName = file.FileName; string uploadPath = "\\\\05prd1\\emp\\"; // Get the file name if (fName.Contains("\\")) { fName = fName.Substring( fName.LastIndexOf("\\") + 1); } // Delete the courses file if it is already on \\05prd1\emp FileInfo fi = new FileInfo(uploadPath + fName); if (fi != null && fi.Exists) { fi.Delete(); } // Open new file stream on \\05prd1\emp and read bytes into it from file upload FileStream fs = File.Create(uploadPath + fName, file.ContentLength); using (Stream stream = file.InputStream) { byte[] b = new byte[4096]; int read; while ((read = stream.Read(b, 0, b.Length)) > 0) { fs.Write(b, 0, read); } } fs.Close(); lblMsg.Text = "File Successfully Uploaded"; lblMsg.ForeColor = System.Drawing.Color.Green; } catch (Exception ex) { lblMsg.Text = ex.Message; lblMsg.ForeColor = System.Drawing.Color.Red; } finally { impCtx.Undo(); } } Any help on this would be very appreciated!

    Read the article

  • IO Exception: directory name is invalid using directory from File System Watcher OnChanged Event

    - by Bi
    My C# application throws a System.IO.IOExcepton (The directory name is invalid) for the following code for implementing a filewatcher: public void OnChanged(object source, FileSystemEventArgs e) { DirectoryInfo dList = new DirectoryInfo(e.FullPath); FileInfo[] TxtFiles = dList.GetFiles("*.TXT"); } e.FullPath is "C:/Documents and Settings/Bi/Application Data/TestApp/Reports\\0MA01P62240_000005798_TRI_4947712701738551.TXT". If you notice it seems to append a "\\" to the path when it tracks the file. Any idea what the problem may be?

    Read the article

  • Php miniserver downloader bandwidth

    - by snikolov
    $httpsock = @socket_create_listen("9090"); if (!$httpsock) { print "Socket creation failed!\n"; exit; } while (1) { $client = socket_accept($httpsock); $input = trim(socket_read ($client, 4096)); $input = explode(" ", $input); $input = $input[1]; $fileinfo = pathinfo($input); switch ($fileinfo['extension']) { default: $mime = "text/html"; } if ($input == "/") { $input = "index.html"; } $input = ".$input"; if (file_exists($input) && is_readable($input)) { echo "Serving $input\n"; $contents = file_get_contents($input); $output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents"; } else { //$contents = "The file you requested doesn't exist. Sorry!"; //$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents"; $filename = "dada"; $file = fopen($filename, 'r'); $filesize = filesize($filename); $buffer = fread($file, $filesize); $send = array("Output"=$buffer,"filesize"=$filesize,"filename"=$filename); $file = $send['filename']; $filesize = $send['filesize']; $output = 'HTTP/1.0 200 OK\r\n'; $output .= "Content-type: application/octet-stream\r\n"; $output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n'; $output .= "Content-Length:$filesize\r\n"; $output .= "Accept-Ranges: bytes\r\n"; $output .= "Cache-Control: private\n\n"; $output .= $send['Output']; $output .= "Content-Transfer-Encoding: binary"; $output .= "Connection: Keep-Alive\r\n"; } socket_write($client, $output); socket_close ($client); } socket_close ($httpsock); Hello i have create a code here to work as a webserver downloader the client can request files and download, i got it working at last however, i would like to know if the webserver can show much bandwidth the user request via sockets, perl has the same option as php but its more hardcore than php, i dont understand much about perl, i even saw that a miniwebserver can show much the client user pulls from the server would it be possible that you can assist me with this coding, i much aprreciate it thank you guys.

    Read the article

  • delete all files and folders in multiple directory but leave the directoy

    - by NightsEVil
    well i like this nice of code right here it seems to work awsome but i cant seem to add any more directories to it DirectoryInfo dir = new DirectoryInfo(@"C:\temp"); foreach(FileInfo files in dir.GetFiles()) { files.Delete(); } foreach (DirectoryInfo dirs in dir.GetDirectories()) { dirs.Delete(true); } i would also like to add in special folders aswell like History and cookies and such how would i go about doing that (i would like to include atleast 4-5 different folders)

    Read the article

  • PHP miniwebsever file download

    - by snikolov
    $httpsock = @socket_create_listen("9090"); if (!$httpsock) { print "Socket creation failed!\n"; exit; } while (1) { $client = socket_accept($httpsock); $input = trim(socket_read ($client, 4096)); $input = explode(" ", $input); $input = $input[1]; $fileinfo = pathinfo($input); switch ($fileinfo['extension']) { default: $mime = "text/html"; } if ($input == "/") { $input = "index.html"; } $input = ".$input"; if (file_exists($input) && is_readable($input)) { echo "Serving $input\n"; $contents = file_get_contents($input); $output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents"; } else { //$contents = "The file you requested doesn't exist. Sorry!"; //$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents"; function openfile() { $filename = "a.pl"; $file = fopen($filename, 'r'); $filesize = filesize($filename); $buffer = fread($file, $filesize); $array = array("Output"=$buffer,"filesize"=$filesize,"filename"=$filename); return $array; } $send = openfile(); $file = $send['filename']; $filesize = $send['filesize']; $output = 'HTTP/1.0 200 OK\r\n'; $output .= "Content-type: application/octet-stream\r\n"; $output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n'; $output .= "Content-Length:$filesize\r\n"; $output .= "Accept-Ranges: bytes\r\n"; $output .= "Cache-Control: private\n\n"; $output .= $send['Output']; $output .= "Content-Transfer-Encoding: binary"; $output .= "Connection: Keep-Alive\r\n"; } socket_write($client, $output); socket_close ($client); } socket_close ($httpsock); Hello, I am snikolov i am creating a miniwebserver with php and i would like to know how i can send the client a file to download with his browser such as firefox or internet explore i am sending a file to the user to download via sockets, but the cleint is not getting the filename and the information to download can you please help me here,if i declare the file again i get this error in my server Fatal error: Cannot redeclare openfile() (previously declared in C:\User s\fsfdsf\sfdsfsdf\httpd.php:31) in C:\Users\hfghfgh\hfghg\httpd.php on li ne 29, if its possible, i would like to know if the webserver can show much banwdidth the user request via sockets, perl has the same option as php but its more hardcore than php i dont understand much about perl, i even saw that a miniwebserver can show much the client user pulls from the server would it be possible that you can assist me with this coding, i much aprreciate it thank you guys.

    Read the article

  • Save file info in program c#

    - by rubentjeuh
    Hello, Is it possible to save some fields in the program, or do I have to write them to a file? Example: 1) I open a file (with OpenFileDialog) and put it in a FileInfo 2) close the program 3) restart the program 4) go to open - recent - select the previous File Thanks

    Read the article

  • Problem writing HTML content to Word document in ASP.NET

    - by saran
    I am trying to export the HTML page contents to Word. My Html display page is: What is your favourite color? NA List the top three school ? one National two Devs three PS And a button for click event. The button click event will open MS word and paste the page contents in word. The word page contains the table property of html design page. It occurs only in Word 2003. But in word 2007 the word document contains the text with out table property. How can I remove this table property in word 2003. I am not able to add the snapshots. Else i will make you clear. I am designing the web page by aspx. I am exporting the web page content by the following code. protected void Button1_Click(object sender, EventArgs e) { Response.ContentEncoding = System.Text.Encoding.UTF7; System.Text.StringBuilder SB = new System.Text.StringBuilder(); System.IO.StringWriter SW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlTW = new System.Web.UI.HtmlTextWriter(SW); tbl.RenderControl(htmlTW); string strBody = "<html>" + "<body>" + "<div><b>" + htmlTW.InnerWriter.ToString() + "</b></div>" + "</body>" + "</html>"; Response.AppendHeader("Content-Type", "application/msword"); Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName); Response.ContentEncoding = System.Text.Encoding.UTF7; string fileName1 = "C://Temp/Excel" + DateTime.Now.Millisecond.ToString(); BinaryWriter writer = new BinaryWriter(File.Open(fileName1, FileMode.Create)); writer.Write(strBody); writer.Close(); FileStream fs = new FileStream(fileName1, FileMode.Open, FileAccess.Read); byte[] renderedBytes; // Create a byte array of file stream length renderedBytes = new byte[fs.Length]; //Read block of bytes from stream into the byte array fs.Read(renderedBytes, 0, System.Convert.ToInt32(fs.Length)); //Close the File Stream fs.Close(); FileInfo TheFile = new FileInfo(fileName1); if (TheFile.Exists) { File.Delete(fileName1); } Response.BinaryWrite(renderedBytes); Response.Flush(); Response.End(); }

    Read the article

  • C# delete all files and folders in multiple directory but leave the directoy

    - by NightsEVil
    well i like this nice of code right here it seems to work awsome but i cant seem to add any more directories to it { DirectoryInfo dir = new DirectoryInfo(@"C:\temp"); foreach(FileInfo files in dir.GetFiles()) { files.Delete(); } foreach (DirectoryInfo dirs in dir.GetDirectories()) { dirs.Delete(true); } } i would also like to add in special folders aswell like History and cookies and such how would i go about doing that (i would like to include atleast 4-5 different folders)

    Read the article

  • C#: My callback function gets called twice for every Sent Request

    - by Madi D.
    I've Got a program that uploads/downloads files into an online server,Has a callback to report progress and log it into a textfile, The program is built with the following structure: public void Upload(string source, string destination) { //Object containing Source and destination to pass to the threaded function KeyValuePair<string, string> file = new KeyValuePair<string, string>(source, destination); //Threading to make sure no blocking happens after calling upload Function Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.TUpload)); t.Start(file); } private void TUpload(object fileInfo) { KeyValuePair<string, string> file = (KeyValuePair<string, string>)fileInfo; /* Some Magic goes here,Checking The file and Authorizing Upload */ var ftiObject = new FtiObject () { FileNameOnHDD = file.Key, DestinationPath = file.Value, //Has more data used for calculations. }; //Threading to make sure progress gets callback gets called. Thread t = new Thread(new ParameterizedThreadStart(amazonHandler.UploadOP)); t.Start(ftiObject); //Signal used to stop progress untill uploadCompleted is called. uploadChunkDoneSignal.WaitOne(); /* Some Extra Code */ } private void UploadOP(object ftiSentObject) { FtiObject ftiObject = (FtiObject)ftiSentObject; /* Some useless code to create the uri and prepare the ftiObject. */ // webClient.UploadFileAsync will open a thread that // will upload the file and report // progress/complete using registered callback functions. webClient.UploadFileAsync(uri, "PUT", ftiObject.FileNameOnHDD, ftiObject); } I got a callback that is registered to the Webclient's UploadProgressChanged event , however it is getting called twice per sent request. void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e) { FtiObject ftiObject = (FtiObject )e.UserState; Logger.log(ftiObject.FileNameOnHDD, (double)e.BytesSent ,e.TotalBytesToSend); } Log Output: Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:1024 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:2048 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241 Filename: C:\Text1.txt Uploaded:3072 TotalFileSize: 665241 Etc... I am watching the Network Traffic using a watcher, and only 1 request is being sent. Some how i cant Figure out why the callback is being called twice, my doubt was that the callback is getting fired by each thread opened(the main Upload , and TUpload), however i dont know how to test if thats the cause. Note: The reason behind the many /**/ Comments is to indicate that the functions do more than just opening threads, and threading is being used to make sure no blocking occurs (there a couple of "Signal.WaitOne()" around the code for synchronization)

    Read the article

  • IO Exception: directory name is invalid C#

    - by Bi
    My C# application throws a System.IO.IOExcepton (The directory name is invalid) for the following code for implementing a filewatcher: public void OnChanged(object source, FileSystemEventArgs e) { DirectoryInfo dList = new DirectoryInfo(e.FullPath); FileInfo[] TxtFiles = dList.GetFiles("*.TXT"); } e.FullPath is "C:/Documents and Settings/Bi/Application Data/TestApp/Reports\\0MA01P62240_000005798_TRI_4947712701738551.TXT". If you notice it seems to append a "\\" to the path when it tracks the file. Any idea what the problem may be? Thanks

    Read the article

  • Best practice to include log4Net external config file in ASP.NET

    - by Martin Buberl
    I have seen at least two ways to include an external log4net config file in an ASP.NET web application: Having the following attribute in your AssemblyInfo.cs file: [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log.config", Watch = true)] Calling the XmlConfigurator in the Global.asax.cs: protected void Application_Start() { XmlConfigurator.Configure(new FileInfo("Log.config")); } What would be the best practice to do it?

    Read the article

  • How Do you Declare a Dependancy Property in VB.Net 3.0

    - by discwiz
    My company is stuck on .Net 3.0. The task I am trying to tackle is simple, I need to bind the IsChecked property of the CheckBoxResolvesCEDAR to the CompletesCEDARWork in my Audio class. The more I read about this it appears that I have to declare CompletesCEDARWork as dependancy propert, but I can not find a good example of how this is done. I found this example, but when I pasted into my code I get an "is not defined" error for GetValue and I have not successfully figure out what MyCode is supposed to represent. Any help/examples would be greatly appreciated. Thanks Public Shared ReadOnly IsSpinningProperty As DependencyProperty = DependencyProperty.Register("IsSpinning", GetType(Boolean), GetType(MyCode)) Public Property IsSpinning() As Boolean Get Return CBool(GetValue(IsSpinningProperty)) End Get Set(ByVal value As Boolean) SetValue(IsSpinningProperty, value) End Set End Property Here is my slimed down Audio Class as it stands now. Imports System.Xml Imports System Imports System.IO Imports System.Collections.ObjectModel Imports System.ComponentModel Public Class Audio Private mXMLString As String Private mTarpID As Integer Private mStartTime As Date Private mEndTime As Date Private mAudioArray As Byte() Private mFileXMLInfo As IO.FileInfo Private mFileXMLStream As IO.FileStream Private mFileAudioInfo As IO.FileInfo Private mDisplayText As String Private mCompletesCEDARWork As Boolean Private Property CompletesCEDARWork() As Boolean Get Return mCompletesCEDARWork End Get Set(ByVal value As Boolean) mCompletesCEDARWork = value End Set End Property And here is my XML Datatemplate where I set the binding. <DataTemplate x:Key="UploadLayout" DataType="Audio"> <Border BorderBrush="LightGray" CornerRadius="8" BorderThickness="1" Padding="10" Margin="0,3,0,0"> <StackPanel Orientation="Vertical"> <TextBlock Text="{Binding Path=DisplayText}"> </TextBlock> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <TextBlock Text="TARP ID" VerticalAlignment="Center"/> <ComboBox x:Name="ListBoxTarpIDs" ItemsSource="{Binding Path=TarpIds}" SelectedValue="{Binding Path=TarpID}" BorderBrush="Transparent" Background="Transparent" > </ComboBox> </StackPanel> <CheckBox x:Name="CheckBoxResolvesCEDAR" Content="Resolves CEDAR Work" IsChecked="{Binding ElementName=Audio,Path=CompletesCEDARWork,Mode=TwoWay}"/> </StackPanel> </Border> </DataTemplate>

    Read the article

  • how to insert into database from stored procedure in log4net?

    - by Samreen
    I have to log thread context properties like this: string logFilePath = AppDomain.CurrentDomain.BaseDirectory + "log4netconfig.xml"; FileInfo finfo = new FileInfo(logFilePath); log4net.Config.XmlConfigurator.ConfigureAndWatch(finfo); ILog logger = LogManager.GetLogger("Exception.Logging"); log4net.ThreadContext.Properties["MESSAGE"] = exception.Message; log4net.ThreadContext.Properties["MODULE"] = "module1"; log4net.ThreadContext.Properties["COMPONENT"] = "component1"; logger.Debug("test"); and the configuration file is: <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <logger name="Exception.Logging" level="Debug"> <appender-ref ref="AdoNetAppender"/> </logger> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <connectionString value="Data Source=xe;User ID=test;Password=test;" /> <connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <bufferSize value="10000"/> <commandText value="Log_Exception_Pkg.Insert_Log" /> <commandType value="StoredProcedure" /> <parameter> <parameterName value="@p_Error_Message" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{MESSAGE}"/> </layout> </parameter> <parameter> <parameterName value="@p_Module" /> <dbType value="String" /> <size value="225" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{MODULE}"/> </layout> </parameter> <parameter> <parameterName value="@p_Component" /> <dbType value="String" /> <size value="225" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{COMPONENT}"/> </layout> </parameter> </appender> </log4net> </configuration> But its not inserting them in the database. How can I get that to work?

    Read the article

  • Compare DateTime ticks on two machines

    - by vani
    Is it a viable option to compare two FileInfo.CreationTimeUtc.Ticks of two files on two different computers to see which version is newer - or is there a better way? Do Ticks depend on OS time or are they really physical ticks from some fixed date in the past?

    Read the article

  • Is there way to determine if a file has been executed or not in C#?

    - by Shane
    I'm looking for a way to determine if a file has been executed or not. I've looked a bit into FileInfo's LastAccessTime but this doesn't seem to change when a file is executed. I've also looked into FileSystemWatcher but this also doesn't seem to offer a solution. Is there such a thing as a file execution listener or is there another way? If it helps, i'm looking to write a folder listener that renames an .avi file within it after it has been watched/executed.

    Read the article

  • Closing a process that open in code

    - by AmirHossein
    I create a WordTemplate with some placeholders for field,in code I insert value in this placeholders and show it to user. protected void Button1_Click(object sender, EventArgs e) { string DocFilePath = ""; //string FilePath = System.Windows.Forms.Application.StartupPath; object fileName = @"[...]\asset\word templates\FormatPeygiri1.dot"; DocFilePath = fileName.ToString(); FileInfo fi = new FileInfo(DocFilePath); if (fi.Exists) { object readOnly = false; object isVisible = true; object PaperNO = "PaperNO"; object PaperDate = "PaperDate"; object Peyvast = "Peyvast"; object To = "To"; object ShoName = "ShoName"; object DateName = "DateName"; Microsoft.Office.Interop.Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref isVisible, ref missing, ref missing, ref missing); WordApp.ActiveDocument.FormFields.get_Item(ref PaperNO).Result = TextBox_PaperNO.Text; string strPaperDate = string.Format("{0}/{1}/{2}", PersianDateTimeHelper.GetPersainDay(DateTimePicker_PaperDate.SelectedDate), PersianDateTimeHelper.GetPersainMonth(DateTimePicker_PaperDate.SelectedDate), PersianDateTimeHelper.GetPersainYear(DateTimePicker_PaperDate.SelectedDate)); WordApp.ActiveDocument.FormFields.get_Item(ref PaperDate).Result = strPaperDate; WordApp.ActiveDocument.FormFields.get_Item(ref Peyvast).Result = TextBox_Peyvast.Text; WordApp.ActiveDocument.FormFields.get_Item(ref To).Result = TextBox_To.Text; ; WordApp.ActiveDocument.FormFields.get_Item(ref ShoName).Result = TextBox_ShoName.Text; string strDateName = string.Format("{0}/{1}/{2}", PersianDateTimeHelper.GetPersainDay(DateTimePicker_DateName.SelectedDate), PersianDateTimeHelper.GetPersainMonth(DateTimePicker_DateName.SelectedDate), PersianDateTimeHelper.GetPersainYear(DateTimePicker_DateName.SelectedDate)); WordApp.ActiveDocument.FormFields.get_Item(ref DateName).Result = strDateName; aDoc.Activate(); WordApp.Visible = true; aDoc = null; WordApp = null; } else { MessageBox1.Show("File Not Exist!"); } it work good and successfully! but when a user close the Word,her Process not closed and exists in Task Manager Process list. this process name is WINWORD.exe I know that I can close process whit code [process.Kill()] but I don't know which process that I should to kill. if I want to kill all process with name [WINWORD.exe] all Word window closed.but I want to close specific Word window and kill process that I opened. How to do it?

    Read the article

  • C#, how to delete all files and folders in a directory?

    - by JL
    Using C#, how can I delete all files and folders from a directory, but still keep the root directory? I have this System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(GetMessageDownloadFolderPath()); foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories()) { dir.Delete(true); } Is this the cleanest way to do it?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >