I want to make a program to open some directory and monitor when they are closed, but I had some trouble.
If Process opened explorer.exe, the process object will auto close right away, but
notepad.exe will not.
What should I do?
string fileOpenPath = "F:\\testOpen";
string fileHidePath = "F:\\test...\\";
Process p = new Process();
p.StartInfo.FileName = "explorer";
p.StartInfo.Arguments = fileOpenPath;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(Dir_Closed);
if (!Directory.Exists(fileOpenPath))
{
Directory.Move(fileHidePath, fileOpenPath);
p.Start();
}
else
{
p.Start();
}
Related
I have a following sql code, if I set AutoDetectChangesEnabled and ValidateOnSaveEnabled to false. When there is a race condition in database, is it possible that my string process is processing half way then exit the using.
using (DbContext dbContext = new DbContext()) {
dbContext.Configuration.AutoDetectChangesEnabled = false;
dbContext.Configuration.ValidateOnSaveEnabled = false;
string a = dbContext.sp_getsomething().FirstOrDefault();
string b = a.substring(2);
//and other string processing
}
I have a Windows service that periodically uploads files to an FTP server, and will then redownload the file to check that the bytes match exactly. For most files it seems ok, but one of the files we're using recently is a 10mb CSV file and the files are always slightly different (by a couple of bytes).
Below are the upload, download and file compare methods. Note that the Download is setting UseBinary as true but the upload isn't - could this be why?
public string Upload(FileInfo fi, string targetFilename)
{
//copy the file specified to target file: target file can be full path or just filename (uses current dir)
//1. check target
string target;
if (targetFilename.Trim() == "")
{
//Blank target: use source filename & current dir
target = this.CurrentDirectory + fi.Name;
}
else if (targetFilename.Contains("/"))
{
//If contains / treat as a full path
target = AdjustDir(targetFilename);
}
else
{
//otherwise treat as filename only, use current directory
target = CurrentDirectory + targetFilename;
}
string URI = Hostname + target;
//perform copy
System.Net.FtpWebRequest ftp = GetRequest(URI);
//Set request to upload a file in binary
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftp.UseBinary = false;
//Notify FTP of the expected size
ftp.ContentLength = fi.Length;
//create byte array to store: ensure at least 1 byte!
const int BufferSize = 2048;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead;
string result = null;
//open file for reading
using (FileStream fs = fi.OpenRead())
{
try
{
//open request to send
using (Stream rs = ftp.GetRequestStream())
{
do
{
dataRead = fs.Read(content, 0, BufferSize);
rs.Write(content, 0, dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
}
}
catch (Exception x)
{
result = URI + " - " + x.ToString();
}
finally
{
//ensure file closed
fs.Close();
}
}
ftp = null;
return result;
}
#endregion
public bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite)
{
//1. check target
if (targetFI.Exists && !(PermitOverwrite))
{
throw (new ApplicationException("Target file already exists"));
}
//2. check source
string target;
if (sourceFilename.Trim() == "")
{
throw (new ApplicationException("File not specified"));
}
else if (sourceFilename.Contains("/"))
{
//treat as a full path
target = AdjustDir(sourceFilename);
}
else
{
//treat as filename only, use current directory
target = CurrentDirectory + sourceFilename;
}
string URI = Hostname + target;
//3. perform copy
System.Net.FtpWebRequest ftp = GetRequest(URI);
//Set request to download a file in binary mode
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
//open request and get response stream
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (FileStream fs = targetFI.OpenWrite())
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
targetFI.Delete();
throw;
}
}
responseStream.Close();
}
response.Close();
}
return true;
}
Public Function FileCompare(ByVal file1 As String, ByVal file2 As String) As Boolean
' Checks to see if two files are the same
Dim file1byte As Integer
Dim file2byte As Integer
Dim fs1 As FileStream
Dim fs2 As FileStream
If file1 = file2 Then
Return True
End If
fs1 = New FileStream(file1, FileMode.Open)
fs2 = New FileStream(file2, FileMode.Open)
' Simple length test
If fs1.Length <> fs2.Length Then
fs1.Close()
fs2.Close()
Return False
End If
Do
file1byte = fs1.ReadByte()
file2byte = fs2.ReadByte()
Loop While file1byte = file2byte And file1byte <> -1
fs1.Close()
fs2.Close()
Return ((file1byte - file2byte) = 0)
End Function
I have an external WCF well work from the second call, the first is very slow takes 20 seconds.
My web.config
https://drive.google.com/a/integrens.com/file/d/0B8Ix7-GIED4eUVdNOTNYN215RVU/view?usp=sharing
My code
string mensaje = "";
mensaje = DateTime.Now.ToString();
System.Net.ServicePointManager.UseNagleAlgorithm = true;
System.Net.ServicePointManager.Expect100Continue = false;
System.Net.ServicePointManager.CheckCertificateRevocationList = true;
EnvioSunat.billServiceClient obj = new EnvioSunat.billServiceClient();
//ASMX.billService obj = new ASMX.billService();
byte[] data = File.ReadAllBytes(#"C:\inetpub\wwwroot\ws_integrensfe\FacturaElectronica\20566598389-REDDIGITALDELPERUS.A.C\DocumentosElectronico\20566598389-01-FT01-00000012\20566598389-01-FT01-00000012.zip");
//obj.Open();
var datarpta = obj.sendBill("20566598389-01-FT01-00000012.zip", data);
//obj.Close();
mensaje = mensaje + "-" + DateTime.Now.ToString();
Label1.Text = mensaje;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url, SPUserToken.SystemAccount))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFolder folder = web.Folders["ContractorDetails"];
SPFileCollection filecol = folder.Files;
Boolean replaceExistingFiles = true;
string filename = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
byte[] contents = new byte[Convert.ToInt32(FileUpload.PostedFile.ContentLength)];
SPFile addedFile = filecol.Add(filename, contents, replaceExistingFiles);
SPItem newItem = addedFile.Item;
newItem["Title"] = ddlTitle.SelectedValue;
newItem["First Name"] = tbFirstName.Text;
newItem["Middle Name"] = tbMiddleName.Text;
newItem["Last Name"] = tbLastName.Text;
newItem["NT User Name"] = tbNtuser.Text;
newItem["Contract Firm"] = tbContractFirm.Text;
newItem["Employee Type"] = tbEmpType.Text;
newItem["Division"] = ddlDivision.SelectedValue;
newItem["Location"] = ddlLocation.SelectedValue;
newItem["Contract Start Date"] = dateTimeStart.SelectedDate;
newItem["Contract End Date"] = dateTimeEnd.SelectedDate;
newItem["Project Term"] = Convert.ToInt32(tbProjectTerm.Text);
// newItem["Manager"] = PeopleEditor1.t
newItem["Comments"] = tbcomments.Text;
newItem.Update();
addedFile.Update();
web.AllowUnsafeUpdates = false;
}
}
});
}
Can you just try to upload file from UI to check field is mandatory or not?
I am trying to automate ie.This is my code to catch ie window
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.FileName = "IExplore.exe";
psi.Arguments = "-nomerge about:blank ";
psi.WindowStyle = ProcessWindowStyle.Normal;
Process p = new Process();
p.StartInfo = psi;
if (p.Start())
{
int maxWait = 10000, wait = 0;
while (!p.HasExited && (p.MainWindowHandle == IntPtr.Zero))
{
wait += 10;
Thread.Sleep(10);
p.Refresh();
if (wait > maxWait) break;
}
wait = 0;
while (!p.HasExited && (_IE == null))
{
_IE = null;
ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();//here i get exception
foreach (InternetExplorer Browser in m_IEFoundBrowsers)
{
if (Browser.HWND == (int)p.MainWindowHandle)
{
_IE = Browser;
break;
}
}
if ((_IE != null) || (wait > maxWait)) break;
else
{
wait += 10;
Thread.Sleep(10);
}
}
if (_IE != null)
{
IE.Visible = true;
IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
}
else
{
Console.WriteLine("Problem opening IE!");
}
}
This code works fine normally but when i try to launch application via remoteapp then i get exception i guess reason is some access related but nt sure wht to do. please help
Finally got it working just replace above big code with small one
**
_IE = new InternetExplorer();
IE.Visible = true;
IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
**
But here also i get above exception if automation failed and ie gets stuck then rest all automation will start throwing this exception. The resolution to that is i need to close the instance of failed ie from taskmanager then all will work fine again.