Dev2.DynamicServices.FileSystemInstanceStoreIO.SaveInstanceAssociation C# (CSharp) Method

SaveInstanceAssociation() public method

public SaveInstanceAssociation ( System.Guid instanceId, System.Guid instanceKeyToAssociate, System.Boolean isDelete ) : void
instanceId System.Guid
instanceKeyToAssociate System.Guid
isDelete System.Boolean
return void
        public void SaveInstanceAssociation(Guid instanceId, Guid instanceKeyToAssociate, Boolean isDelete)
        {
            try
            {
                var fullPath = GetSaveInstanceAssociationPath(instanceId, instanceKeyToAssociate);
                lock(fullPath)
                {
                    if(!isDelete)
                    {
                        if(!File.Exists(fullPath))
                        {
                            File.Create(fullPath);
                        }
                    }
                    else
                    {
                        if(File.Exists(fullPath))
                        {
                            File.Delete(fullPath);
                        }
                    }
                }
            }
            catch(Exception exception)
            {
                Dev2Logger.Log.Error(exception);
                throw new InstancePersistenceException(exception.Message, exception);
            }
        }

Usage Example

        // ReSharper disable InconsistentNaming - Unit Tests
        public void SaveInstanceAssociation_With_FileUsedByAnotherProcess_Expected_ThrowsInstancePersistenceException()
        // ReSharper restore InconsistentNaming
        {
            var instanceId = Guid.NewGuid();
            var instanceKey = Guid.NewGuid();

            var store = new FileSystemInstanceStoreIO();

            var path = store.GetSaveInstanceAssociationPath(instanceId, instanceKey);

            try
            {
                var xml = XmlResource.Fetch(TestFileName);
                xml.Save(path);

                // Force error: The process cannot access the file because it is being used by another process
                using(var fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    store.SaveInstanceAssociation(instanceId, instanceKey, true);
                }
            }
            finally
            {
                if(File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }