I have written the following code in a Timer's Tick event to checking if the file modification time of an image has changed then copy that image and save it to another directory. Sometimes GetLastWrittenTime() doesn't change even though the file has already been overwritten.
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp"))
{
DateTime filetime=File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
if (!filetime.Equals(lastmMdifiedTime))
{
if (txtkapan.Text != "" && txtlot.Text != "")
{
if (reg.Read("AUTOPATH") == null || reg.Read("AUTOPATH").Equals(""))
{
Directory.CreateDirectory("D:\\" + txtkapan.Text + "\\" + txtlot.Text);
}
else
{
Directory.CreateDirectory(reg.Read("AUTOPATH")+"\\" + txtkapan.Text + "\\" + txtlot.Text);
}
string image_name;
if (txtlot.Text.Length <= 3 || txtparty.Text.Length <= 3 || txtkapan.Text.Length <= 3)
{
image_name = txtparty.Text.Substring(0, txtparty.Text.Length) + "_" + txtkapan.Text.Substring(0, txtkapan.Text.Length) + "_" + txtlot.Text.Substring(0, txtlot.Text.Length) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
else
{
image_name = txtparty.Text.Substring(0, 3) + "_" + txtkapan.Text.Substring(0, 3) + "_" + txtlot.Text.Substring(0, 3) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
img.Save(reg.Read("AUTOPATH") + "\\" + txtkapan.Text + "\\" + txtlot.Text + "\\" + image_name, ImageFormat.Jpeg);
lastmMdifiedTime = File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString());
}
}
else { }
}
}
Please tell me what is wrong in my code.
when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}
I need some help about the following program code! Why this code (write) throw an error?
Writing:
using (IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamWriter w = new StreamWriter(f.OpenFile("data.cfg", FileMode.Create)))
{
w.Write(penz.Text + " || " + tipus.Text + " || " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
}
}
Reading:
IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication();
{
StreamReader r = new StreamReader(f.OpenFile("data.cfg", FileMode.OpenOrCreate));
{
fullmoney = int.Parse(r.ReadLine());
teljes.Text = "Full Money: " + fullmoney + " .-";
}
}
I am trying to create a hash text file. The code works, the problem is that once the streamwriter starts the process it won't stop until it is finished. I want to break up the output file into smaller parts. How do I stop the streamwriter and start a new file without starting the process over again?
string infile = #"ntlmchar.txt";
string hashfile = #"ntlmhash.txt"; //File that includes the hash and clear test
string charfile = #"ntlmchar.txt"; //File that only has the clear text
string oldCharFile = ""; //Temp file to apply to infile.
int cint = 1; //The number of characters in the file
string str_cint = cint.ToString(); //convert cint to string
int pint = 1; //The number of parts to the character file
string str_pint = pint.ToString(); //convert pint to string
int cm = 4; //Max number of characters
int pm = 4000; //Man number of parts
int line = 0; //line index number
while (cint <= cm)
{
if (!File.Exists(infile))
{
for (int ci =1; ci <= cm; ci++)
{
str_cint = cint.ToString();
for (int pi =1; pi <= pm; pi++)
{
str_pint = pint.ToString();
// System.Console.WriteLine("Inner for loop cint file does not exist" +cint +" pint " + pint);
// System.Console.WriteLine("Inner for loop str_cint file does not exist " + str_cint + " cint " + cint);
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
pint = pi;
oldCharFile = charfile;
infile = oldCharFile;
if (File.Exists(infile)) break;
// System.Console.WriteLine("inner loop file " + infile);
}
// System.Console.WriteLine("outer for loop cint " + cint + " pint " + pint);
// System.Console.WriteLine("infile not found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
// System.Console.WriteLine("No work files found " + infile + " " + oldCharFile + " " + charfile + " " + hashfile);
}
else if (File.Exists(infile))
{
// Create a file to write to.
// System.Console.WriteLine("cint at the start of else if " + cint + " str_cint " + str_cint);
infile = oldCharFile;
str_cint = cint.ToString();
// System.Console.WriteLine("cint after assign to str_cint " + cint + " str_cint " + str_cint);
pint=1;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
//System.Console.WriteLine(infile + " " + oldCharFile + " " + charfile + " " + hashfile);
// System.Console.WriteLine("Infile found " + cint + " " + pint);
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
foreach (string s in alpha)
{
if (line <= 2000000)
{
string j = i + s;
string str = Program.Ntlm(j);
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
// System.Console.WriteLine("line before writing to file " + line + " in charfile " + charfile);
h.WriteLine("{0}, {1}", j, str);
c.WriteLine("{0}", j);
line++;
// System.Console.WriteLine("h file" + h + " c file" + c);
}
else
{
h.Flush();
c.Flush();
pint++;
str_pint = pint.ToString();
hashfile = "ntlmhash" + str_cint + "_" + str_pint + ".txt";
charfile = "ntlmchar" + str_cint + "_" + str_pint + ".txt";
line = 1;
System.Console.WriteLine("line after writing to part of file " + line + " in charfile " + charfile);
}
}
}
I assume you're trying to get 2,000,000 items per file? You just need to restructure a little.
Right now you have:
using (StreamWriter h = new StreamWriter(hashfile))
using (StreamWriter c = new StreamWriter(charfile))
using (StreamReader sr = new StreamReader(infile))
{
string i = "";
while ((i = sr.ReadLine()) != null)
{
You need to change your code so that you open the output files later:
using (StreamReader sr = new StreamReader(infile))
{
StreamWriter h = null;
StreamWriter c = null;
try
{
h = new StreamWriter(...);
c = new StreamWriter(...);
string i = "";
while ((i = sr.ReadLine()) != null)
{
// output line here
// and increment line counter.
++line;
if (line > 2000000)
{
// Close the output files and open new ones
h.Close();
c.Close();
h = new StreamWriter(...);
c = new StreamWriter(...);
line = 1;
}
}
}
finally
{
if (h != null) h.Close();
if (c != null) c.Close();
}
}
I have the following condition using in my code but that doesn't look very efficient,is this any better way to handle ?
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".wmv"))
{
if (bitnumber < 400)
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
Break it up in other classes like:
public class AudioFileValidator
{
private List<string> _extensions = new List<string>{".aac", ".mp3"};
public bool IsValid(string filename)
{
if (!_extensions.Contains(Path.GetExtension(filename))
return false;
//validate bitrate etc
}
}
Usage:
var audioValidator = new AudioFileValidator();
if (audioValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
var videoValidator = new VideoFileValidator();
if (videoValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
By doing so you'll get classes with a single responsibility which can be reused in other places and which are easy to unit test.
You could even take it further and introduce a new interface called IMediaFileValidator which all validators implement. and do something like:
foreach (var validator in validators)
{
if (validator.IsValid(filename))
{
// use info from the validator to build the path
var mediaName = validator.MediaName;
path = "ftp://" + ftpServerIP + "/" + mediaName + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
Which would also make your code adhere to Open/Closed principle.
You will need a lot of refactoring. Here are couple of ideas to get you started:
Use String.Format and passed in only value that changed to save you all the repeating the text
Build a dictionary of Extension/Ext-Combination key and set the value to the the destination path. You will then only require one lookup than big nesting if - else statements
Use Path.GetExtension rather than Contains to be more accurate
Eg.
string formatStringNews = "ftp://{0}/news/{1}/";
string formatStringMedia = "ftp://{0}/media/{1}/";
dictionary["wmv"] = formatStringMedia;
dictionary["mp3"] = formatStringNews;
....
string key = Path.GetExtension(filename);
path = string.Format(dictionary[key], serverName, programName);
Something like this is a nice short solution to your problem and I believe it handles all of the cases your if statements are handling.
String[] videoExtensions = { "wmv", "m4v", "mp4", "flv" };
String[] audioExtensions = { "aac", "mp3" };
String ext = Path.GetExtension(filename).ToLower();
String path = "ftp://" + ftpServerIP + "/";
if (-1 != Array.IndexOf(videoExtensions, ext)) {
if ("wmv".equals(ext) && bitnumber > 400)
path += "media/lib/" + programName + "/" + date + "/";
else
path += "mpegmedia/news/" + programName + "/video/podcast/";
}
else if (-1 != Array.IndexOf(audioExtensions, ext)) {
path += "mpegmedia/news/" + programName + "/audio/podcast/";
}
else {
// handle unknown extension types as desired
}
UploadCondition(path, filename);
Use a switch statement and System.IO.Path.GetExtension.
select (System.IO.Path.GetExtension(filename))
{
case ".wmv":
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
break;
case ".m4v":
case ".mp4":
case ".flv":
case ".mpg":
case ".mp3":
default:
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
I'm guessing you'll want variations for the last block, but this should be easy enough to modify.
At the very least you could convert it into an if/elseif statement:
if (ic....)
{
...
} else if (ic...) {
...
}
I assume, at a time your filename will be either be .m4v, .flv,.mp4 etc...so here goes the code..
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
else if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else
{
//No Match found
}
and the best approach would be to use Switch(fileExtn)
You could perhaps make it a bit simpler like
if (filename.Contains(".wmv"))
// path = set the path as you require
and after all the ifs end call your method
UploadCondition(path, filename);
Better would be to extract the extension .wmv, .m4v from filename and make this into a switch whereby you set the path.