After I restart my PC, my background service works fine. If I reinstalled or made any changes to the DB, my PC access path ".zip" denied. one more thing same background is running in another PC.
Two background services running in two different PCs to exchange the data.
Here's the code:
public void GetFilesFromWebAPIAndCountTemplates(DateTime startTime,DateTime endTime,string webAPIURL,string code,string localPath)
{
ZipLocationsCount zipLocation = null;
count = 0;
if (startTime < endTime)
{
WebApiCall apiCall = new WebApiCall();
Thread.Sleep(10000);
var zipByteResponse = apiCall.CallZipWebApi(webAPIURL, "api/ZIPEnrollmentsDownload/ZIPResponse?startTime=" + startTime + "&endTime=" + endTime+ "&locationCode="+code, null, Constants.Get);
lgmr.Log(string.Concat(serviceName, " ", code, ": Get Response From WebAPI successfully"), LoggingManager.LogType.Info);
if (zipByteResponse.Result != null && zipByteResponse.Result.Length > 0)
{
string fileName = code + "_Enrollments.zip";
try
{
ConvertIntoZipAndMoveToBackUp(localPath, fileName, zipByteResponse.Result, code);
}
catch(Exception ex)
{
//GetFilesFromWebAPIAndCountTemplates(startTime, endTime, webAPIURL, code, localPath);
ecount = 0;
strECount = "Fail to Zip";
lgmr.Log(string.Concat(serviceName, " ", code, " count:", ecount, ": Failed to Converted to ZIP", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
goto label1;
}
}
else
{
ecount = 0;
if(ecount == 0)
{
strECount = "No Enrolments";
}
lgmr.Log(string.Concat(serviceName, " ", code, ": No Enrollments"), LoggingManager.LogType.Info);
}
}
else
{
lgmr.Log(string.Concat(serviceName, " ",code, ": Start Date Should be lass than End Date"), LoggingManager.LogType.Info);
}
FPSyncHistory fpSync = new FPSyncHistory();
fpSync.LocationCode = code;
fpSync.FromDate = startTime;
fpSync.ToDate = endTime;
fpSync.FPExported = ecount;
fpSync.Status = true;
fpSync.CreatedBy = 1;
fpSync.CreatedOn = DateTime.Now;
fPSyncHistories.Add(fpSync);
label1:
zipLocation = new ZipLocationsCount() { LocationCode = code, FromDate = startTime, ToDate = endTime, EnrollmentsCount = strECount };
if (zipLocation.FromDate < zipLocation.ToDate)
{
zipLocationsCounts.Add(zipLocation);
}
}
the Above Method i am calling into another method
public void GetZipResponseFromWebAPI()
{
try
{
zipLocationsCounts = new List<ZipLocationsCount>();
fPSyncHistories = new List<FPSyncHistory>();
DateTime sTime = new DateTime();
DateTime startTime = new DateTime();
DateTime eTime = new DateTime();
DateTime endTime = new DateTime();
foreach (FPSyncLocationDetail fpLocation in tmlEntity.FPSyncLocationDetails)
{
var findHistory = tmlEntity.FPSyncHistories.FirstOrDefault(x => x.LocationCode == fpLocation.Code);
if (findHistory == null)
{
if(fpLocation.Status == true)
{
sTime = DateTime.Now.AddDays(-1);
startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
eTime = DateTime.Now.AddDays(-1);
endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);
GetFilesFromWebAPIAndCountTemplates(startTime,endTime,fpLocation.WebAPIURL,fpLocation.Code,fpLocation.LocalFPFolderPath);
}
}
else if (findHistory != null)
{
var locationLastDates = from n in tmlEntity.FPSyncHistories
group n by n.LocationCode into g
select new { LocationCode = g.Key, ToDate = g.Max(t => t.ToDate) };
foreach (var loc in locationLastDates)
{
if (fpLocation.Code == loc.LocationCode)
{
if (fpLocation.Status == true)
{
sTime = loc.ToDate.AddDays(1);
startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
eTime = DateTime.Now.AddDays(-1);
endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);
GetFilesFromWebAPIAndCountTemplates(startTime, endTime, fpLocation.WebAPIURL, fpLocation.Code, fpLocation.LocalFPFolderPath);
}
}
}
}
}
}
catch (Exception ex)
{
string InnerException = ex.InnerException != null ? ex.InnerException.ToString() : "";
lgmr.Log(string.Concat("Error at GetZipResponseFromWebAPI", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
return;
}
}
finally CallWebAPI method logic below
public async Task<byte[]> CallZipWebApi(String WebApiUri, String uri, StringContent obj, string type)
{
try
{
count++;
HttpResponseMessage resMeg;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
client.BaseAddress = new Uri(WebApiUri);
lgmr.Log(string.Concat(uri,": Sending Request to WebAPI"), LoggingManager.LogType.Info);
if (type == Constants.Get)
{
resMeg =await client.GetAsync(uri);
}
else
{
resMeg =await client.PostAsync(uri, obj);
}
lgmr.Log(string.Concat(uri,": Receive Response From WebAPI"), LoggingManager.LogType.Info);
var Bytes =await resMeg.Content.ReadAsByteArrayAsync();
//byte[] mybyteArray = null;
//Task<byte[]> Bytes = ProcessURLAsync(uri,client);
lgmr.Log(string.Concat(": Read the Data from WebAPI Response"), LoggingManager.LogType.Info);
return Bytes;
}
}
}
public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
{
string Destinationpath = ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"] + "\\" + code;
try
{
ZipArchive archive = null;
if (File.Exists(localPath + "\\" + fileName))
{
File.Delete(localPath + "\\" + fileName);
}
archive = ZipFile.Open(localPath + "\\" + fileName, ZipArchiveMode.Create);
archive.Dispose();
lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created", localPath + "\\" + fileName), LoggingManager.LogType.Info);
File.WriteAllBytes(localPath + "\\" + fileName, zipByteResponse);
lgmr.Log(string.Concat(serviceName, " ", code, ": Download Zipfile from the WebAPI Response"), LoggingManager.LogType.Info);
archive = ZipFile.OpenRead(localPath + "\\" + fileName);
ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
strECount = ecount.ToString();
lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(localPath + "\\" + entry.Name))
{
File.Delete(localPath + "\\" + entry.Name);
}
entry.ExtractToFile(localPath + "\\" + entry.Name);
}
archive.Dispose();
File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("Enrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
}
catch (Exception ex)
{
//File.Delete(localPath + "\\" + fileName);
//File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
ecount = 0;
lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
throw ex;
}
}
A few things that you can look at.
First, use the using statement to create the archive, that will make sure that it gets disposed.
Second, why do you check if the file exists, delete it, then create it with ZipFile just to Write it with File? Look at this
Third, use Path class. It will make sure that all your backslashed is correct, and it looks neater.
Fourth, check if a file can be created in the folder
Check if this code gives you the same result.
public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
{
string Destinationpath = Path.Combine(ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"], code);
try
{
fileName = Path.GetFileNameWithoutExtension(fileName) + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss.fff") + ".zip"; //This will ensure that you have a unique filename to create
File.WriteAllBytes(Path.Combine(localPath, fileName), zipByteResponse);
lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created and Downloaded from the WebAPI Response", Path.Combine(localPath, fileName)), LoggingManager.LogType.Info);
using (var archive = ZipFile.OpenRead(Path.Combine(localPath, fileName)))
{
ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
strECount = ecount.ToString();
lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(Path.Combine(localPath, entry.Name)))
{
File.Delete(Path.Combine(localPath, entry.Name));
}
entry.ExtractToFile(Path.Combine(localPath, entry.Name));
}
}
File.Move(Path.Combine(localPath, fileName), Path.Combine(Destinationpath, code + string.Format("Enrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now)));
}
catch (Exception ex)
{
//File.Delete(localPath + "\\" + fileName);
//File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
ecount = 0;
lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
throw ex;
}
}
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
and
if(closeRequest == true) responseFile.Close();
So now my problem:
If i try to download a file, it does so, closes the response. All good.
However, if I type wrong URL (with 404 returned or smth), I can't close the response because it gives me nullreference error. So I close it only when I get a response.
However, after providing wrong URL and not closing response, further tries to download anything result in timeout (even if URL is correct).
Why is that happening and can I resolve it somehow?
EDIT: Full code of class:
public void DownloadAndReplace(string webFile, string sourceFile)
{
var requestFile = (HttpWebRequest)WebRequest.Create(webFile);
var requestMD5 = (HttpWebRequest)WebRequest.Create(webFile + ".md5");
var requestSHA = (HttpWebRequest)WebRequest.Create(webFile + ".sha");
bool closeRequest = true;
_location = sourceFile + "\\" + OriginalFileName(webFile);
requestFile.Method = "HEAD";
requestFile.Timeout = 2000;
HttpWebResponse responseFile = null;
HttpWebResponse responseMD5 = null;
HttpWebResponse responseSHA = null;
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
if (!File.Exists(_location) || responseFile.LastModified > File.GetLastWriteTime(_location))
{
downloadFile(webFile, _location);
if (_controlsRef.chooseMD5.Checked)
{
try
{
responseMD5 = (HttpWebResponse)requestMD5.GetResponse();
downloadFile(webFile + ".md5", _location);
responseMD5.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".md5");
}
}
else if (_controlsRef.chooseSHA1.Checked)
{
try
{
responseSHA = (HttpWebResponse)requestSHA.GetResponse();
downloadFile(webFile + ".sha", _location);
responseSHA.Close();
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message + " " + webFile + ".sha");
}
}
}
else MessageBox.Show("Newest version");
if(closeRequest == true) responseFile.Close();
public void downloadFile(string urlAddress, string location)
{
_fileHasher = new HashFile(_controlsRef);
using (var downloadClient = new WebClient())
{
downloadClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
downloadClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri URL = new Uri(urlAddress);
if (location == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
location = location + "\\" + OriginalFileName(urlAddress);
this._location = location;
}
else location = _location;
_downloadStopWatch.Start();
if (File.Exists(location))
{
File.Delete(location);
}
if (_isFile == true)
{
try
{
downloadClient.DownloadFileAsync(URL, location);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
_isFile = false;
}
}
}
}
private string OriginalFileName(string urlAddress)
{
var requestFile = (HttpWebRequest)WebRequest.Create(urlAddress);
requestFile.Method = "HEAD";
HttpWebResponse responseFile = null;
string originalFileName = "";
try
{
responseFile = (HttpWebResponse)requestFile.GetResponse();
}
catch (WebException exResponse)
{
MessageBox.Show(exResponse.Message);
_isFile = false;
}
if (_isFile == true)
{
int segmentLenght = responseFile.ResponseUri.Segments.Length;
originalFileName = responseFile.ResponseUri.Segments[segmentLenght - 1];
responseFile.Close();
}
return originalFileName;
}
To further clarify:
I provide URL for existing file 1. All is ok.
I provide URL for existing file 2. All is ok.
I provide URL for non-exisitng file 3. It throws me an 404 error.
I provide URL for existing file 4. I get program hangup and timeout.
Wrap your HttpWebResponse inside a using statement so that the object can be disposed correctly.
Something like this:
try
{
using(responseFile = (HttpWebResponse)requestFile.GetResponse())
{
...your code...
}
}
catch (WebException exRequestFile)
{
MessageBox.Show(exRequestFile.Message);
closeRequest = false;
}
"using" reference: https://msdn.microsoft.com/en-us/library/yh598w02.aspx
I have this code in my winform C# application:
public void InsertValidationDate(Validar v, string descanso)
{
bool insert = false;
try
{
bd.con.Open();
bdag.bd.trans = bdag.bd.con.BeginTransaction();
insert = InsertDate(v);
if (insert == true)
{
MessageBox.Show("Insert Ok");
pk = ReturnInsertDate(DateTime.Parse(v.Date), v.User);
insert = UpdateReference(DateTime.Parse(v.Date), pk);
if (insert == false)
{
Rollback();
MessageBox.Show("Update Error");
}
else
{
Commit();
MessageBox.Show("Update OK");
}
}
}
catch (Exception ex)
{
Rollback();
}
finally
{
con.Close();
}
}
After displaying the message ("Insert Ok") the connection to the database is closed and the transaction is not posible commited. Why? Because the Insert function don't close the database connection. Any Ideas? Thanks!!.
public int ReturnInsertDate(DateTime date, int user)
{
int validate = -1;
try
{
bd.CadSQL = "select " + bd.Validar.id + " from " + bd.Validar.tabla + " where ";
bd.CadSQL += bd.Validar.date + " = '" + date.Year + "-" + date.Month.ToString("d2") + "-" + date.Day.ToString("d2") + "'";
bd.CadSQL += " and " + bd.Validar.user+ " = " + user;
bd.comandoSQL.CommandText = bd.CadSQL;
bd.reader = bd.comandoSQL.ExecuteReader();
while (bd.reader.Read())
{
if (!bd.reader.IsDBNull(0))
validate = bd.reader.GetInt32(0);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
bd.reader.Close();
}
return validate;
}
public bool UpdateReference(DateTime date, int validate)
{
bool updateR = false;
try
{
bd.CadSQL = "update " + bd.Fichar.tabla;
bd.CadSQL += " set " + bd.Fichar.validateId + " = " + validate;
bd.CadSQL += " where " + bd.Fichar.date + " = '" + date.Year + "-" + date.Month.ToString("d2") + "-" + date.Day.ToString("d2") + "'";
bd.comandoSQL.CommandText = bd.CadSQL;
bd.comandoSQL.ExecuteNonQuery();
updateR = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return updateR ;
}
i would set your transaction as follows since it seems you are working with different connection objects.
using (var scope = TransactionHelper.Instance)
{
var process = true;
var aMessage = "";
try
{
//Enter you code and functions here
//Whenever you find a piece of code to be working incorrectly, Raise an error
if(!someCode(blabla))
throw new Exception("This someCode quited on me!");
//Whenever your code does what it needs to do, end with a commit
scope.Commit();
}
catch(Exception ex) //Catch whatever exception might occur
{
scope.FullRollBack();
aMessage = ex.Message;
process = false;
}
finally
{
//only here you will use messageboxes to explain what did occur during the process
if (process)
MessageBox.Show("Succesfully Committed!");
else
MessageBox.Show(string.Format("Rollback occurred, exception Message: {0}"
, aMessage);
}
}
It's a bit strange that you're referring to con when you open the connection, and then you use bdag.bd.con for the BeginTransaction call. Are you absolutely certain these two variables are pointing to the same connection object?
These codes allow me to access the registry and grab out the lastvisitedMRU values which are in a non-readable format. What I did here was to convert them into a readable format. I placed them in an array and output them into console.
The output goes like this:
C : \ P r o g r a m F i l e s \ i P o d \ f i l e . t x t
How do I remove the spacings in between?
Thanks in advance.
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
String[] names = rk.GetValueNames();
Console.WriteLine("Subkeys of " + rk.Name);
Console.WriteLine("-----------------------------------------------");
foreach (String s in names)
{
try
{
if (s == "MRUList")
{
continue;
}
else
{
try
{
Byte[] byteValue = (Byte[])rk.GetValue(s);
string str = BitConverter.ToString(byteValue).Replace("00", "");
str = BitConverter.ToString(byteValue).Replace("-", "");
//str binry AND VAR CONVERTED TEXT
Console.WriteLine(s + " Contains the value of : " + str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= str.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(str.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
String val = Convert.ToString(sb).Replace(" ", "");
Console.WriteLine(s + " Contains the value of : " + val);
}
catch (Exception Errors)
{
Console.WriteLine("An error has occurred: " + Errors.Message);
}
}
//rk.Close();
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
Console.WriteLine("-----------------------------------------------");
//rk.Close();
}
The binary there is unicode encoded. I fixed your code and verified it is working on my XP. However, it doesn't work on Windows 7 or Vista because LastVisitedMRU no longer exists.
static void Main(string[] args)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception ex)
{
Console.WriteLine("An error has occurred: " + ex.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
foreach (String s in rk.GetValueNames())
{
if (s == "MRUList")
{
continue;
}
Byte[] byteValue = (Byte[])rk.GetValue(s);
UnicodeEncoding unicode = new UnicodeEncoding();
string val = unicode.GetString(byteValue);
Console.Out.WriteLine(val);
}
Console.ReadLine();
}