Open Workshared document in Revit Architecture 2014 using Revit API - autodesk

I am new to Revit API. I am trying to open revit documents using Revit API 2014. It works fine for the non-workshared revit files but I am not able to open workshared revit files using API. Can anyone point out if I am using a correct way to open workshared revit files? Below is my code snippet:
Document _docCl = uiapp.Application.OpenDocumentFile(_revitFileToOpen);
if (_docCl.IsWorkshared)
{
_docCl.Close();
_docCl = null;
ModelPath mdlPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(this._revitFileToOpen);
OpenOptions opts = new OpenOptions();
opts.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
_docClActive = uiapp.OpenAndActivateDocument(mdlPath, opts, false); //doesn't work
//uiapp.Application.OpenDocumentFile(mdlPath, opts); //doesn't work either
}
else
{
_docClActive = uiapp.OpenAndActivateDocument(_revitFileToOpen);
}
Below is the portion of Journal Log file which seems relevant:
' 0.000032 7:<<<WorksharingLog::getSlog [\\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt]
' 6:< Additional IP address/name found for host INLTAPPL034: 10.10.87.85
' 6:< DBG_INFO: Get addresses failed (using getaddrinfo) for central server CBA01-SRV-FS01: The requested name is valid, but no data of the requested type was found. : line 626 of n:\build\2014_ship_x64_inst_20130308_1515\source\revit\revitdb\permissions\WorksharingLog.cpp.
' 6:< SLOG user="amitp"
' 6:< SLOG build="20130308_1515(x64)"
' 6:< SLOG server=??.??.??.?? "???.com"
' 6:< SLOG central="\\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt"
' 6:< SLOG local="E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt"
' 6:< SLOG timer="pulse-6e549c85.tmp"
' 2.553593!!!!!!! 6:!!!BIG_GAP LoadSerialize
' 7:< Threaded version of fileExists is enabled. 2.262 seconds elapsed for threaded fileExists \\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt
' 2.252302 7:<<<fileExists?
' 6:< SLOG $6e549c85 2016-08-22 20:29:58.408 >Open
' 0.000237 7:<<<fileExists?
' 6:< SLOG $6e549c85 2016-08-22 20:29:58.408 >Open:Local "E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt"
' 0.000223 7:<<<fileExists?
' 6:< fileSizeOnOpen:89056KB
'E 22-Aug-2016 20:29:58.409; 7:<
' [Jrn.BasicFileInfo] Rvt.Attr.Worksharing: Local Rvt.Attr.UserName: amitp Rvt.Attr.CentralModelPath: \\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.RevitBuildVersion: Autodesk Revit Architecture 2014 (Build: 20130308_1515(x64)) Rvt.Attr.LastSavePath: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.ProjectSpark: notProjectSpark Rvt.Attr.LocaleWhenSaved: ENU
' 0.024759 8:<<<app infos and other global data
' 7:< File was saved in Autodesk Revit Architecture 2014 (Build: 20130308_1515(x64))
' 1.071029 10:<<<updating dependencies in delayed deletion
' 0.005856 10:<<<getAllNonexistentParents in delayed deletion
' 0.050896 10:<<<findAppInfoNonexistentParents in delayed deletion
' 1.128135 9:<<delayed deletion
' 0.007749 9:<<<forceResetOfElemRecOwnerCache
' 1.223763 8:<<ADocumentUpgrade::docUpgrade
' 8.653545 5:<<LoadSerialize/ALL_GAPS 2.559036/TurnOff_GAPs 100%
' 8.653719 4:<<LoadFromStorage
' 4:< LPSTORAGE RELEASED: plpRootStg=0x14321818, lpRootStg=0x09778080
' 4:< DummyStorage destroying DataStorageInterface 0x0000000014790090
' 4:< DataStorageInterface destroyed 0x0000000014790090
' 4:< AFTER RELEASE: plpRootStg=0x14321818, lpRootStg=0x00000000
' 0.010065 4:<<<relinquishAllLocks
' 3:< SLOG $6e549c85 2016-08-22 20:30:02.133 <Open:Local
' 0.000248 4:<<<fileExists?
' 3:< SLOG $6e549c85 2016-08-22 20:30:02.133 <Open
' 0.000146 4:<<<fileExists?
' 0.022058 5:<<<forceResetOfElemRecOwnerCache
' 5:< Unnecessary nesting;Document\PostLoadDocument.cpp;160;String_Revit_DelayedPropagatoinRegen ;N++E(N);
' 6:< Element Expansion Statistics:
' 6:< 0% Opening Plans (0)
' 6:< 0% Opening RC Plans (0)
' 6:< 0% Opening 3d Views (0)
' 6:< 0% Opening Elevations and Sections (0)
' 6:< 0% In Regnerate (0)
' 6:< 0% In Autojoin (0)
' 6:< 0% In Overlap Checking (0)
' 6:< 0% Reviewing PostedWarnings (0)
' 6:< 100% Other (1560439)
' 6:< total bytes expanded: 1560439
' 6:< ;EES;0;0;0;0;0;0;0;0;100;
' 0.000330 7:<<<ppg constructor
' 0.000011 7:<<<updating dependencies in dp
' 0.000031 7:<<<notifyAppInfosOfDP(0)
' 0.000002 8:<<<updating dependencies in delayed deletion
' 0.005908 8:<<<getAllNonexistentParents in delayed deletion
' 0.063470 8:<<<findAppInfoNonexistentParents in delayed deletion
' 0.000016 8:<<<notifyAppInfosOfDP(1)
' 0.069706 7:<<delayed deletion
' 0.176552 6:<<ADocumentMerge::delayedPropagation
' 0.000262 7:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000032 7:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 7:< ::2:: Delta VM: Avail 8384631 MB, Used 534 MB; RAM: Avail +11 -> 2810 MB, Used +0 -> 612 MB
' 0.000005 8:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000031 9:<<<;PERF;MISC;regenerating
' 0.000570 7:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000534/TurnOff_GAPs 17%
' 0.619823 6:<<EndOrAbortUndoTransaction();DOPT;
' 0.810964 5:<<delayed propagation on open
' 0.000014 5:<<<updating dependencies on open
' 5:< ::2:: Delta VM: Avail 8384631 MB, Used 534 MB; RAM: Avail +126 -> 2936 MB, Used 612 MB
' 5:< Threaded version of fileExists is enabled. 2.559 seconds elapsed for threaded fileExists \\DENHV12P\PROJECTS\TCH-FITZ.338\338.081 East Tower\6 Drawings\Revit Working\__CAD Underlays\KITCHEN BACKGROUND - EXT.dwg
' 2.557757!!!!!!! 6:!!!BIG_GAP reloadLinkedInstances [5/6]
' 5:< No Keynote File: R:\TCH-FITZ.338\338.081 East Tower\6 Drawings\Revit Working\IMFM Keynotes User.txt
' 5:< DBG_INFO: Couldn't obtain time/date stamp for R:\TCH-FITZ.338\338.081 East Tower\6 Drawings\Revit Working\IMFM Keynotes User.txt so that cannot correct file create/access/modify time!, the GetLastError is 6: line 1951 of FileUtil.cpp.
' 4:< Document save history --> :
' 4:< Revit Architecture 2014 2014 (2014.000) : 20140709_2115(x64)
' 4:< Revit Architecture 2014 2014 (2014.000) : 20130709_2115(x64)
' 4:< Revit 2014 2014 (2014.000) : 20131024_2115(x64)
' 4:< Revit Architecture 2014 2014 (2014.000) : 20130308_1515(x64)
' 4:< Document save history <--
' 3.448459 4:<<[Cloud]postLoadDocument
' 12.119349 3:<<DocumentStorage::onOpenDocument [E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt]
'H 22-Aug-2016 20:30:05.625; 2:<
Jrn.Directive "DocSymbol" _
, "[AMCFM_C_AI_R14_HL.rvt]"
' 2:< DBG_INFO: When constructing ElementRecord, elem 0 not found: line 24 of n:\build\2014_ship_x64_inst_20130308_1515\source\revit\revitdb\elemtable\ElementRecord.cpp.
' 3:< TaskDialog "Doc opened... Document Name : E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt"
'CommonButtons : Close
'DefaultButton : Close
'H 22-Aug-2016 20:30:07.541; 3:<
Jrn.Data "TaskDialogResult" _
, "Doc opened... Document Name : E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt", _
"Close", "IDCLOSE"
' 2:< SLOG $6e549c85 2016-08-22 20:30:07.710 >WSConfig
' 1.983669!!!! 3:!!!BIG_GAP [Cloud]handWrittenOpenDocumentFile
' 2:< 0 ModelServerState "Created": Current server = "Not Queried", Model server = "", Model server state = "Not Applicable"
' 2:< DataStorageInterface created 0x0000000014A46750
' 3:< MasterLocks 0x000000000012CD70 ensureAppropriateStorage DataStorageInterface WAS m_oDataStorage 0x0000000014A46750 m_pDataStorage 0x0000000014A46750
' 3:< DataStorageInterface created 0x0000000014A467D0
' 3:< DataStorageInterface destroyed 0x0000000014A46750
' 3:< MasterLocks 0x000000000012CD70 ensureAppropriateStorage DataStorageInterface m_oDataStorage 0x0000000014A467D0 m_pDataStorage 0x0000000014A467D0
' 3:< SLOG $6e549c85 2016-08-22 20:30:07.715 .WSConfig:LockRoot R SCODE=0x80070035
' 2:< initTransactionStatus unable to refresh permissions
' 2:< DataStorageInterface destroyed 0x0000000014A467D0
' 2:< 0 ModelServerState "Destroyed": Current server = "Not Queried", Model server = "", Model server state = "Not Applicable"
' 2:< SLOG $6e549c85 2016-08-22 20:30:07.717 <WSConfig
' 2:< Element Expansion Statistics:
' 2:< 0% Opening Plans (0)
' 2:< 0% Opening RC Plans (0)
' 2:< 0% Opening 3d Views (0)
' 2:< 0% Opening Elevations and Sections (0)
' 2:< 0% In Regnerate (0)
' 2:< 0% In Autojoin (0)
' 2:< 0% In Overlap Checking (0)
' 2:< 13% Reviewing PostedWarnings (257178)
' 2:< 87% Other (1715892)
' 2:< total bytes expanded: 1973070
' 2:< ;EES;0;0;0;0;0;0;0;13;87;
' 14.282558 2:<<[Cloud]handWrittenOpenDocumentFile/ALL_GAPS 2.163209/TurnOff_GAPs 83%
' 1:< TaskDialog "Requested document is a workshared document...."
'CommonButtons : Close
'DefaultButton : Close
'H 22-Aug-2016 20:30:08.872; 1:<
Jrn.Data "TaskDialogResult" _
, "Requested document is a workshared document....", _
"Close", "IDCLOSE"
' 1:< INVISIBLE timing block
' 1:< 0 ModelServerState "Created": Current server = "Not Queried", Model server = "", Model server state = "Not Applicable"
' 0.000071 2:<<<saveModifiedRvtLinkSymbols
' 0.000025 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000004 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000003 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000014 6:<<<;PERF;MISC;regenerating
' 0.000292 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000275/TurnOff_GAPs 29%
' 0.129988 3:<<EndOrAbortUndoTransaction();DOPT;
' 0.000014 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000004 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000002 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000011 6:<<<;PERF;MISC;regenerating
' 0.000270 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000257/TurnOff_GAPs 30%
' 0.002592 3:<<EndOrAbortUndoTransaction();DOPT;
' 0.000009 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000003 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000002 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000006 6:<<<;PERF;MISC;regenerating
' 0.000174 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000167/TurnOff_GAPs 28%
' 0.001768 3:<<EndOrAbortUndoTransaction();DOPT;/ALL_GAPS 0.001581/TurnOff_GAPs 1%
' 0.000007 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000001 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000001 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000005 6:<<<;PERF;MISC;regenerating
' 0.000156 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000150/TurnOff_GAPs 31%
' 0.001319 3:<<EndOrAbortUndoTransaction();DOPT;
' 0.000007 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000001 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000001 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000006 6:<<<;PERF;MISC;regenerating
' 0.000162 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000155/TurnOff_GAPs 30%
' 0.001432 3:<<EndOrAbortUndoTransaction();DOPT;/ALL_GAPS 0.001262/TurnOff_GAPs 1%
' 0.000007 4:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000002 4:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000001 5:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000005 6:<<<;PERF;MISC;regenerating
' 0.000150 4:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000144/TurnOff_GAPs 32%
' 0.001306 3:<<EndOrAbortUndoTransaction();DOPT;
' 0.140553 2:<<saveModifiedImportSymbols
' 1:< DataStorageInterface created 0x0000000014A467D0
' 1:< DataStorageInterface created 0x0000000014A46750
' 1:< MasterLocks 0x000000000012CEA0 ensureAppropriateStorage DataStorageInterface WAS m_oDataStorage 0x0000000014A46750 m_pDataStorage 0x0000000014A46750
' 1:< DataStorageInterface created 0x0000000014A46850
' 1:< DataStorageInterface destroyed 0x0000000014A46750
' 1:< MasterLocks 0x000000000012CEA0 ensureAppropriateStorage DataStorageInterface m_oDataStorage 0x0000000014A46850 m_pDataStorage 0x0000000014A46850
' 0.000005 2:<<<relinquishAllLocks
' 1:< DataStorageInterface destroyed 0x0000000014A46850
' 0.000022 3:<<<EndOrAbortUndoTransaction() -- trackers regen;DOPT;
' 0.000002 3:<<<EndOrAbortUndoTransaction()--AtomViewReferencingUpdate();DOPT;
' 0.000002 4:<<<EndOrAbortUndoTransaction()--end of transaction checks--invisible elements;DOPT;
' 0.000011 5:<<<;PERF;MISC;regenerating
' 0.000249 3:<<EndOrAbortUndoTransaction()--end of transaction checks;DOPT;/ALL_GAPS 0.000236/TurnOff_GAPs 32%
' 0.001897 2:<<EndOrAbortUndoTransaction();DOPT;
' 2:< MasterLocks 0x00000000574F0080 ensureAppropriateStorage DataStorageInterface WAS m_oDataStorage 0x0000000014A467D0 m_pDataStorage 0x0000000014A467D0
' 2:< DataStorageInterface created 0x0000000014A46850
' 2:< DataStorageInterface destroyed 0x0000000014A467D0
' 2:< MasterLocks 0x00000000574F0080 ensureAppropriateStorage DataStorageInterface m_oDataStorage 0x0000000014A46850 m_pDataStorage 0x0000000014A46850
' 4:< ::2:: Delta VM: Avail -175 -> 8384455 MB, Used +2 -> 537 MB; RAM: Avail +0 -> 2947 MB, Used +1 -> 615 MB
' 4:< MasterLocks 0x00000000574F0080 DummyStorage stole m_oDataStorage 0x0000000014A46850 but left m_pDataStorage 0x0000000014A46850
' 4:< LPSTORAGE ACQUIRED: DocumentStorage=0x14321750, plpRootStg=0x14321818, lpRootStg=0x09778080
' 0.003546 4:<<acquireFileLock
' 0.003637 3:<<acquiring lock
' 3:< DataStorageInterface created 0x0000000014A467D0
'C 22-Aug-2016 20:30:09.087; 4:< File: Open
' 0.000002 5:<<<OpenDocumentTask::acquireFileLock
' 0.030179 8:<<<loadAllClasses
' 0.000038 8:<<<RegisterPreDocLoadCallback::invokeCallbacks
' 0.000769 9:<<<LoadModel DSI
' 0.000833 8:<<loading DocumentStorageIndex
'E 22-Aug-2016 20:30:09.119; 8:<
' [Jrn.BasicFileInfo] Rvt.Attr.Worksharing: Local Rvt.Attr.UserName: amitp Rvt.Attr.CentralModelPath: \\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.RevitBuildVersion: Autodesk Revit Architecture 2014 (Build: 20130308_1515(x64)) Rvt.Attr.LastSavePath: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.ProjectSpark: notProjectSpark Rvt.Attr.LocaleWhenSaved: ENU
' 0.000510 9:<<<History
' 0.001148 9:<<<increment table
' 0.015164 8:<<DocumentStorageIndexImpl::loadDocument()
' 0.047160 6:<<LoadSerialize
' 0.047289 5:<<LoadFromStorage
' 0.047553 4:<<DocumentStorage::onOpenDocument [E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt]
' 3:< compare GUIDs; creation c18fea7b-7fd5-40e0-9b77-3ccb92fe3eeb; detach c2effc75-eec7-4a68-9985-7cb8985cc740; upgrade 80d9c28b-d7e7-4013-8d2d-edd4c21d435a; DIFF prevUpgrade c18fea7b-7fd5-40e0-9b77-3ccb92fe3eeb != 80d9c28b-d7e7-4013-8d2d-edd4c21d435a
' 0.000004 4:<<<relinquishAllLocks
' 3:< DataStorageInterface destroyed 0x0000000014A467D0
' 2:< Revit Graphics Information
' 2:< Current Mode : DirectX Hardware
' 2:< Use Hardware: ON
' 2:< Use Overlays : ON
' 2:< After : Create Display Manager
' 0.123757 2:<<OpenFileForSave::openFileForSave
' 0.000002 4:<<<storePreviewImage
' 0.003901 4:<<<storeValidation
' 0.064306 5:<<<ElementSender::createDocSaveSwapout
' 0.000127 7:<<<Reconsolidater::getAllLiveElementCounts
' 6:< [ISL] Stream#266 (0 live/0 total elements) marked for deletion during reconsolidation
' 0.000248 6:<<Reconsolidater::getStreamsToReconsolidate
' 0.000281 5:<<pre-swapout reconsolidate
' 0.000620 5:<<<ElemTable::updateETforSave
' 0.000001 5:<<<ElementSender::swapOut()
' 5:< updateDITforSave increment 267L has 12782 (+0) episodes
' 0.000358 5:<<Updating increment and partition tables for save (quick)
' 0.003116 6:<<<Storing increment table [#obsolete=15, first#=212, last#=267]
' 0.062210 6:<<<Storing DocumentHistory [#episodes=12783, #valid=11257, max ep id#=12782]
' 0.011262 6:<<<Storing PartitionTable [#partitions=1512, #deleted=815, max id#=43818]
' 0.001607 6:<<<Storing Content Documents
' 0.181542 6:<<<Storing ElemTable [#elts=137923, #graveyard=928, max id#=12483562]
' 0.035586 6:<<<Storing global stream
' 0.000048 7:<<<OLEStgLock::commit overwrite=yes consolidate=no
' 0.304950 6:<<commitAllGlobalStreams/ALL_GAPS 0.304902/TurnOff_GAPs 100%
' 0.615831 5:<<Storing tables
' 0.000024 8:<<<OLEStgLock::commit overwrite=yes consolidate=no
' 0.031170 5:<<ModelStorer::storeStreams() /ALL_GAPS 0.031146/TurnOff_GAPs 99%
' 0.713105 4:<<ModelStorer::storeDocument()
' 3:< GETLOADSTOREOPTIONS in GET Project\OleStorage.cpp(240) despite m_dontFetch
' 0.000224 5:<<<storeSelf DocumentStorageIndexBackup
' 0.001857 5:<<<storeSelf updateDSIforSave
' 0.005144 4:<<DocumentStorageIndex::storeSelf [12781]
' 3:< GETLOADSTOREOPTIONS in GET n:\build\2014_ship_x64_inst_20130308_1515\source\revit\revitdb\document\Document.cpp(6024) despite m_dontFetch
' 3:< GETLOADSTOREOPTIONS in GET Project\ProjectExtras.cpp(122) despite m_dontFetch
' 4:< GETLOADSTOREOPTIONS in GET Project\OleStorage.cpp(240) despite m_dontFetch
' 4:< GETLOADSTOREOPTIONS in GET Project\ProjectExtras.cpp(140) despite m_dontFetch
' 4:< GETLOADSTOREOPTIONS in GET Project\ProjectExtras.cpp(159) despite m_dontFetch
' 0.030804 4:<<storeBasicFileInfoStream
' 0.000007 4:<<<storePartAtomStream
' 0.168626 4:<<storeProjectXMLInfoStream
' 1.006264 3:<<TrustedUtility::SaveToStorage - serialize block/ALL_GAPS 0.084674/TurnOff_GAPs 65%
' 0.032333 3:<<TrustedUtility::SaveToStorage - commit format/contents locks
' 3:< ::3:: Delta VM: Avail +11 -> 8384467 MB, Used 537 MB; RAM: Avail -14 -> 2933 MB, Used +12 -> 628 MB
' 0.268941 4:<<<OLEStgLock::commit overwrite=yes consolidate=yes
' 0.269292 3:<<TrustedUtility::SaveToStorage - commitStorage
' 1.309396 2:<<TrustedUtility::saveToStorage
'H 22-Aug-2016 20:30:10.550; 1:<
Jrn.Directive "DocSymbol" _
, "[AMCFM_C_AI_R14_HL.rvt]"
' 0.000395 3:<<<preCommit finding backup files
' 2:< GETLOADSTOREOPTIONS in GET Project\OleStorage.cpp(240) despite m_dontFetch
' 0.000177 3:<<<findFileAndWorksetVersionsToKeep
' 0.000387 3:<<<BackupPaths::DocumentVersionIterator
' 2:< GETLOADSTOREOPTIONS in GET Project\OleStorage.cpp(240) despite m_dontFetch
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\265_0.rws
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\global.7070.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\history.7070.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\elemtable.7070.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\contentdocuments.0431.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\partitiontable.7070.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\incrementtable.7099.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\basicfileinfo.7065.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\transmissiondata.0431.dat
' 3:< Marking file for quick purge: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL_backup\projectinformation.0431.dat
' 0.001184 3:<<<findFilesToDeleteBasedOnIncrements
' 0.003227 2:<<BackupFileManager::preUnlockPreCommit
' 0.000006 2:<<<BackupFileManager::postUnlockPreCommit
' 0.013889 2:<<<BackupFileManager::commit
' 2:< ::3:: Delta VM: Avail +176 -> 8384643 MB, Used 537 MB; RAM: Avail +3 -> 2937 MB, Used -4 -> 624 MB
' 2:< LPSTORAGE RELEASED: plpRootStg=0x14321818, lpRootStg=0x09778080
' 2:< DummyStorage destroying DataStorageInterface 0x0000000014A46850
' 2:< DataStorageInterface destroyed 0x0000000014A46850
' 2:< AFTER RELEASE: plpRootStg=0x14321818, lpRootStg=0x00000000
' 0.005317 2:<<<relinquishAllLocks
' 1:< DataStorageInterface created 0x0000000014A46850
' 0.000004 2:<<<temporaryEffects.destroy(DoSave)
' 0.000255 2:<<<commit/cleanup
' 0.000005 2:<<<relinquishAllLocks
' 1:< DataStorageInterface destroyed 0x0000000014A46850
'C 22-Aug-2016 20:30:11.048; 3:< File: Open
' 4:< DataStorageInterface created 0x000000001478E590
' 4:< Connecting session [$404fa1d3] to Worksharing Log [C:\Users\amitp\AppData\Local\Autodesk\Revit\Autodesk Revit Architecture 2014\Journals\journal.0001.txt]
' 0.000013 5:<<<WorksharingLog::getSlog []
' 4:< Additional IP address/name found for host INLTAPPL034: 10.10.87.85
' 5:< MasterLocks 0x0000000046654730 ensureAppropriateStorage DataStorageInterface WAS m_oDataStorage 0x000000001478E590 m_pDataStorage 0x000000001478E590
' 5:< DataStorageInterface created 0x000000001478F510
' 5:< DataStorageInterface destroyed 0x000000001478E590
' 5:< MasterLocks 0x0000000046654730 ensureAppropriateStorage DataStorageInterface m_oDataStorage 0x000000001478F510 m_pDataStorage 0x000000001478F510
' 5:< ::4:: Delta VM: Avail -169 -> 8384499 MB, Used 513 MB; RAM: Avail +4 -> 2960 MB, Used 601 MB
' 5:< MasterLocks 0x0000000046654730 DummyStorage stole m_oDataStorage 0x000000001478F510 but left m_pDataStorage 0x000000001478F510
' 5:< LPSTORAGE ACQUIRED: DocumentStorage=0x14321ab0, plpRootStg=0x14321b78, lpRootStg=0x14881ba0
' 0.002869 5:<<acquireFileLock
' 0.004018 4:<<OpenDocumentTask::acquireFileLock
' 0.020358 7:<<<loadAllClasses
' 0.000029 7:<<<RegisterPreDocLoadCallback::invokeCallbacks
' 0.000506 8:<<<LoadModel DSI
' 0.000557 7:<<loading DocumentStorageIndex
'E 22-Aug-2016 20:30:11.074; 7:<
' [Jrn.BasicFileInfo] Rvt.Attr.Worksharing: Local Rvt.Attr.UserName: amitp Rvt.Attr.CentralModelPath: \\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.RevitBuildVersion: Autodesk Revit Architecture 2014 (Build: 20130308_1515(x64)) Rvt.Attr.LastSavePath: E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt Rvt.Attr.ProjectSpark: notProjectSpark Rvt.Attr.LocaleWhenSaved: ENU
' 0.057984 8:<<<History
' 0.001012 8:<<<increment table
' 0.002487 8:<<<WorksetTable
' 0.086087 7:<<DocumentStorageIndexImpl::loadDocument()
' 0.000027 8:<<<distributeKnownEpisodesToSubsets
' 0.107716 5:<<LoadSerialize
' 0.107821 4:<<LoadFromStorage
' 4:< ::5:: Delta VM: Avail +174 -> 8384674 MB, Used 513 MB; RAM: Avail 2960 MB, Used 601 MB
' 4:< LPSTORAGE RELEASED: plpRootStg=0x14321b78, lpRootStg=0x14881ba0
' 4:< DummyStorage destroying DataStorageInterface 0x000000001478F510
' 4:< DataStorageInterface destroyed 0x000000001478F510
' 4:< AFTER RELEASE: plpRootStg=0x14321b78, lpRootStg=0x00000000
' 0.001984 4:<<<relinquishAllLocks
' 0.114172 3:<<DocumentStorage::onOpenDocument [E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt]
' 2:< Connecting session [$1de94fdf] to Worksharing Log [C:\Users\amitp\AppData\Local\Autodesk\Revit\Autodesk Revit Architecture 2014\Journals\journal.0001.txt]
' 2:< Additional IP address/name found for host INLTAPPL034: 10.10.87.85
' 2:< SLOG $1de94fdf 2016-08-22 20:30:13.425 >Session $1de94fdf
' 2:< SLOG user="amitp"
' 2:< SLOG build="20130308_1515(x64)"
' 2:< SLOG journal="C:\Users\amitp\AppData\Local\Autodesk\Revit\Autodesk Revit Architecture 2014\Journals\journal.0001.txt"
' 2:< SLOG host=fe80::59d8:cab6:ad7:5925%14 "INLTAPPL034.MPTDC1-India.MirrorPlus.com"
' 2:< SLOG server=??.??.??.?? "???.com"
' 2:< SLOG central="\\CBA01-SRV-FS01\EAD Files\C0190-ARC\15-0091-CHCO-Children's Hospital Colorado\80-CHCO-Revit Files\AMCFM_C_AI_R14_HL.rvt"
' 2:< SLOG local="E:\Test Dataset\Revit Files\AMCFM_C_AI_R14_HL.rvt"
' 2:< SLOG timer="pulse-1de94fdf.tmp"
' 2:< SLOG timebias=-330
' 2.251970!!!! 3:!!!BIG_GAP MFCProjectAgent::getWorksetConfigForLoading 'Specify' = askUser
' 2:< SLOG $1de94fdf 2016-08-22 20:30:13.426 >WSD
' 3:< 0 ModelServerState "Created": Current server = "Not Queried", Model server = "", Model server state = "Not Applicable"
' 3:< DataStorageInterface created 0x000000001478E590
' 4:< MasterLocks 0x000000000012C2F0 ensureAppropriateStorage DataStorageInterface WAS m_oDataStorage 0x000000001478E590 m_pDataStorage 0x000000001478E590
' 4:< DataStorageInterface created 0x0000000014A4CD50
' 4:< DataStorageInterface destroyed 0x000000001478E590
' 4:< MasterLocks 0x000000000012C2F0 ensureAppropriateStorage DataStorageInterface m_oDataStorage 0x0000000014A4CD50 m_pDataStorage 0x0000000014A4CD50
' 4:< SLOG $1de94fdf 2016-08-22 20:30:13.434 .WSD:LockRoot R SCODE=0x80070035
' 3:< initTransactionStatus unable to refresh permissions
' 3:< DataStorageInterface destroyed 0x0000000014A4CD50
**' 3:< 0 ModelServerState "Destroyed": Current server = "Not Queried", Model server = "", Model server state = "Not Applicable"
' 2.407079=== 2:<<MFCProjectAgent::getWorksetConfigForLoading 'Specify' = askUser
' 1:< System.FormatException exception(Index (zero based) must be greater than or equal to zero and less than the size of the argument list.) was thrown from a handler of Idling event. The API event handler was registered by application Application RevitCommandListener (acf561d2-8c6c-4beb-be55-2346825b53a4). Changes made by this handler are going to be discarded.
' 0:< The Idling event callback used 20 seconds
Tried below code too,as suggested by #Matt but that is not opening the document either:
OpenOptions options = new OpenOptions();
options.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets;
ModelPath mdlPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(_revitFileToOpen);
uiapp.OpenAndActivateDocument(mdlPath, options, false);

So - it looks like there's some kind of problem in your code that's related to the worksets, and it's tripping up the idling event callback that you're in.
That said - Opening a whole file just to determine if it is workshared is a very expensive operation. Instead, you can call:
BasicFileInfo info = BasicFileInfo.Extract(filename);
if (info.IsWorkshared)...
Also - I think it probably would also work to call the OpenAndActivate method with the OpenDetached option, even if the model was not workshared. I believe I've done that before as well.

Related

How can i insert data again when it keeps saying open and close connection?

what is wrong with this code. i cannot insert data anymore, i kept
saying close and open the connection but when i open it i says . the
connection was already open. hope u help me
For employee_id As Integer = 0 To DataGridView1.Rows.Count - 1
If txt_employee_id.Text = DataGridView1.Rows(employee_id).Cells(0).Value.ToString Then
MessageBox.Show("Duplicate ID")
Else
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO employeelist VALUES('" + txt_employee_id.Text + "', '" + txt_password.Text + "', '" + txt_name.Text + "', '" + txt_address.Text + "', '" + txt_contact_info.Text + "', '" + txt_department.Text + "', '" + txt_position.Text + "', '" + txt_basic_salary.Text + "', '" + txt_usertype.Text + "' )"
cmd.ExecuteNonQuery()
txt_employee_id.Text = ""
txt_password.Text = ""
txt_name.Text = ""
txt_address.Text = ""
txt_contact_info.Text = ""
txt_department.Text = ""
txt_position.Text = ""
txt_basic_salary.Text = ""
txt_usertype.Text = ""
disp_data()
MessageBox.Show("Data Inserted")
End If
Next
You really ought to avoid having a common connection object in the first place, so this sort of thing can't happen. Store your connection string in a common location but then create, configure, open, use and destroy your connection object where it's needed, which will be the same place you create the command object, e.g.
Using connection As New MySqlConnection(connectionString),
command As New MySqlCommand(query, connection)
connection.Open()
command.ExecuteNonQuery()
End Using
Because you just created the connection, you know that it is not open so opening it will not be an issue. It gets closed implicitly at the end of the Using block.
That said, if you really want to use a common connection then you can. If you're being told to open it and that it was already open then obviously you're not closing it again after using it. Open, use, close. Simple:
con.Open()
cmd.ExecuteNonQuery()
con.Close()
If you do that every time you execute a command over the connection then it will work as expected. Don't open the connection anywhere that you're not using it and always close it afterwards.
Note that you don't need to open or close if you are calling Fill or Update on a data adapter, as it will do so implicitly. That said, if you are calling more than one method that will use the connection, e.g. ExecuteNonQuery multiple times or Fill or Update on multiple data adapters, you should call Open once at the start and Close once at the end. If you don't do that with data adapters then the connection will be implicitly closed and reopened between calls and that is inefficient.
can't open same connection object multiple time, for reopen you need to close it.
So just write below line above each execute command (cmd.ExecuteNonQuery()).
It will check connection is open or not if closed then open it
If con.State = ConnectionState.Closed Then con.Open()

Downloading png to disk creates broken file

In my project, I want to download a png file from a url and save it to disk.
I have a url to an image, and I can load it in my web browser without any problem.
But when I use Access to download this file and save it, it saves "a" file, but it doesn't seem to have any image. Every file it creates is 167kb, and I cannot view them with my graphics viewers (XnViewMP, for example).
When I load the created file with PE Studio, it says the MZ signature is missing (I'm not sure that means anything).
I've tried this with an .ico file on my local webserver, too, and have the same issue.
Here is the code I'm using to download the image file.
Public Function DownloadFile(whaturl As String, whatdestination As String) As Boolean
Dim newfilepath
Dim success As Boolean
Dim WinHttpReq: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", whaturl, False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
Dim oStream: Set oStream = CreateObject("ADODB.Stream")
oStream.type = 1 '1 is binary
oStream.Open
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile whatdestination, 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
success = True
Else
success = False
End If
DownloadFile = success
End Function
Maybe someone can tell my why this code seems to fail in downloading the png file? I've tried with an .ico file, too, and have the same problem. Maybe someone can help me with this code?
You are making it too hard. Use a function like this:
Option Compare Database
Option Explicit
' API declarations.
'
Private Declare Function URLDownloadToFile Lib "Urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
' Download a file or a page with public access from the web.
' Returns 0 if success, error code if not.
'
' If parameter NoOverwrite is True, no download will be attempted
' if an existing local file exists, thus this will not be overwritten.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' FileName = "C:\Test\CodeProjectProfile.jpg"
' Result = DownloadFile(Url, FileName)
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' FileName = "C:\Test\CodeProject1022704.html"
' Result = DownloadFile(Url, FileName)
'
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' -1 "local file could not be created."
'
' 2004-12-17. Gustav Brock, Cactus Data ApS, CPH.
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH. Added check for local file.
' 2017-06-05. Gustav Brock, Cactus Data ApS, CPH. Added option to no overwrite the local file.
'
Public Function DownloadFile( _
ByVal Url As String, _
ByVal LocalFileName As String, _
Optional ByVal NoOverwrite As Boolean) _
As Long
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Const ErrorNotFound As Long = -1
Dim Result As Long
If NoOverwrite = True Then
' Page or file should not be overwritten.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) <> "" Then
' File exists. Don't proceed.
Exit Function
End If
End If
' Download file or page.
' Return success or error code.
Result = URLDownloadToFile(0, Url & vbNullChar, LocalFileName & vbNullChar, BindFDefault, 0)
If Result = ErrorNone Then
' Page or file was retrieved.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) = "" Then
Result = ErrorNotFound
End If
End If
DownloadFile = Result
End Function
taken from my article: Show pictures directly from URLs in Access forms and reports
(If you don't have an account, browse for the link: Read the full article)
Full code is also at GitHub: VBA.PictureUrl

MS ACCESS webbrowser control file preview not working properly

I've been trying to display files in a form using the webbrowser control and have had some success when displaying pdf's, however, if I want to display a TIFF file it wants to download the picture rather than displaying it.
I suppose the question I am asking is if the webbrowser control can display TIFF files. Is there a workaround?
Cheers
Eych
You may need a more advanced picture control like csXImage to display TIFF pictures.
The file, you can download with my DownloadFile function found in my article here:
Show pictures directly from URLs in Access forms and reports
and also on GitHub: VBA.PictureUrl
Option Compare Database
Option Explicit
' API declarations.
'
Private Declare Function URLDownloadToFile Lib "Urlmon" Alias "URLDownloadToFileA" ( _
ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) _
As Long
' Download a file or a page with public access from the web.
' Returns 0 if success, error code if not.
'
' If parameter NoOverwrite is True, no download will be attempted
' if an existing local file exists, thus this will not be overwritten.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' FileName = "C:\Test\CodeProjectProfile.jpg"
' Result = DownloadFile(Url, FileName)
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' FileName = "C:\Test\CodeProject1022704.html"
' Result = DownloadFile(Url, FileName)
'
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' -1 "local file could not be created."
'
' 2004-12-17. Gustav Brock, Cactus Data ApS, CPH.
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH. Added check for local file.
' 2017-06-05. Gustav Brock, Cactus Data ApS, CPH. Added option to no overwrite the local file.
'
Public Function DownloadFile( _
ByVal Url As String, _
ByVal LocalFileName As String, _
Optional ByVal NoOverwrite As Boolean) _
As Long
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Const ErrorNotFound As Long = -1
Dim Result As Long
If NoOverwrite = True Then
' Page or file should not be overwritten.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) <> "" Then
' File exists. Don't proceed.
Exit Function
End If
End If
' Download file or page.
' Return success or error code.
Result = URLDownloadToFile(0, Url & vbNullChar, LocalFileName & vbNullChar, BindFDefault, 0)
If Result = ErrorNone Then
' Page or file was retrieved.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) = "" Then
Result = ErrorNotFound
End If
End If
DownloadFile = Result
End Function

Can I share an MS-Access database application via Dropbox?

I have a small Access application that only 3 or 4 people will ever use, but I want them to be able to use it from different locations. Only one person will use it at a time. They are a non-profit with little to no funding. They don't have a server and are currently sharing an Excel spreadsheet back and forth between all of them. The easiest thing I could think of doing was to upload the .accdb file to a Dropbox account and have them access it from there. I know that you can publish it to SharePoint, but all they have are local copies of Office. Are there any issues with doing the Dropbox thing or are there any better alternatives any of you could suggest?
I agree that using a Dropbox folder as a shared location could possibly work provided that only one person had the database open at any one time. If more than one person opened the database at the same time then when Dropbox went to sync the file it could clobber somebody else's changes, or have sync conflicts, or perhaps just get horribly confused.
If I was to try using this approach I certainly would not rely on telling users to "always check if somebody else is using the database before opening it" or "always open the database in Exclusive mode". Instead, I would use a little launcher script like the following VBScript to manage access to the database. It uses a second file extension (.Available or .IN_USE) to indicate the status of the database file, makes a local (not synced) copy, opens that copy in Access, and then copies the updated file back to the Dropbox folder so it can be synced.
Option Explicit
Dim WshShell, fso, f, AccessPath, DropboxFolder, WorkingFolder, DatabaseName
Const TemporaryFolder = 2
DropboxFolder = "C:\Users\Gord\Dropbox\dbStorage\"
DatabaseName = "myDatabase.accdb"
Set fso = CreateObject("Scripting.FileSystemObject")
WorkingFolder = fso.GetSpecialFolder(TemporaryFolder) & "\"
If fso.FileExists(DropboxFolder & DatabaseName & ".Available") Then
Set f = fso.GetFile(DropboxFolder & DatabaseName & ".Available")
f.Name = DatabaseName & ".IN_USE"
WScript.Echo "Copying database file to working folder..."
f.Copy WorkingFolder & DatabaseName
Set f = Nothing
Set WshShell = CreateObject("WScript.Shell")
AccessPath = WshShell.RegRead("HKEY_CLASSES_ROOT\Access.MDBFile\shell\Open\command\")
AccessPath = Left(AccessPath, InStr(AccessPath, "MSACCESS.EXE") + 12)
WScript.Echo "Launching Access..."
WshShell.Run AccessPath & " """ & WorkingFolder & DatabaseName & """", 1, True
WScript.Echo "Copying database file back to Dropbox folder..."
fso.CopyFile WorkingFolder & DatabaseName, DropboxFolder & DatabaseName & ".IN_USE"
Set f = fso.GetFile(DropboxFolder & DatabaseName & ".IN_USE")
f.Name = DatabaseName & ".Available"
Set f = Nothing
Else
If fso.FileExists(DropboxFolder & DatabaseName & ".IN_USE") Then
MsgBox "The database is currently in use. Try again later."
Else
MsgBox "The database could not be found."
End If
End If
Set fso = Nothing
The launcher could be invoked by a shortcut whose target is
CSCRIPT.EXE C:\wherever\launchMyDatabase.vbs
This is an enhanced version of Gord Thompsons script which tries to inform the user to help them do the "right thing".
It also deals with exceptional behaviour such as bad internet access (it encourages the user NOT to use it!) and it also deals with the script being terminated by the user once access has been opened)
' This uses a second file extension (.Available or .InUse) to indicate the status of the database file,
' makes a local (not synced) copy inthe temp folder and opens that copy in Access.
' The updated file is copied back to the Dropbox folder so it can be synced.
' A backup fodler and file can be created with a date in the filename if the suer chooses to.
'
' The launcher could be invoked by a shortcut whose target is
'
' CSCRIPT.EXE C:\!AA\OpenFMFtoolDatabase.vbs
' Or to debug (it can open in VS if VS has been setup right with an external tool)
' CSCRIPT.EXE /X C:\!AA\OpenFMFtoolDatabase.vbs
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' This file is used to open and backup the FMFtool university and Subject database
'
' It can be invoked by a shortcut whose target is CSCRIPT.EXE C:\!AA\OpenFMFtoolDatabase.vbs
'
' See the tag #DOTHESE below for constants that need to be changed for each specific user
'Option Explicit
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' Supporting functions
'
Function LPad(MyString, MakeStringThisLong, PadWithThisChar)
Dim n: n = 0
If MakeStringThisLong > Len(MyString) Then n = MakeStringThisLong - Len(MyString)
LPad = String(n, PadWithThisChar) & MyString
End Function
Function BuildDateForFile()
Dim TheMonth, TheDay
TheMonth = LPad(Month(Date), 2, "0")
TheDay = LPad(Day(Date), 2, "0")
BuildDateForFile = DatePart("yyyy", Now) & TheMonth & TheDay & "_"
End Function
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' Main Procedure
'
Sub OpenDatabase()
' -----------------------------------------------------------------
' -----------------------------------------------------------------
' USER / MACHINE SPECIFIC #DOTHESE
Const SupportEmail = "mr#harveyfrench.co.uk"
' This script may prompt the user to contact support using this email address.
Const DropboxFolder = "C:\!AA\DropBox\"
' A typical value is "C:\Users\Gord\Dropbox\dbStorage\" Note that it must END WITH a backslash
' It is set to the name of the LOCAL folder (ie a folder on the PC running this script) which is synced with dropbox
' (or any internet based file sharing system like Dropbox, Onedrive, GDrive, etc)
Const DatabaseCalled = "University and Subject Database"
' The name of the database file without the file extension (ie no .accdb)
Const DatabaseExtension = ".accdb"
' The file extension (eg .accdb)
' -----------------------------------------------------------------
' -----------------------------------------------------------------
' General constants
Const TemporaryFolder = 2
Const TAGForINUSE = ".InUse"
Const TAGForAVAILABLE = ".Available"
Const TAGForOldLocalFile = ".OldFile"
Dim WshShell, f, AccessPath, WorkingFolder, DatabaseName
Dim FileNameWhenInUse, FileNameWhenAvailable
Dim DropBoxInUse, DropBoxAvailable
Dim DropboxBackupFolder, DropboxBackupFileName, DropboxDONOTBackupFileName
Dim LocalFile, OldLocalFile
Dim blnOpenLocalFile
' -----------------------------------------------------------------
' Use these lines when delivering the code
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
' -----------------------------------------------------------------
' Use may use these lines when writing the code
'Dim fso As Scripting.FileSystemObject
'Set fso = New Scripting.FileSystemObject
' -----------------------------------------------------------------
' About files and folders
DatabaseName = DatabaseCalled & DatabaseExtension
FileNameWhenInUse = DatabaseName & TAGForINUSE
FileNameWhenAvailable = DatabaseName & TAGForAVAILABLE
DropBoxInUse = DropboxFolder & FileNameWhenInUse
DropBoxAvailable = DropboxFolder & FileNameWhenAvailable
DropboxBackupFolder = DropboxFolder & "Backups"
WorkingFolder = fso.GetSpecialFolder(TemporaryFolder) & "\"
' eg often: C:\Users\Harvey\AppData\Local\Temp\
LocalFile = WorkingFolder & DatabaseName
OldLocalFile = LocalFile & TAGForOldLocalFile
blnOpenLocalFile = False
' -----------------------------------------------------------------
' WARN User
'
If vbNo = MsgBox("This will open " & DatabaseName & vbCrLf & _
vbCrLf & _
"DO YOU HAVE ACCESS TO THE WEB?" & vbCrLf & _
vbCrLf & _
"Do not click YES unless you are sure you do as the web is needed to prevent other people from opening the above file while you have it open. " & vbCrLf & _
vbCrLf & _
"NOTE 1: It is OK to loose web access once the file is opened - but others will not be able to use it again until you have web access (and have closed the file)." & vbCrLf & _
vbCrLf & _
"NOTE 2: If you click YES and you do not have web accesss, either you or someone else WILL LOOSE ALL changes made to the file!)", vbYesNo) Then
Exit Sub
End If
' ---------------------------------------------------------------------------------
' ---------------------------------------------------------------------------------
'
' Main processing -
' The file is only opened if it is available (ie not in use by another person).
' It can also be opened if it is determined that the file was not copied back to the dropbox folder
' but was "accidentally" left in the temp folder
' When it is opened the file is renamed on dropbox to indicate it is unavailable
'
If fso.FileExists(DropBoxAvailable) Then
Set f = fso.GetFile(DropBoxAvailable)
' This renames the file on dropbox to be "InUse"
f.Name = FileNameWhenInUse
'
' Allow dropbox to upload the file ASAP (if possible, force dropbox to sync here )
'
WScript.Echo "Copying database file to temp folder..."
f.Copy LocalFile
Set f = Nothing
blnOpenLocalFile = True
Else
If fso.FileExists(DropBoxInUse) Then
If fso.FileExists(LocalFile) Then
MsgBox "The database was found locally and will be opened " & vbCrLf & _
vbCrLf & _
"(it had already been previoulsy opened by you, but not written back to the dropbox folder (perhaps a process crashed)."
blnOpenLocalFile = True
Else
MsgBox "The database is currently in use by someone else. Try again later."
blnOpenLocalFile = False
End If
Else
MsgBox "The database could not be found on dropbox " & vbCrLf & _
vbCrLf & _
"(Both " & TAGForINUSE & " and " & TAGForAVAILABLE & " versions are missing from dropbox!)."
If fso.FileExists(LocalFile) Then
MsgBox "A Copy of the file exists locally on your computer. " & vbCrLf & _
vbCrLf & _
"(The file will be opened and written back to dropbox as usual BUT - " & vbCrLf & _
"please email " & SupportEmail & " as this situation should not be arising!)."
blnOpenLocalFile = True
Else
If fso.FileExists(OldLocalFile) Then
MsgBox "A backup copy of the local file exists (know as the OldLocalFile)" & vbCrLf & _
vbCrLf & "Email support on " & SupportEmail & vbCrLf & _
"to find out what to do (as this is a really wierd situation)."
Else
MsgBox "A backup copy of the local file DOES NOT EXIST " & vbCrLf & _
vbCrLf & "Email support on " & SupportEmail & vbCrLf & _
"..but being honest you may be in a really bad pickle, but if you've been taking backups you'll be fine!"
End If
blnOpenLocalFile = False
End If
End If
End If
If blnOpenLocalFile Then
' ---------------------------------------------------------------------------------
' Take a daily backup
'
If Not fso.FolderExists(DropboxBackupFolder) Then
WScript.Echo "Creating backup folder."
fso.CreateFolder DropboxBackupFolder
End If
DropboxBackupFileName = DropboxBackupFolder & "\" & BuildDateForFile() & DatabaseName
DropboxDONOTBackupFileName = DropboxBackupFileName & ".NoBackup"
DropboxBackupFileName = DropboxBackupFileName & ".Backup"
If Not (fso.FileExists(DropboxBackupFileName)) And Not (fso.FileExists(DropboxDONOTBackupFileName)) Then
If vbYes = MsgBox("Do you want to take a daily backup? " & vbCrLf & _
vbCrLf & "(click YES if a lot of work has been done since the last backup was taken. " & vbCrLf & _
" If in doubt click YES)", vbYesNo) Then
WScript.Echo "Creating daily backup file."
fso.CopyFile LocalFile, DropboxBackupFileName
Else
' Create an empty text file to flag no backup is wanted that day
WScript.Echo "No daily backup file will be created."
fso.CreateTextFile (DropboxDONOTBackupFileName)
End If
End If
' ---------------------------------------------------------------------------------
' Open the file
'
Set WshShell = CreateObject("WScript.Shell")
AccessPath = WshShell.RegRead("HKEY_CLASSES_ROOT\Access.MDBFile\shell\Open\command\")
AccessPath = Left(AccessPath, InStr(AccessPath, "MSACCESS.EXE") + 12)
WScript.Echo "Launching Access and Opening temp database file: " & vbCrLf & LocalFile
WshShell.Run AccessPath & " """ & LocalFile & """", 1, True
WScript.Echo "Copying temp database file back to Dropbox folder..."
fso.CopyFile LocalFile, DropBoxInUse
Set f = fso.GetFile(DropBoxInUse)
f.Name = FileNameWhenAvailable
Set f = Nothing
' Make another copy of the file that was copied to the dropbox folder, then delete the original file
' (This might help stop a bad catastrophe!)
WScript.Echo "In Temp Folder: Copying temp database file to be .oldfile"
fso.CopyFile LocalFile, OldLocalFile
WScript.Echo "In Temp Folder: Deleting temp database file "
fso.DeleteFile LocalFile
End If
Set fso = Nothing
End Sub
' Do the work!
OpenDatabase
I know this is an old question, I do not think it is possible to do this safely. The issue is that LDB files, which are the files that manages the share of connections to the database can lose track of open state. This occurs when external files are joined to the primary database via JOIN/IN type constructs. When this occurs the Jet/ADO engine still has locks on files even if the application exits, as the file specified in the IN clauses is opened but not closed when the query completes. Then DropBox creates conflicted copies of files and data is lost.

How to setup a scheduled task in Windows XP to run a Marcro in ms-access?

I typically have some need to run a process each day prior to my arrival at the office. I would like to set this up as a scheduled task.
How can this be accomplished?
Is there a best practice on doing this?
Can or should this be done programmatically?
To resolve this I did the following:
Created a Macro named "Submit".
Created a Scheduled task .job file by going to:
Start > All Programs > Accessories > System Tools > Schedule Tasks
(This produced the .job file in the following location: "C:\WINDOWS\Tasks\Submit.job")
Once this was created, I placed the following syntax into the Run: text box.
"C:\Program Files\Microsoft Office\Office11\MSACCESS.EXE" "C:\MyDatabasePath\MyDatabaseName.mdb" /x "Submit"
After this, the remaining portion of the setup is completed as a normal schedule task should be. You can find more details about how to manually setup these tasks [here][2] or if you like to perform the setup through the command line, this is a particularly useful reference.
Note: Both the Macro and the job file must be setup for this to work correctly.
One way to accomplish this programmatically would be do utilize the job API's. Here is one such example where this was accomplished using VBA:
See Reference Here
Option Explicit
' Schedule api's
Declare Function NetScheduleJobAdd Lib "netapi32.dll" _
(ByVal Servername As String, Buffer As Any, Jobid As Long) As Long
' Schedule structure
Type AT_INFO
JobTime As Long
DaysOfMonth As Long
DaysOfWeek As Byte
Flags As Byte
dummy As Integer
Command As String
End Type
' Schedule constants
Const JOB_RUN_PERIODICALLY = &H1
Const JOB_NONINTERACTIVE = &H10
Const NERR_Success = 0
Private Sub Command1_Click()
Dim lngWin32apiResultCode As Long
Dim strComputerName As String
Dim lngJobID As Long
Dim udtAtInfo As AT_INFO
' Convert the computer name to unicode
strComputerName = StrConv(Text1.Text, vbUnicode)
' Setup the tasks parameters
SetStructValue udtAtInfo
' Schedule the task
lngWin32apiResultCode = NetScheduleJobAdd(strComputerName, udtAtInfo, lngJobID)
' Check if the task was scheduled
If lngWin32apiResultCode = NERR_Success Then
MsgBox "Task" & lngJobID & " has been scheduled."
End If
End Sub
Private Sub SetStructValue(udtAtInfo As AT_INFO)
Dim strTime As String
Dim strDate() As String
Dim vntWeek() As Variant
Dim intCounter As Integer
Dim intWeekCounter As Integer
vntWeek = Array("M", "T", "W", "TH", "F", "S", "SU")
With udtAtInfo
' Change the format of the time
strTime = Format(Text2.Text, "hh:mm")
' Change the time to one used by the api
.JobTime = (Hour(strTime) * 3600 + Minute(strTime) * 60) * 1000
' Set the Date parameters
If Val(Text3.Text) > 0 Then
' Set the task to run on specific days of the month i.e. 9th & 22nd of the month
strDate = Split(Text3.Text, ",")
For intCounter = 0 To UBound(strDate)
.DaysOfMonth = .DaysOfMonth + 2 ^ (strDate(intCounter) - 1)
Next
Else
' Set the task to run on sepecific days of the week i.e. Monday & Thursday
strDate = Split(Text3.Text, ",")
For intCounter = 0 To UBound(strDate)
For intWeekCounter = 0 To UBound(vntWeek)
If UCase(strDate(intCounter)) = vntWeek(intWeekCounter) Then
.DaysOfWeek = .DaysOfWeek + 2 ^ intWeekCounter
Exit For
End If
Next
Next
End If
' Set the interactive property
If Check1.Value = vbUnchecked Then
.Flags = .Flags Or JOB_NONINTERACTIVE
End If
' Set to run periodically
If Option2.Value = True Then
.Flags = .Flags Or JOB_RUN_PERIODICALLY
End If
' Set the command to run
.Command = StrConv(Text4.Text, vbUnicode)
End With
End Sub
If the tasks do not run appropriately, it may be due to updates in software and/or service packs. Check the program files for Microsoft Office and Access. "Office11" as shown in the run line may need to be changed to "Office 14" or "Office12" depending on the folders showing in program files.