Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Multiple application instances-how prevent multiple file instances or file overwrite

Multiple application instances-how prevent multiple file instances or file overwrite

Scheduled Pinned Locked Moved C / C++ / MFC
c++questiontestingbeta-testinghelp
22 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L lctrncs

    THANK YOU! I wonder if the problem stems from the flat file database I have hanging off the doc/view. CODE FOR CreateFile call etc. From StudyPartnerDoc.cpp file ///////////////////////////////////////////////////////////////////////////// /////////////////// OnOpenDocument ////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// BOOL CStudyPartnerDoc::OnOpenDocument(LPCTSTR lpszPathName) { if (!CDocument::OnOpenDocument(lpszPathName)) return FALSE; //Get a pointer to the view POSITION pos = GetFirstViewPosition(); CStudyPartnerView* pView = dynamic_cast( GetNextView(pos) ); //Tell the view that its got a new data set if (pView) pView->NewDataSet(); ///////////////////////////////////////////////////////////// // Attempts to prevent file overwrite when multiple copies of app open the same file ///* //CreateFile and dwsharedmode to prevent make file read only when one instance is using it //opens the file - but "access denied" passed through to program on save after First Chance Exception m_hFileLock = CreateFile( lpszPathName, GENERIC_WRITE|GENERIC_READ, // access (read-write) mode //0, //attempt to use "query device attributes without accessing the device." 0,// share mode NULL,// pointer to security descriptor OPEN_EXISTING,// how to create FILE_ATTRIBUTE_NORMAL,// file attributes NULL); // handle to file with attributes to copy //FILE ATTRIBUTES TRIALS //FILE_ATTRIBUTE_NORMAL - crash on save //FILE_ATTRIBUTE_TEMPORARY - access denied //FILE_FLAG_WRITE_THROUGH - First Chance Exception on save //FILE_ATTRIBUTE_HIDDEN DestroyDialog(); //Ensure that the Study Dialog is closed return TRUE; } ///////////////////////////////////////////////////////////////////////////// /////////////////// OnSaveDocument ////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// BOOL CStudyPartnerDoc::OnSaveDocument(LPCTSTR lpszPathName) { if (!CDocument::OnSaveDocument(lpszPathName)) return FALSE; //////////////////////////////////////////////////// // Close the file handle opened for CreateFile and dwShareMode CloseHandle( m_hFileLock ); return TRUE; } /////////////////

    M Offline
    M Offline
    Mark Salsbery
    wrote on last edited by
    #13

    You're welcome! Calling the base class OnOpenDocument() (CDocument::OnOpenDocument()) the file using a CFile object, reads the file into a CArchive object, and closes the file. No problem there except a waste of CPU cycles and RAM. Calling the base class OnSaveDocument() (CDocument::OnSaveDocument()), on the other hand, opens the file using a CFile object in this mode: "CFile::modeCreate | CFile::modeReadWrite | File::shareExclusive" which will fail miserably since you've opened the file with CreateFile(). Thus, calling the base class methods is a bad idea in this case - you are handling the open/save functionality yourself. :) Once you've opened that file with no sharing enabled, any other attempt to open the file will fail, which should work nicely with your multiple processes. Mark

    L 1 Reply Last reply
    0
    • M Mark Salsbery

      You're welcome! Calling the base class OnOpenDocument() (CDocument::OnOpenDocument()) the file using a CFile object, reads the file into a CArchive object, and closes the file. No problem there except a waste of CPU cycles and RAM. Calling the base class OnSaveDocument() (CDocument::OnSaveDocument()), on the other hand, opens the file using a CFile object in this mode: "CFile::modeCreate | CFile::modeReadWrite | File::shareExclusive" which will fail miserably since you've opened the file with CreateFile(). Thus, calling the base class methods is a bad idea in this case - you are handling the open/save functionality yourself. :) Once you've opened that file with no sharing enabled, any other attempt to open the file will fail, which should work nicely with your multiple processes. Mark

      L Offline
      L Offline
      lctrncs
      wrote on last edited by
      #14

      You appear to be correct about the failure of other attempts to open the file once I have it open with CreateFile. Such attempts yield a Sharing Violation message. However, the Access Denied exceptions upon attempts to save the primary file and the Invalid Handle exceptions upon attemtps to close the primary instance of the application with the file open or closed remain an issue. X| It appears that I am not even gaining access to the file to save it, AND something else seriously wrong associated with CreateFile is interfering with nominal shutdown of the program. :confused: You can look at an earlier version of the program at www.studypartnernow.com. I wonder if the flat file database that also contributes to the file structure might be part of my problem with the CreateFile. Groff

      "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

      M 2 Replies Last reply
      0
      • L lctrncs

        You appear to be correct about the failure of other attempts to open the file once I have it open with CreateFile. Such attempts yield a Sharing Violation message. However, the Access Denied exceptions upon attempts to save the primary file and the Invalid Handle exceptions upon attemtps to close the primary instance of the application with the file open or closed remain an issue. X| It appears that I am not even gaining access to the file to save it, AND something else seriously wrong associated with CreateFile is interfering with nominal shutdown of the program. :confused: You can look at an earlier version of the program at www.studypartnernow.com. I wonder if the flat file database that also contributes to the file structure might be part of my problem with the CreateFile. Groff

        "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

        M Offline
        M Offline
        Mark Salsbery
        wrote on last edited by
        #15

        Maybe I misunderstood....you did remove the calls to the CDocument::OnOpenDocument and CDocument::OnSaveDocument in your derived document class, right? I noticed they were still in the code you posted so I'm not sure if you did that before or after the last messages we exchanged. Those need to be removed or there will be problems for sure! Mark

        L 1 Reply Last reply
        0
        • L lctrncs

          You appear to be correct about the failure of other attempts to open the file once I have it open with CreateFile. Such attempts yield a Sharing Violation message. However, the Access Denied exceptions upon attempts to save the primary file and the Invalid Handle exceptions upon attemtps to close the primary instance of the application with the file open or closed remain an issue. X| It appears that I am not even gaining access to the file to save it, AND something else seriously wrong associated with CreateFile is interfering with nominal shutdown of the program. :confused: You can look at an earlier version of the program at www.studypartnernow.com. I wonder if the flat file database that also contributes to the file structure might be part of my problem with the CreateFile. Groff

          "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

          M Offline
          M Offline
          Mark Salsbery
          wrote on last edited by
          #16

          I downloaded the free demo...is that the right one? I get the following error in a messagebox: \Setup.ini Invalid Database. The Installation will be cancelled.

          1 Reply Last reply
          0
          • M Mark Salsbery

            Maybe I misunderstood....you did remove the calls to the CDocument::OnOpenDocument and CDocument::OnSaveDocument in your derived document class, right? I noticed they were still in the code you posted so I'm not sure if you did that before or after the last messages we exchanged. Those need to be removed or there will be problems for sure! Mark

            L Offline
            L Offline
            lctrncs
            wrote on last edited by
            #17

            I just was not sure that if (!CDocument::OnOpenDocument(lpszpathname) return FALSE; was the same as CDocument::OnOpenDocument However, I thought I understood you to say that both were to be removed for the success of the CreateFile. I attempted this, but encountered problems when I removed the calls to the base classes. Below, please find a matrix indicating the results of a quicky test of the various possibilities. Column 1 2 3 4 5 OnOpenDoc base class code 0 1 1 1 1 OnSaveDoc base class code 0 0 0 1 0 CreateFile code 1 1 0 1 0 First app opens file? 0 1 1 1 1 First app saves file? x Inv. Hndle 0 Acc.Den. 0 Open second file instance? x 0 1 0 x It appears that the best results occur in column two and four, in which the app opens the file and prevents use by a second app while it has it open. However, both of these configurations result in exceptions when the user attempts to save the file. Note that the base class calls appear to be required for function of the open and save capabilities. It appears that the challenge revolves around restoring functional save capabilities when the base class calls are not present and the CreateFile code is, or overcoming the Access Denied exception that occurs when the open and save base class calls are present in conjunction with the CreateFile code.

            "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

            M 2 Replies Last reply
            0
            • L lctrncs

              I just was not sure that if (!CDocument::OnOpenDocument(lpszpathname) return FALSE; was the same as CDocument::OnOpenDocument However, I thought I understood you to say that both were to be removed for the success of the CreateFile. I attempted this, but encountered problems when I removed the calls to the base classes. Below, please find a matrix indicating the results of a quicky test of the various possibilities. Column 1 2 3 4 5 OnOpenDoc base class code 0 1 1 1 1 OnSaveDoc base class code 0 0 0 1 0 CreateFile code 1 1 0 1 0 First app opens file? 0 1 1 1 1 First app saves file? x Inv. Hndle 0 Acc.Den. 0 Open second file instance? x 0 1 0 x It appears that the best results occur in column two and four, in which the app opens the file and prevents use by a second app while it has it open. However, both of these configurations result in exceptions when the user attempts to save the file. Note that the base class calls appear to be required for function of the open and save capabilities. It appears that the challenge revolves around restoring functional save capabilities when the base class calls are not present and the CreateFile code is, or overcoming the Access Denied exception that occurs when the open and save base class calls are present in conjunction with the CreateFile code.

              "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

              M Offline
              M Offline
              Mark Salsbery
              wrote on last edited by
              #18

              lctrncs wrote:

              It appears that the challenge revolves around restoring functional save capabilities when the base class calls are not present and the CreateFile code is, or overcoming the Access Denied exception that occurs when the open and save base class calls are present in conjunction with the CreateFile code.

              Yes. I looked at your code again and noticed your document class is derived from CRichEditDoc. You'll definitely need the serialization code used in CDocument::OnSaveDocument() to get the changes to save. Sorry about that! I (now) think the simplest solution would be to copy the code from CDocument::OnOpenDocument() and CDocument::OnSaveDocument() into your overridden implementations. Then tweak the CFile related code to hold the file open for the entire time the document is open. Also adjust the open flags appropriately to prevent sharing. Something like this:

              class CStudyPartnerDoc : public CRichEditDoc
              {
              CFile StudyPartnerDocFile;

              public:
              virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
              virtual BOOL OnSaveDocument(LPCTSTR lpszPathName);
              virtual void OnCloseDocument();

              };

              BOOL CStudyPartnerDoc::OnOpenDocument(LPCTSTR lpszPathName)
              {
              #ifdef _DEBUG
              if (IsModified())
              TRACE(traceAppMsg, 0, "Warning: OnOpenDocument replaces an unsaved document.\n");
              #endif

              CFileException fe;
              if (!StudyPartnerDocFile.Open(lpszPathName,
              	CFile::modeReadWrite | CFile::shareExclusive, &fe))
              {
              	ReportSaveLoadException(lpszPathName, &fe,
              		FALSE, AFX\_IDP\_FAILED\_TO\_OPEN\_DOC);
              	return FALSE;
              }
              
              DeleteContents();
              SetModifiedFlag();  // dirty during de-serialize
              
              CArchive loadArchive(&StudyPartnerDocFile, CArchive::load | CArchive::bNoFlushOnDelete);
              loadArchive.m\_pDocument = this;
              loadArchive.m\_bForceFlat = FALSE;
              TRY
              {
              	CWaitCursor wait;
              	if (StudyPartnerDocFile.GetLength() != 0)
              		Serialize(loadArchive);     // load me
              	loadArchive.Close();
              }
              CATCH\_ALL(e)
              {
              	StudyPartnerDocFile.Abort();
              	DeleteContents();   // remove failed contents
              
              	TRY
              	{
              		ReportSaveLoadException(lpszPathName, e,
              			FALSE, AFX\_IDP\_FAILED\_TO\_OPEN\_DOC);
              	}
              	END\_TRY
              	e->Delete();
              	return FALSE;
              }
              END\_CATCH\_ALL
              
              SetModifiedFlag(FALSE);     // start off with unmodified
              
              return TRUE;
              

              }

              BOOL CStudyPartnerDoc::OnSaveDocument(LPCTSTR lpszPathName)
              {
              StudyPartnerDocFile.SeekToBegin();

              CArchive saveArchive(&StudyPartnerDocFile, CArchive::store | CArchive::bNoF
              
              L 1 Reply Last reply
              0
              • L lctrncs

                I just was not sure that if (!CDocument::OnOpenDocument(lpszpathname) return FALSE; was the same as CDocument::OnOpenDocument However, I thought I understood you to say that both were to be removed for the success of the CreateFile. I attempted this, but encountered problems when I removed the calls to the base classes. Below, please find a matrix indicating the results of a quicky test of the various possibilities. Column 1 2 3 4 5 OnOpenDoc base class code 0 1 1 1 1 OnSaveDoc base class code 0 0 0 1 0 CreateFile code 1 1 0 1 0 First app opens file? 0 1 1 1 1 First app saves file? x Inv. Hndle 0 Acc.Den. 0 Open second file instance? x 0 1 0 x It appears that the best results occur in column two and four, in which the app opens the file and prevents use by a second app while it has it open. However, both of these configurations result in exceptions when the user attempts to save the file. Note that the base class calls appear to be required for function of the open and save capabilities. It appears that the challenge revolves around restoring functional save capabilities when the base class calls are not present and the CreateFile code is, or overcoming the Access Denied exception that occurs when the open and save base class calls are present in conjunction with the CreateFile code.

                "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

                M Offline
                M Offline
                Mark Salsbery
                wrote on last edited by
                #19

                BOOL CStudyPartnerDoc::OnSaveDocument(LPCTSTR lpszPathName)
                {
                StudyPartnerDocFile.SeekToBegin();
                ...

                should be

                BOOL CStudyPartnerDoc::OnSaveDocument(LPCTSTR lpszPathName)
                {
                StudyPartnerDocFile.SetLength(0LL);
                StudyPartnerDocFile.SeekToBegin();
                ...

                1 Reply Last reply
                0
                • M Mark Salsbery

                  lctrncs wrote:

                  It appears that the challenge revolves around restoring functional save capabilities when the base class calls are not present and the CreateFile code is, or overcoming the Access Denied exception that occurs when the open and save base class calls are present in conjunction with the CreateFile code.

                  Yes. I looked at your code again and noticed your document class is derived from CRichEditDoc. You'll definitely need the serialization code used in CDocument::OnSaveDocument() to get the changes to save. Sorry about that! I (now) think the simplest solution would be to copy the code from CDocument::OnOpenDocument() and CDocument::OnSaveDocument() into your overridden implementations. Then tweak the CFile related code to hold the file open for the entire time the document is open. Also adjust the open flags appropriately to prevent sharing. Something like this:

                  class CStudyPartnerDoc : public CRichEditDoc
                  {
                  CFile StudyPartnerDocFile;

                  public:
                  virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
                  virtual BOOL OnSaveDocument(LPCTSTR lpszPathName);
                  virtual void OnCloseDocument();

                  };

                  BOOL CStudyPartnerDoc::OnOpenDocument(LPCTSTR lpszPathName)
                  {
                  #ifdef _DEBUG
                  if (IsModified())
                  TRACE(traceAppMsg, 0, "Warning: OnOpenDocument replaces an unsaved document.\n");
                  #endif

                  CFileException fe;
                  if (!StudyPartnerDocFile.Open(lpszPathName,
                  	CFile::modeReadWrite | CFile::shareExclusive, &fe))
                  {
                  	ReportSaveLoadException(lpszPathName, &fe,
                  		FALSE, AFX\_IDP\_FAILED\_TO\_OPEN\_DOC);
                  	return FALSE;
                  }
                  
                  DeleteContents();
                  SetModifiedFlag();  // dirty during de-serialize
                  
                  CArchive loadArchive(&StudyPartnerDocFile, CArchive::load | CArchive::bNoFlushOnDelete);
                  loadArchive.m\_pDocument = this;
                  loadArchive.m\_bForceFlat = FALSE;
                  TRY
                  {
                  	CWaitCursor wait;
                  	if (StudyPartnerDocFile.GetLength() != 0)
                  		Serialize(loadArchive);     // load me
                  	loadArchive.Close();
                  }
                  CATCH\_ALL(e)
                  {
                  	StudyPartnerDocFile.Abort();
                  	DeleteContents();   // remove failed contents
                  
                  	TRY
                  	{
                  		ReportSaveLoadException(lpszPathName, e,
                  			FALSE, AFX\_IDP\_FAILED\_TO\_OPEN\_DOC);
                  	}
                  	END\_TRY
                  	e->Delete();
                  	return FALSE;
                  }
                  END\_CATCH\_ALL
                  
                  SetModifiedFlag(FALSE);     // start off with unmodified
                  
                  return TRUE;
                  

                  }

                  BOOL CStudyPartnerDoc::OnSaveDocument(LPCTSTR lpszPathName)
                  {
                  StudyPartnerDocFile.SeekToBegin();

                  CArchive saveArchive(&StudyPartnerDocFile, CArchive::store | CArchive::bNoF
                  
                  L Offline
                  L Offline
                  lctrncs
                  wrote on last edited by
                  #20

                  Mark, Thank for all your help. This feature is becoming a bit too much for my current schedule. Chances are that I will return to it at some point. However, for right now I am going to have to put this on the back burner because I need to generate some income (through freelance writing) and find a way to protect my Doc/View based content files (six are ready for posting) so that they cannot be edited and then misrepresented as the work of my company. Since setting the "read only" bit on the file will not be permanent enough, I thought I might save a flag with my original files then override DoSave to prevent saving if the flag is set. Another way might be to somehow embed the file in the program itself, so each content file distributed from my company comes with a program, again with DoSave = NULL in the Save As function or some such thing. This approach has the added benefit that I could distribute the content using Armadillo (which I use to provide 30 day trial functionality) which is not able to protect simple unzippers and non-executables. Since the second approach probably requires the completion of the first, it looks like that will be my starting point. Thank you again. Your posts were very educational, useful and well written. If you were on my team, I'll bet you could fix all of the problems I plan to spend the next 6 months beating my head against the in an afternoon. Thanks again. I hope you enjoy your "greetings seasons." Take the rest of the year off. Groff Schroeder

                  "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

                  M 1 Reply Last reply
                  0
                  • L lctrncs

                    Mark, Thank for all your help. This feature is becoming a bit too much for my current schedule. Chances are that I will return to it at some point. However, for right now I am going to have to put this on the back burner because I need to generate some income (through freelance writing) and find a way to protect my Doc/View based content files (six are ready for posting) so that they cannot be edited and then misrepresented as the work of my company. Since setting the "read only" bit on the file will not be permanent enough, I thought I might save a flag with my original files then override DoSave to prevent saving if the flag is set. Another way might be to somehow embed the file in the program itself, so each content file distributed from my company comes with a program, again with DoSave = NULL in the Save As function or some such thing. This approach has the added benefit that I could distribute the content using Armadillo (which I use to provide 30 day trial functionality) which is not able to protect simple unzippers and non-executables. Since the second approach probably requires the completion of the first, it looks like that will be my starting point. Thank you again. Your posts were very educational, useful and well written. If you were on my team, I'll bet you could fix all of the problems I plan to spend the next 6 months beating my head against the in an afternoon. Thanks again. I hope you enjoy your "greetings seasons." Take the rest of the year off. Groff Schroeder

                    "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

                    M Offline
                    M Offline
                    Mark Salsbery
                    wrote on last edited by
                    #21

                    lctrncs wrote:

                    Thanks again. I hope you enjoy your "greetings seasons." Take the rest of the year off.

                    You're welcome! I wish I could take the rest of the year off but I am about to release my own product (yeah, I said that last year at this time, and the year before...) which is 5 years in the making. I have to get it out...this living as a "starving artist" thing is getting old. At least I have the drums to beat out my aggressions :) Anyway, I may have missed the point of what you were trying to achieve. If it's protecting content then I would make the doc/view editors read-only and encrypt the content files so they can't be edited outside of your application. There's always a solution (I refuse to ever be convinced otherwise). Best of luck (or "break a leg"?) on your writing projects! Mark Salsbery

                    L 1 Reply Last reply
                    0
                    • M Mark Salsbery

                      lctrncs wrote:

                      Thanks again. I hope you enjoy your "greetings seasons." Take the rest of the year off.

                      You're welcome! I wish I could take the rest of the year off but I am about to release my own product (yeah, I said that last year at this time, and the year before...) which is 5 years in the making. I have to get it out...this living as a "starving artist" thing is getting old. At least I have the drums to beat out my aggressions :) Anyway, I may have missed the point of what you were trying to achieve. If it's protecting content then I would make the doc/view editors read-only and encrypt the content files so they can't be edited outside of your application. There's always a solution (I refuse to ever be convinced otherwise). Best of luck (or "break a leg"?) on your writing projects! Mark Salsbery

                      L Offline
                      L Offline
                      lctrncs
                      wrote on last edited by
                      #22

                      Drums!? My little band needs a drummer badly. Do you like Pink Floyd? Do you live anywhere near Colorado? When you get close with your product, send me a version and I will happily test it for you. I once turned down a full time job teaching college for a six-week gigue testing network protocol analyzers for HP. I stayed a year and a half, then came back as a full consultant. Those were the days! Testing is specialty of mine and since you have been so helpful, I would gladly punish your software for you. Bwaahahahahhaaaa! If you send me your email address through that web site I sent you to, we can both avoid public postings. Best of luck. Groff PS: Thanks for the heads up on the download error. I experienced the same thing and learned that the problem occurs when the complete file does not download. It is about 5.5 meg, so it is probably easy to try to start early. I will probably put up a little warning page in my "free time." GS

                      "For a successful technology, reality must take precedence over public relations, for nature cannot be fooled." Richard Feynman, Minority Report to the Official Report on the Space Shuttle Challenger Crash

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups