Below is the function where I am trying to execute a function in the background and then carry on without waiting for a result from it.
When debugging the task itself is executed but the actual function within it does not. The rest of the code then carries on like normal.
What could be the issue as there is no error produced after that to indicate otherwise?
This is on a page load.
public ActionResult ExceptionReport(int? id)
{
var ExceptionList = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == id);
if (ExceptionList.Count() == 0)
{
globalInvoice.Status = "Exception Verification";
db.Entry(globalInvoice).State = EntityState.Modified;
db.SaveChanges();
Task.Run(() => ExceptionFinalTests(globalInvoice)); //Function To run in the background
TempData["warning"] = "Verifying all exceptions fixed. A notification will be sent when the verifications are complete.";
return RedirectToAction("Index", "GlobalInvoices");
}
return View(ExceptionList);
}
private void ExceptionFinalTests(GlobalInvoice globalInvoice)
{
RunTests(globalInvoice, true);
decimal TotalPaymentAmount = db.Invoices.Where(m => m.GlobalInvoiceID == globalInvoice.Id).Sum(m => m.Invoice_Amount) ?? 0;
}
GlobalInvoicesController globalInvoicesController = new GlobalInvoicesController();
var ApproverList = globalInvoicesController.GetUserEmailsInRole(globalInvoice, "Reviewer");
globalInvoicesController.Dispose();
var exceptionExistCompulsoryTest = db.Invoices.Where(m => m.ExceptionFlag == true && m.GlobalInvoiceID == globalInvoice.Id);
if (exceptionExistCompulsoryTest.Count() > 0)
{
try
{
string baseUrl = ConfigurationManager.AppSettings["site"];
EmailExtension emailExtension = new EmailExtension();
foreach (var approver in ApproverList)
{
string approvalLink = baseUrl + "/Invoices/ExceptionReport/" + globalInvoice.Id;
StringBuilder mailbody = new StringBuilder();
mailbody.AppendFormat("Hi<br/>");
mailbody.AppendFormat("There are " + exceptionExistCompulsoryTest.Count() + " exceptions for invoice #" + globalInvoice.Id + "that need attention before proceeding. - <a href='" + approvalLink + "'>Click Here</a> <br/><br/>");
mailbody.AppendFormat("Exception Count: {0}<br/>", exceptionExistCompulsoryTest.Count());
mailbody.AppendFormat("Invoice Amount: {0}<br/>", TotalPaymentAmount.ToString("C"));
mailbody.AppendFormat("Reviewed By: {0} <br/>", "");
mailbody.AppendFormat("Approved By: {0} <br/>", "");
EmailVM emailVM = new EmailVM()
{
Subject = "Invoice - #" + globalInvoice.Id,
EmailAddress = approver,
Message = mailbody.ToString()
};
emailExtension.SendEmail(emailVM);
}
}
catch (Exception ex)
{
LogWriter.WriteLog(ex.Message);
LogWriter.WriteLog(ex.StackTrace);
}
}
}
private void RunTests(GlobalInvoice globalInvoice, bool retestFlag = false)
{
List<Invoice> invoices;
var vendorTests = globalInvoice.Vendor.VendorTests;
string[] testsToRun = vendorTests.Split(',');
if (retestFlag == true)
{
if (globalInvoice.Vendor.VendorHasHierarchy == true)
{
testsToRun = new string[] { "Account Number", "Hierarchy" };
}
else
{
testsToRun = new string[] { "Account Number" };
}
}
using (var context = new MyContext())
{
invoices = context.Invoices.Where(m => m.GlobalInvoiceID == globalInvoiceToTestID).ToList();
}
foreach (var test in testsToRun)
{
if (test == "Account Number")
{
LogWriter.WriteLog("Starting Account Number Check : Invoice Batch ID - " + globalInvoice.Id);
AccountNumberCheck(invoices, globalInvoice.VendorID);
LogWriter.WriteLog("Account Number Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
if (test == "Hierarchy")
{
LogWriter.WriteLog("Starting Hierarchy Check : Invoice Batch ID - " + globalInvoice.Id);
BillingHierarchyCheck(invoices);
LogWriter.WriteLog("Hierarchy Check Complete : Invoice Batch ID - " + globalInvoice.Id);
}
}
}
I created transaction publication and tried to create subscription for this publication. Creating subscription in MS Studio works fine, but when I'm using RMO, the table in my subscription base never appear.
What is wrong in my "at first time synchronize initialization"?
How to set "immediately initialization"?
My code:
public static void CreateSub(string publicationName, string publisherName, string subscriberName, string subscriptionDbName, string publicationDbName)
{
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);
TransPublication publication;
TransPullSubscription subscription;
try
{
subscriberConn.Connect();
publisherConn.Connect();
publication = new TransPublication();
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
publication.ConnectionContext = publisherConn;
if (publication.IsExistingObject)
{
if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
{
publication.Attributes |= PublicationAttributes.AllowPull;
}
publication.Attributes |= PublicationAttributes.ImmediateSync;
subscription = new TransPullSubscription();
subscription.ConnectionContext = subscriberConn;
subscription.PublisherName = publisherName;
subscription.PublicationName = publicationName;
subscription.PublicationDBName = publicationDbName;
subscription.DatabaseName = subscriptionDbName;
subscription.SynchronizationAgentProcessSecurity.Login = #"*****";
subscription.SynchronizationAgentProcessSecurity.Password = "****";
subscription.CreateSyncAgentByDefault = true;
subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Continuously;
subscription.Create();
Boolean registered = false;
foreach (TransSubscription existing in publication.EnumSubscriptions())
{
if (existing.SubscriberName == subscriberName&& existing.SubscriptionDBName == subscriptionDbName)
{
registered = true;
}
}
if (!registered)
{
publication.MakePullSubscriptionWellKnown(
subscriberName, subscriptionDbName,
SubscriptionSyncType.Automatic,
TransSubscriberType.ReadOnly);
}
if (subscription.LoadProperties())
{
if (subscription.PublisherSecurity != null)
{
subscription.SynchronizationAgent.Synchronize();// class is not registered error
}
else
{
throw new ApplicationException("There is insufficent metadata to " +
"synchronize the subscription. Recreate the subscription with " +
"the agent job or supply the required agent properties at run time.");
}
}
}
else
{
throw new ApplicationException(String.Format(
"The publication '{0}' does not exist on {1}.",
publicationName, publisherName));
}
}
catch (Exception ex)
{
throw new ApplicationException(string.Format(
"the subscription to {0} could not be created.", publisherName), ex);
}
finally
{
subscriberConn.Disconnect();
publisherConn.Disconnect();
}
}
I have no idea.. why this occurs.
In debug mode it is running well .
however, now I am trying to run my project in IIS web server and
it doesn't runs well.
I can access the main page of my project. but when I try to access the local database, the following error shows up.
this is my log file and codes:
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine("아님여기?"+ex.Message);
file2.Close(); //디버깅 계속................
}
In this catch I have the following error:
provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
I am sorry that I can not explain which line is generating this exception because there's no exception occurring in debug mode...
Here is the code for Page Load:
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
WA = Request.QueryString["WA"];
if (string.IsNullOrEmpty(WA)) WA = "off";
string qstr = null;
qstr = Request.QueryString["vCnt"]; //ㅇㅈ이파라메터 들은 어디서...??
if (qstr != null && qstr != "") vCnt = Int32.Parse(qstr);
if (!IsPostBack)
{
Keywords = Request.QueryString["keywords"]; //ㅇㅈ search main -> searh 버튼 클릭
VideoSearch = Request.QueryString["VideoSearch"];//ㅇㅈ ~^~^~
// 스마트폰에서 포스팅 되었을 때
if (Request.UserAgent.Contains("Android"))
{
if (Request.Cookies["VIDEOSEARCH"] != null && Request.Cookies["VIDEOSEARCH"].Value != "")
{
VideoSearch = Request.Cookies["VIDEOSEARCH"].Value;
MAM.Models.Utils.CookieManager("VIDEOSEARCH", "");
}
}
if (!String.IsNullOrEmpty(Keywords) && !Keywords.Contains("null")) SearchTextbox2.Text = Keywords;
Debug.WriteLine("search text is " + SearchTextbox2.Text);
Debug.Flush();
try
{
if (!string.IsNullOrEmpty(VideoSearch))
{
//ㅇㅈ DNA를 추출하여 유사 동영상을 돌려받음.
string results = RetrieveDNAfromVideo(System.Web.HttpUtility.UrlDecode(VideoSearch)/*video name*/);
string[] lines = results.Split(new string[] { "\r\n" }, StringSplitOptions.None);
vSearchResults = new List<VSearchResult>();
foreach (string line in lines)
{
string[] words = line.Split(',');
VSearchResult vSearchResult = new VSearchResult();
vSearchResult.VideoID = Int32.Parse(words[0]);
vSearchResult.idx = Int32.Parse(words[1]);
vSearchResult.RGBdifferce = Int32.Parse(words[2]);
vSearchResults.Add(vSearchResult);
} //ㅇㅈ vSearchResults : RetrieveDNAfromVideo가 알려준유사동영상정보
MAMDataContext db = new MAMDataContext();
List<int> VideoIDs = (List<int>)vSearchResults.Select(v => v.VideoID).ToList();
//vdo = (List<Video>)(from a in db.Video
// join b in vSearchResults
// on a.id equals b.VideoID
// orderby b.RGBdifferce
// select a).ToList();
vdo = (List<Video>)(from a in db.Videos
where VideoIDs.Contains(a.id)
select a).ToList(); //ㅇㅈ vdo는 결국, RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들
vSearchResults2 = new List<VSearchResult2>();
VSearchResult v1 = null;
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v1 = vSearchResults.Where(t => t.VideoID == v.id).OrderBy(t => t.RGBdifferce).FirstOrDefault();//ㅇㅈ ㅇㄱㅁㅇ
// ㅇㅈ RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들[-> RGBdifferce가 가장작은 애] [] 무슨의미??
v2.idx = v1.idx;
v2.RGBdifferce = v1.RGBdifferce;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Serach done");
Debug.Flush();
}
if (!string.IsNullOrEmpty(Keywords))
{
string ret2 = null;
string str1 = null;
if (string.IsNullOrEmpty(Keywords))
{
Keywords = SearchTextbox2.Text;
}
if (string.IsNullOrEmpty(str1)) str1 = Keywords; //ㅇㅈ str1 은 질의의도??
string[] searchTextArray = str1.Split(' ');
int cnt1 = searchTextArray.Count();
string st1 = ""; string st2 = ""; string st3 = "";
if (cnt1 > 0) st1 = searchTextArray[0];
if (cnt1 > 1) st2 = searchTextArray[1];
if (cnt1 > 2) st3 = searchTextArray[2];
MAMDataContext db = new MAMDataContext();
vdo = (List<Video>)db.Videos.Where(v => v.overview.Contains(st1)
|| (cnt1 > 1 ? v.overview.Contains(st2) : false)
|| (cnt1 > 2 ? v.overview.Contains(st3) : false)).ToList();//ㅇㅈ 검색어를 overview에 가지고 있는 동영상 리스트
vSearchResults2 = new List<VSearchResult2>();
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v2.idx = 0;
v2.RGBdifferce = 0;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Search");
}
}
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine(ex.Message);
file2.Close(); //디버깅 계속................
}
Debug.WriteLine("Search End");
}
if (fUpload.PostedFile != null) //ㅇㅈ
{
fileupload1();
}
else
{
}
}
this is a guess because you did not provide a key information: the connection string.
my guess is that the application is using integrated authentication hence while debugging the access to the database is done using your credentials: as the developer you are likely allowed to do almost everything on the db so the application works correctly.
when the application is deployed the login to the database is performed using the credentials of the application pool used to run the application itself.
as a test you can change the user of the application pool on the iis server to use an account enabled on the db and retry to login.
there are two solutions:
- configure the application pool to use a specific windows user that is allowed to interact with the db
- change the connection string to log onto the db as a sql user (allowed to interact with the db)
I have a button click event in code behind file as follows:
protected void btnArchive_Click(object sender, EventArgs e)
{
try
{
if (projectId == 0)
{
return;
}
Int32 serverPathId = 0;
ProjectArchiveResponse archiveResponse;
if (!int.TryParse(this.ddlSourceServer.SelectedValue, out serverPathId))
return;
if (string.IsNullOrEmpty(hidFileCount.Value))
{
this.ShowMsg(this.divMessage, Resources.Resource.ProjectFileArchiveNotAllowed, MessageType.Failed);
//The project files couldn't be archived until archive operation was completed.
return;
}
ProjectManager projectManager = new ProjectManager(null, BasePage.GetCurrentUser(), null) { IsServiceCall = false};
try
{
archiveResponse = projectManager.StartProjectArchive(projectId, false, () =>
{
foreach (Control control in tdFileList.Controls.Cast<Control>())
{
if (control is Dell.AFP.UserControl.ProjectFileListBaseControl)
{
((ProjectFileListBaseControl)control).Refresh();
}
}
}, false);
if (archiveResponse.MassivePackageID > 0)
{
this.ViewState["transferPackageId"] = archiveResponse.MassivePackageID;
PopupMonitor(archiveResponse.MassivePackageID);
}
//handled for any erorrs while submitting massive package or any unhandled exceptions will be taken care here
if (archiveResponse._CustomError != null && !string.IsNullOrEmpty(archiveResponse._CustomError.Erorrmessage))
{
if (!archiveResponse._CustomError._Erorrtype.Equals(MessageType.Info))
logger.ErrorFormat("Error occurred with details : {0}", archiveResponse._CustomError.Erorrmessage);
ShowMsg(divMessage, archiveResponse._CustomError.Erorrmessage, (MessageType)archiveResponse._CustomError._Erorrtype);
}
}
catch (KnownErrorException ke)
{
//logger.Fatal("UnExpected exception occured. Exception Details " + ke.Message);
logger.Fatal(ke.Message);
if (ke.Error.Type.Equals(DELL.AFP.Management.Exceptions.ErrorType.Warning))
this.ShowMsg(this.divMessage, ke.Message, MessageType.Info);
else
this.ShowMsg(this.divMessage, ke.Message, MessageType.Failed);
}
catch (Exception ke)
{
logger.ErrorFormat("UnExpected exception has occured with details : {0} - {1}", ke.Message, ke.StackTrace);
//ShowMsg(divMessage, "UnExpected exception has occured. Details are logged. Please try after sometime", MessageType.Failed);
ShowMsg(divMessage,ke.Message, MessageType.Failed);
}
}
In this event I am calling a method StartProjectArchive which is in ProjectManager.cs file
StartProjectArchive method in ProjectManager.cs is as follows:
public ProjectArchiveResponse StartProjectArchive(int projectID, bool promoteAfterArchive, Action uiRefresh, bool waitTillTransfered, string archiveNotificationUrl = null)
{
ProjectArchiveResponse projectArchiveResponse = new ProjectArchiveResponse() { ProjectID = projectID, MassivePackageID = -1 };
string sourceServerPath = String.Empty;
int packageID =0;
Int32 sourceServerPathID = GetSourceServerPath(projectID, out sourceServerPath);
var filesWhichNeedsToBeArchived = GetFilesWhichNeedsToBeArchived(projectID, sourceServerPathID, uiRefresh);
if (objFilesNotInSourceServer != null && objFilesNotInSourceServer.Count > 0)
KnownErrorException.Throw("ePRJARCMISSFILE01", string.Join(",", objFilesNotInSourceServer.ToArray()));
if (filesWhichNeedsToBeArchived != null)
{
MassiveServiceClientProxy proxy = new MassiveServiceClientProxy();
Dictionary<string, string> files = new Dictionary<string, string>();
filesWhichNeedsToBeArchived.Select(file => new
{
SourcePath = file.FileName,
DestinationPath = Path.Combine(ConfigurationManager.AppSettings["ArchiveProcessPrefixFolder"],
Path.GetDirectoryName(file.FileName), Path.GetFileName(file.FileName),
projectFilelist.Where(pf => string.Compare(pf.FileName, file.FileName, true) == 0).First().VersionID.ToString(),
Path.GetFileName(file.FileName))
}).ToList().
ForEach(file =>
{
if (!files.ContainsKey(file.SourcePath))
files.Add(file.SourcePath, file.DestinationPath);
});
if (files.Count > 0)
{
string packageDescription = "AFP 4.0: " + projectID.ToString(),
targetServerGroupName = archiveServer.MassiveServerGroupName,
userSuppliedId = "AFP 4.0: " + EndUserInfo.UserName;
try
{
packageID = proxy.SubmitPackageWithDestinationPath(files, packageDescription, new[] { sourceServerPath },
targetServerGroupName, userSuppliedId, MassiveService.MassivePriority.URGENT, true);
}
catch (Exception ex)
{
if (IsServiceCall == true)
KnownErrorException.Throw("wPRJARCMASER01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Failed, Erorrmessage = ex.Message } };
}
if (packageID > 0)
{
ProjectFileBizManager projectFileBM = new ProjectFileBizManager();
projectFileBM.InsertArchiveTransferPackageByProjectFileList(
GetProjectFileIDsByFileName(projectID, filesWhichNeedsToBeArchived.Select(file => file.FileName).ToArray()), filesWhichNeedsToBeArchived.Select(file => file.FileName).ToArray(), packageID, projectID, EndUserInfo.UserId);
TransferPackageBizManager transferPackageBM = new TransferPackageBizManager();
if (promoteAfterArchive)
{
transferPackageBM.UpdateTransferPackageFeature(packageID, promoteAfterArchive);
}
projectArchiveResponse.MassivePackageID = packageID;
if (waitTillTransfered)
{
Task<ProjectArchiveResponse> mainTask = Task<ProjectArchiveResponse>.Factory.StartNew(
() =>
{
Task<Enums.TransferStatusEnum> packageTransfer = Task<Enums.TransferStatusEnum>.Factory.StartNew(
() =>
{
try
{
TransferPackage transferPackage = null;
while (true)
{
transferPackage = transferPackageBM.GetTransferPackage(packageID);
if (transferPackage.TransferStatus.TransferStatusId == (int)Enums.TransferStatusEnum.Submitted || transferPackage.TransferStatus.TransferStatusId == (int)Enums.TransferStatusEnum.Transferring)
Thread.Sleep(8000);
else
break;
}
logger.DebugFormat("Massive package status : {0} for Package : {1}", (Enums.TransferStatusEnum)transferPackage.TransferStatus.TransferStatusId, transferPackage.TransferPackageId);
return (Enums.TransferStatusEnum)transferPackage.TransferStatus.TransferStatusId;
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while trying to find massive package status : {0}", exp);
return Enums.TransferStatusEnum.Submitted;
}
});
try
{
Int32 timeOutInMins = (ConfigurationManager.AppSettings["ProjectArchive_PackageMonitorTimeoutInMinutes"] == null) ? 60 :
Convert.ToInt32(ConfigurationManager.AppSettings["ProjectArchive_PackageMonitorTimeoutInMinutes"]);
if (!Task.WaitAll(new Task[] { packageTransfer }, timeOutInMins * 60 * 1000))
{
projectArchiveResponse.Timedout = true;
projectArchiveResponse.TransferStatus = Enums.TransferStatusEnum.Submitted;
}
else
projectArchiveResponse.TransferStatus = packageTransfer.Result;
logger.DebugFormat("Project Archive Response, Project ID: {0}\n Package ID : {1},\n IsTimedout : {2},\n Timeout value : {3} minutes, \n Transfer Status : {4}", projectArchiveResponse.ProjectID, projectArchiveResponse.MassivePackageID, projectArchiveResponse.Timedout, timeOutInMins, projectArchiveResponse.TransferStatus);
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while waiting to fetch massive package status : {0}", exp);
}
return projectArchiveResponse;
});
if (!string.IsNullOrEmpty(archiveNotificationUrl))
{
mainTask.ContinueWith((a) =>
{
try
{
AFPArchiveNotifyProxy archiveNotification = new AFPArchiveNotifyProxy();
ArchiveNotificationService.ProjectArchiveResponse archiveResponse = new ArchiveNotificationService.ProjectArchiveResponse()
{
MassivePackageID = a.Result.MassivePackageID,
ProjectID = a.Result.ProjectID,
IsTimedout = a.Result.Timedout,
ArchiveStatus = (Enum.Parse(typeof(ArchiveNotificationService.ArchiveStatusEnum), (a.Result.TransferStatus.ToString())) as ArchiveNotificationService.ArchiveStatusEnum?).Value
};
MassiveServiceClientProxy massiveServiceClientProxy = new MassiveServiceClientProxy();
FileTransferRequest[] fileTransferRequests = massiveServiceClientProxy.GetFileStatus(a.Result.MassivePackageID);
archiveResponse.Files = fileTransferRequests.Select(f => f.FileName).ToArray();
archiveNotification.ProjectArchiveUpdate(archiveNotificationUrl, archiveResponse);
logger.DebugFormat("Project Archive Response Notification, Project ID: {0}\n Package ID : {1},\n IsTimedout : {2},\n Archive Status :{3},\n Notification Url : {4},\n Total Files : {5}", archiveResponse.ProjectID, archiveResponse.MassivePackageID, archiveResponse.IsTimedout, archiveResponse.ArchiveStatus, archiveNotificationUrl, archiveResponse.Files.Count());
logger.DebugFormat("Package ID : {0}, Files : {1}", archiveResponse.MassivePackageID, string.Join(",", archiveResponse.Files.ToArray()));
}
catch (Exception exp)
{
logger.ErrorFormat("Project Archive Error, while invoking archive notification : {0}", exp);
}
});
projectArchiveResponse.TransferStatus = Enums.TransferStatusEnum.Submitted;
return projectArchiveResponse;
}
else
{
mainTask.Wait();
}
}
}
else
{
if (IsServiceCall == true)
KnownErrorException.Throw("ePRJARCMASS01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Failed, Erorrmessage = "Massive has not returned the massive packageid" } };
}
}
else
{
// this.ShowMsg(this.divMessage, Resources.Resource.NoFilesToArchive, MessageType.Info);
if (IsServiceCall == true)
KnownErrorException.Throw("wPRJARCNOFILES01");
else
return new ProjectArchiveResponse() { _CustomError = new CustomError { _Erorrtype = Model.ErrorType.Info, Erorrmessage = "There are no files to archive" } };
}
}
return projectArchiveResponse;
}
In this we are taking a parameter as "Action uiRefresh" . we are calling this uiRefresh as method in GetFilesWhichNeedsToBeArchived which was in startArchiveProject method. This Refresh method in tunrn calls the method in code behind file. This was passed as a control when we are invoking startArchiveProject in code behind file. Now I have one more thing which I need to implement. I have a method Pop-Up files in code behind file. I need to call that in ProjectManager.cs class inside the Method GetFilesWhichNeedsTobeArchive. In that pop-up I will have a button and checkboxes. Upon the selection user I need to get the details from pop-up and then I have to continue with the remaining execution in ProjectManger.cs page.
Can someone help on this?
Assuming that you have a button named btnArchive then the add click event subscription, pointing to the method you have (which looks like click-event handle proc)
btnArchive.Click+=(s,e)=>btnArchive_Click(s,e);
Regards
I have a database that may be on the network drive.
There are two things that I want to achieve:
When the first user connects to it in read-only mode (he doesn't
have a read-write access to the location, or the database is
read-only), other users must use the read-only connection also (even
if they have RW access).
When the first user connects to it in RW mode, others can not
connect to the database at all.
I'm using SQLite, and the concurrency should not be the problem, as the database should never be used by more than 10 people at the same time.
UPDATE: This is a sample that I'm trying to make work, so I could implement it in the program itself. Almost everything can be changed.
UPDATE: Now when I finally understood what #CL. was telling me, I made it work and this is the updated code.
using System.Diagnostics;
using System.Linq;
using System.IO;
using DbSample.Domain;
using DbSample.Infrastructure;
using NHibernate.Linq;
using NHibernate.Util;
namespace DbSample.Console
{
class Program
{
static void Main(string[] args)
{
IDatabaseContext databaseContext = null;
databaseContext = new SqliteDatabaseContext(args[1]);
var connection = LockDB(args[1]);
if (connection == null) return;
var sessionFactory = databaseContext.CreateSessionFactory();
if (sessionFactory != null)
{
int insertCount = 0;
while (true)
{
try
{
using (var session = sessionFactory.OpenSession(connection))
{
string result;
session.FlushMode = NHibernate.FlushMode.Never;
var command = session.Connection.CreateCommand();
command.CommandText = "PRAGMA locking_mode=EXCLUSIVE";
command.ExecuteNonQuery();
using (var transaction = session.BeginTransaction(ReadCommited))
{
bool update = false;
bool delete = false;
bool read = false;
bool readall = false;
int op = 0;
System.Console.Write("\nMenu of the day:\n1: update\n2: delete\n3: read\n4: read all\n0: EXIT\n\nYour choice: ");
op = System.Convert.ToInt32(System.Console.ReadLine());
if (op == 1)
update = true;
else if (op == 2)
delete = true;
else if (op == 3)
read = true;
else if (op == 4)
readall = true;
else if (op == 0)
break;
else System.Console.WriteLine("Are you retarded? Can't you read?");
if (delete)
{
System.Console.Write("Enter the ID of the object to delete: ");
var objectToRemove = session.Get<MyObject>(System.Convert.ToInt32(System.Console.ReadLine()));
if (!(objectToRemove == null))
{
session.Delete(objectToRemove);
System.Console.WriteLine("Deleted {0}, ID: {1}", objectToRemove.MyName, objectToRemove.Id);
deleteCount++;
}
else
System.Console.WriteLine("\nObject not present in the database!\n");
}
else if (update)
{
System.Console.Write("How many objects to add/update? ");
int number = System.Convert.ToInt32(System.Console.ReadLine());
number += insertCount;
for (; insertCount < number; insertCount++)
{
var myObject = session.Get<MyObject>(insertCount + 1);
if (myObject == null)
{
myObject = new MyObject
{
MtName = "Object" + insertCount,
IdLegacy = 0,
};
session.Save(myObject);
System.Console.WriteLine("Added {0}, ID: {1}", myObject.MyName, myObject.Id);
}
else
{
session.Update(myObject);
System.Console.WriteLine("Updated {0}, ID: {1}", myObject.MyName, myObject.Id);
}
}
}
else if (read)
{
System.Console.Write("Enter the ID of the object to read: ");
var objectToRead = session.Get<MyObject>(System.Convert.ToInt32(System.Console.ReadLine()));
if (!(objectToRead == null))
System.Console.WriteLine("Got {0}, ID: {1}", objectToRead.MyName, objectToRead.Id);
else
System.Console.WriteLine("\nObject not present in the database!\n");
}
else if (readall)
{
System.Console.Write("How many objects to read? ");
int number = System.Convert.ToInt32(System.Console.ReadLine());
for (int i = 0; i < number; i++)
{
var objectToRead = session.Get<MyObject>(i + 1);
if (!(objectToRead == null))
System.Console.WriteLine("Got {0}, ID: {1}", objectToRead.MyName, objectToRead.Id);
else
System.Console.WriteLine("\nObject not present in the database! ID: {0}\n", i + 1);
}
}
update = false;
delete = false;
read = false;
readall = false;
transaction.Commit();
}
}
}
catch (System.Exception e)
{
throw e;
}
}
sessionFactory.Close();
}
}
private static SQLiteConnection LockDbNew(string database)
{
var fi = new FileInfo(database);
if (!fi.Exists)
return null;
var builder = new SQLiteConnectionStringBuilder { DefaultTimeout = 1, DataSource = fi.FullName, Version = 3 };
var connectionStr = builder.ToString();
var connection = new SQLiteConnection(connectionStr) { DefaultTimeout = 1 };
var cmd = new SQLiteCommand(connection);
connection.Open();
// try to get an exclusive lock on the database
try
{
cmd.CommandText = "PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE; COMMIT;";
cmd.ExecuteNonQuery();
}
// if we can't get the exclusive lock, it could mean 3 things
// 1: someone else has locked the database
// 2: we don't have a write acces to the database location
// 3: database itself is a read-only file
// So, we try to connect as read-only
catch (Exception)
{
// we try to set the SHARED lock
try
{
// first we clear the locks
cmd.CommandText = "PRAGMA locking_mode = NORMAL";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT COUNT(*) FROM MyObject";
cmd.ExecuteNonQuery();
// then set the SHARED lock on the database
cmd.CommandText = "PRAGMA locking_mode = EXCLUSIVE";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT COUNT(*) FROM MyObject";
cmd.ExecuteNonQuery();
readOnly = true;
}
catch (Exception)
{
// if we can't set EXCLUSIVE nor SHARED lock, someone else has opened the DB in read-write mode and we can't connect at all
connection.Close();
return null;
}
}
return connection;
}
}
}
Set PRAGMA locking_mode=EXCLUSIVE to prevent SQLite from releasing its locks after a transaction ends.
I don't know if it can be done within db but in application;
You can set a global variable (not sure if it's a web or desktop app) to check if anyone connected and he has a write access or not.
After that you can check the other client's state.