private void ExecuteStep(UpdateStep step) { Dictionary <Type, NodeObjAction> actionDict; if (!ActionDictionary.TryGetValue(step, out actionDict)) { return; } var types = actionDict.Keys.ToArray(); foreach (var key in types) { var value = actionDict[key]; NodeObjAction next; value.GetData(out next).Item2(); actionDict[key] = next; } /*using (var enumerator = actionDict.GetEnumerator()) * { * while (enumerator.MoveNext()) { * var element = enumerator.Current; * var key = element.Key; * var value = actionDict[key]; * NodeObjAction next; * value.GetData(out next).Item2(); * actionDict[key] = next; * } * }*/ }
/// <summary> /// Gets all valid target versions for a specified version of Factorio. /// </summary> /// <param name="versionToUpdate">The version of Factorio that is to be updated.</param> /// <param name="updateSteps">The available update steps provided by the API.</param> /// <returns>Returns a list of valid update targets for the specified version of Factorio.</returns> public static List <UpdateTarget> GetUpdateTargets(FactorioVersion versionToUpdate, List <UpdateStep> updateSteps) { var targets = new List <UpdateTarget>(); var groups = updateSteps.GroupBy(step => new Version(step.To.Major, step.To.Minor)); foreach (var group in groups) { UpdateStep targetStep = group.MaxBy(step => step.To, new VersionComparer()); List <UpdateStep> stepChain = GetStepChain(updateSteps, versionToUpdate.Version, targetStep.To); UpdateTarget target = new UpdateTarget(stepChain, targetStep.To, targetStep.IsStable); targets.Add(target); if (!targetStep.IsStable) { UpdateStep stableStep = group.Where(step => step.IsStable).MaxBy(step => step.To, new VersionComparer()); if (stableStep != null) { stepChain = GetStepChain(updateSteps, versionToUpdate.Version, stableStep.To); target = new UpdateTarget(stepChain, stableStep.To, true); targets.Add(target); } } } return(targets); }
// 下载远程文件列表回调 void OnDownloadRemoteResFileList(bool bSuccess) { if (bSuccess) { m_curUpdateStep = UpdateStep.CompareRes; // 远程文件列表请求成功,开始查找需要下载的资源 LogModule.DebugLog("load file success: " + CacheVersionPath + "/" + ResFileListName); string localFileListName = LocalVersionPath + "/" + ResFileListName; LogModule.DebugLog(localFileListName); // 如果读取目录没有文件,将包体文件拷贝出 if (!File.Exists(localFileListName)) { m_versionFileDownloader = DownloadHelper.StartDownload(this, GetAppDataUrl(AppVersionFolder, ResFileListName), false, localFileListName, OnDownloadLocalResFileList); } else { OnDownloadLocalResFileList(true); } } else { // 下载远程文件列表失败,应该重新请求 UpdateFinish(UpdateResult.GetFileListFail); } }
private static Tree GetNewErrorTimestampsTreeFromErrorsTable(UpdateStep step, Slice errorTimestampsSlice) { var newTableSchema = new TableSchema(); var indexDef = new TableSchema.SchemaIndexDef { StartIndex = 0, IsGlobal = false, Name = errorTimestampsSlice }; newTableSchema.DefineIndex(indexDef); newTableSchema.Create(step.WriteTx, "Errors", 16); var newErrorsTable = step.WriteTx.OpenTable(newTableSchema, "Errors"); var newErrorsTableTableTree = step.WriteTx.ReadTree("Errors", RootObjectType.Table); byte *ptr; using (var indexTree = Tree.Create(step.WriteTx.LowLevelTransaction, step.WriteTx, indexDef.Name, isIndexTree: true)) { using (newErrorsTableTableTree.DirectAdd(indexDef.Name, sizeof(TreeRootHeader), out ptr)) { indexTree.State.CopyTo((TreeRootHeader *)ptr); } } var newErrorTimestampsIndexTree = newErrorsTable.GetTree(newTableSchema.Indexes[errorTimestampsSlice]); return(newErrorTimestampsIndexTree); }
/// <summary> /// Gets all valid target versions for a specified version of Factorio. /// </summary> /// <param name="versionToUpdate">The version of Factorio that is to be updated.</param> /// <param name="installedVersions">A collection that contains all installed versions of Factorio.</param> /// <param name="updateSteps">The available update steps provided by the API.</param> /// <returns>Returns a list of valid update targets for the specified version of Factorio.</returns> public static List <UpdateTarget> GetUpdateTargets(FactorioVersion versionToUpdate, ICollection <FactorioVersion> installedVersions, List <UpdateStep> updateSteps) { var targets = new List <UpdateTarget>(); var groups = updateSteps.GroupBy(step => new Version(step.To.Major, step.To.Minor)); foreach (var group in groups) { UpdateStep targetStep = group.MaxBy(step => step.To, new VersionComparer()); List <UpdateStep> stepChain = GetStepChain(updateSteps, versionToUpdate.Version, targetStep.To); bool isValid = installedVersions.All(version => version.IsSpecialVersion || !version.IsFileSystemEditable || version.Version != targetStep.To); UpdateTarget target = new UpdateTarget(stepChain, targetStep.To, targetStep.IsStable, isValid); targets.Add(target); if (!targetStep.IsStable) { UpdateStep stableStep = group.FirstOrDefault(step => step.IsStable); if (stableStep != null) { stepChain = GetStepChain(updateSteps, versionToUpdate.Version, stableStep.To); isValid = installedVersions.All(version => version.IsSpecialVersion || !version.IsFileSystemEditable || version.Version != stableStep.To); target = new UpdateTarget(stepChain, stableStep.To, true, isValid); targets.Add(target); } } } return(targets); }
private static bool UpdateErrorTimestampsTreeInErrorsTable(UpdateStep step) { using (Slice.From(step.ReadTx.Allocator, "ErrorTimestamps", out var errorTimestampsSlice)) { var oldErrorsTable = GetOldErrorsTable(step, errorTimestampsSlice, out var oldTableSchema); var oldErrorTimestampsTree = oldErrorsTable?.GetTree(oldTableSchema.Indexes[errorTimestampsSlice]); if (oldErrorTimestampsTree == null) { return(false); } var newErrorTimestampsTree = GetNewErrorTimestampsTreeFromErrorsTable(step, errorTimestampsSlice); using (var oldErrorsTreeIterator = oldErrorTimestampsTree.Iterate(false)) { if (oldErrorsTreeIterator.Seek(Slices.BeforeAllKeys)) { do { newErrorTimestampsTree.Add( oldErrorsTreeIterator.CurrentKey, oldErrorsTreeIterator.CreateReaderForCurrent().AsStream()); } while (oldErrorsTreeIterator.MoveNext()); } } step.WriteTx.DeleteTree(oldErrorTimestampsTree.Name); return(true); } }
void OnShowUpdateStepFail(int errorCode) { string tip = "Error on state :" + _currentStep.State + "\nError code : " + errorCode; Debugger.LogError(tip); switch (_currentStep.State) { case UpdateState.CheckNetWork: tip = "No network!"; break; } //* UpdateStep us = new UpdateStep(); us.State = UpdateState.UpdateFinish; OnShowUpdateStep(us); return; //*/ Helper.ShowMessageBox(tip, () => { _currentStep.CallBack(); }); }
// 获取版本号回调 void OnCheckVersion(bool bSuccess) { if (bSuccess) { LogModule.DebugLog("comparing version"); // 比较版本号 LogModule.DebugLog("version --local:" + m_localVersion.ToString() + " --remote:" + m_remoteVersion); if (m_remoteVersion > m_localVersion) { Utils.DeleteFolder(CacheVersionPath); LogModule.DebugLog("remote version is big than local, begin update"); m_curUpdateStep = UpdateStep.GetFileList; // 下载文件列表 m_versionFileDownloader = DownloadHelper.StartDownload(this, m_resServerUrl + "/" + ResFileListName, true, CacheVersionPath + "/" + ResFileListName, OnDownloadRemoteResFileList); } else { StartCoroutine(OnDownloadlevelIndexFile()); } } else { // error 严重错误,可能网络不通,需要重新请求 LogModule.ErrorLog("check verion fail"); UpdateFinish(UpdateResult.GetVersionFail); } }
void updateHelper_UpdateStepMismatch(object sender, Response respType, UpdateStep previousStep) { // we can't install right now if (previousStep == UpdateStep.RestartInfo) { if (ClosingAborted != null) { ClosingAborted(this, EventArgs.Empty); } } if (respType == Response.Progress) { switch (updateHelper.UpdateStep) { case UpdateStep.CheckForUpdate: UpdateStepOn = UpdateStepOn.Checking; break; case UpdateStep.DownloadUpdate: UpdateStepOn = UpdateStepOn.DownloadingUpdate; break; case UpdateStep.BeginExtraction: UpdateStepOn = UpdateStepOn.ExtractingUpdate; break; } } if (UpdateStepMismatch != null) { UpdateStepMismatch(this, EventArgs.Empty); } }
public void StartCheckRes(string resServerUrl, int playerLevel = 0) { m_remoteVersion = -1; if (null != m_versionFileDownloader) { m_versionFileDownloader.Stop(); } if (null != m_dataFileDownloader) { m_dataFileDownloader.Stop(); } if (!Utils.GetFileInt(LocalVersionPath + "/" + LocalResLevelFileName, out m_localResLevel)) { m_localResLevel = GameDefines.RESLEVEL_LOCAL; } m_playerNeedResLevel = playerLevel; if (m_playerNeedResLevel < m_localResLevel) { m_playerNeedResLevel = m_localResLevel; } m_downloadResLevel = 0; m_resServerUrl = resServerUrl; m_remoteDataPath = m_resServerUrl + "/" + DownloadDataFolder;; m_remoteVersion = -1; m_versionFileDownloader = null; m_dataFileDownloader = null; m_totalNeedDownloadSize = 0; m_curUpdateStep = UpdateStep.CheckVersion; StartCoroutine(GetResVersion(OnCheckVersion)); }
public void SendSuccess(UpdateStep step, int windowHandle) { pipeServer.SendMessage(new UpdateHelperData(Response.Succeeded, step) { ProcessID = windowHandle }.GetByteArray()); }
void SendAsync(UpdateHelperData uhd) { lock (_lock) { if (isDisposed) { return; } // if currently working, add the new message to the stack if (bw != null) { sendBuffer.Push(uhd); } else { RecreateBackgroundWorker(); // process immediately UpdateStep = uhd.UpdateStep == UpdateStep.ForceRecheckForUpdate ? UpdateStep.CheckForUpdate : uhd.UpdateStep; // begin sending to the client bw.RunWorkerAsync(uhd); } } }
private static unsafe void UpdateDocumentCounters(UpdateStep step, DocumentsOperationContext context, string docId, CollectionName collection) { using (DocumentIdWorker.GetSliceFromId(context, docId, out Slice lowerDocId)) { var table = step.WriteTx.OpenTable(DocumentsStorage.DocsSchema, collection.GetTableName(CollectionTableType.Documents)); if (table.ReadByKey(lowerDocId, out var tvr) == false) { return; // document doesn't exists } var tableId = tvr.Id; var counterNames = step.DocumentsStorage.CountersStorage.GetCountersForDocument(context, step.WriteTx, docId).ToList(); var doc = step.DocumentsStorage.TableValueToDocument(context, ref tvr, skipValidationInDebug: true); if (doc.TryGetMetadata(out var metadata) == false) { if (counterNames.Count > 0) { doc.Flags |= DocumentFlags.HasCounters; var dvj = new DynamicJsonValue { [Constants.Documents.Metadata.Counters] = counterNames }; doc.Data.Modifications = new DynamicJsonValue(doc.Data) { [Constants.Documents.Metadata.Key] = dvj }; } else { doc.Flags &= ~DocumentFlags.HasCounters; } }
private void ResetState() { this._installFirmware = false; this._installGames = false; this._updateCollection = null; this._isUpdateAvailable = false; this._isCheckingForUpdates = false; this._updateInProgress = false; this._currentStep = null; this._lastCheckForUpdatesResult = HRESULT._S_OK; this._lastCheckForDiskSpaceResult = HRESULT._S_OK; this._lastCheckForUpdateErrorInfo = null; this._lastUpdateResult = HRESULT._S_OK; this._lastFirmwareUpdateErrorInfo = null; this._isSoftFailure = false; this._canCancel = true; this._needsCollectionRefresh = true; this._launchWizardIfUpdatesFound = false; this._fCancelInProgress = false; this._rollbackStarted = false; this._estimatedUpdateTime = 0; this._estimatedUpdateTimeInProgress = false; this._requiresSyncBeforeUpdate = false; this._updateOption = FirmwareUpdateOption.None; this._diskSpaceInfo = null; this.FirePropertyChanged("IsUpdateAvailable"); }
public UpdateHelperData(Response responseType, UpdateStep step, string messageTitle, string messageBody) : this(responseType, step) { ExtraData.Add(messageTitle); ExtraData.Add(messageBody); ExtraDataIsRTF.Add(item: false); ExtraDataIsRTF.Add(item: false); }
// 下载资源回调 void OnDownloadRes(bool bSuccess) { if (bSuccess) { LogModule.DebugLog("check res md5"); m_curUpdateStep = UpdateStep.CheckRes; // 下载所有文件成功,开始检查文件,将MD5错误或未下载文件放入错误文件列表 m_listUpdateErrorFiles.Clear(); foreach (string updateFileName in m_listUpdateFiles) { string curFilePath = m_cacheDataPath + "/" + updateFileName; if (!File.Exists(curFilePath)) { LogModule.ErrorLog("download file fail " + updateFileName); m_listUpdateErrorFiles.Add(updateFileName); } else { string curFileMD5 = Utils.GetMD5Hash(curFilePath); if (!m_dicRemoteFiles.ContainsKey(updateFileName) || curFileMD5.ToLower() != m_dicRemoteFiles[updateFileName].md5.ToLower()) { LogModule.ErrorLog("download file md5 error : romote:" + m_dicRemoteFiles[updateFileName].md5 + " local :" + curFileMD5); m_listUpdateErrorFiles.Add(updateFileName); } else { if (m_dicLocalFiles.ContainsKey(updateFileName)) { m_dicLocalFiles[updateFileName].CopyData(m_dicRemoteFiles[updateFileName]); } else { m_dicLocalFiles.Add(updateFileName, m_dicRemoteFiles[updateFileName]); } } } } if (m_listUpdateErrorFiles.Count == 0) { // 没有错误文件,开始拷贝过程 LogModule.DebugLog("check res success"); CopyResToDataPath(); } else { // 有文件发生错误,应该重新比对下载 LogModule.ErrorLog("check res fail"); UpdateFinish(UpdateResult.DownloadInComplete); } } else { // 下载资源失败,应该重新比对下载 LogModule.ErrorLog("download res error"); UpdateFinish(UpdateResult.DownloadFail); } }
public UpdateHelperData(Response responseType, UpdateStep step, string messageTitle, string messageBody) : this(responseType, step) { ExtraData.Add(messageTitle); ExtraData.Add(messageBody); ExtraDataIsRTF.Add(false); ExtraDataIsRTF.Add(false); }
void Decrement() { if ((_step - 1) >= 0) { _step--; } UpdateStep?.Invoke(_step); Debug.Log("pc step " + _step); }
void Increment() { if ((_step + 1) < _steps) { _step++; } UpdateStep?.Invoke(_step); Debug.Log("pc step " + _step); }
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { lock (_lock) { if (isDisposed) { return; } bw.DoWork -= bw_DoWork; bw.RunWorkerCompleted -= bw_RunWorkerCompleted; bw.Dispose(); bw = null; // error occurs when a message fails to send or wyUpdate fails to start if (e.Error != null) { // if the process is running - try to kill it try { if (ClientProcess != null && !ClientProcess.HasExited) { ClientProcess.Kill(); } } catch { } // set the client process to null so it can be restarted // when the user retries. ClientProcess = null; // clear the to-send stack sendBuffer.Clear(); // inform the AutomaticUpdater that wyUpdate is no longer running if (PipeServerDisconnected != null) { PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, e.Error.Message)); } } else { // process the next in stack if (sendBuffer.Count > 0) { RecreateBackgroundWorker(); UpdateHelperData uhd = sendBuffer.Pop(); UpdateStep = uhd.UpdateStep; // begin sending to the client bw.RunWorkerAsync(uhd); } } } }
// 获取版本号回调 void OnCheckVersion(bool bSuccess) { if (bSuccess) { LogMgr.UnityLog("comparing version"); // 比较版本号 int m_localVerion = -1; string localVersionFilePath = LocalVersionPath + "/" + VersionFileName; string AppVersionFilePath = AppVersionPath + "/" + VersionFileName; string curVersionFilePath = null; if (File.Exists(localVersionFilePath)) { curVersionFilePath = localVersionFilePath; } else if (File.Exists(AppVersionFilePath)) { curVersionFilePath = AppVersionFilePath; } if (null != curVersionFilePath) { FileStream fs = new FileStream(curVersionFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(fs); string localVersion = sr.ReadLine(); sr.Close(); fs.Close(); if (!int.TryParse(localVersion, out m_localVerion)) { LogMgr.UnityLog("parse version error"); } } LogMgr.UnityLog("version --local:" + m_localVerion.ToString() + " --remote:" + m_remoteVersion); if (m_remoteVersion > m_localVerion) { LogMgr.UnityLog("remote version is big than local, begin update"); m_curUpdateStep = UpdateStep.GetFileList; // 下载文件列表 m_versionFileDownloader = DownloadHelper.StartDownload(m_resServerUrl + "/" + ResFileListName, CacheVersionPath + "/" + ResFileListName, OnDownloadResFileList); } else { UpdateFinish(UpdateResult.Success); } } else { // error LogMgr.UnityLog("check verion fail"); UpdateFinish(UpdateResult.GetVersionFail); // 严重错误,可能网络不通,需要重新请求 } }
public bool Update(UpdateStep step) { // When the revision are enabled and we delete a document we stored it with a 'RevisionDelete' flag. This flag was used to find the deleted revisions. // Now we store the resolved conflicts as revisions, so it could be, that a deleted revision will contain flags such as 'Conflicted' or 'Resolved'. // This change require use to change the index definition and the logic of how we find the deleted revisions. // So we say that if the revision is deleted it will be stored with the 'DeletedEtag' to the etag value, // otherwise (if the revision is a document) it will be stored with 'DeletedEtag' set to 0. step.DocumentsStorage.RevisionsStorage = new RevisionsStorage(step.DocumentsStorage.DocumentDatabase, step.WriteTx); using (step.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context)) { step.WriteTx.DeleteTree("RevisionsFlagsAndEtag"); // remove the old index step.WriteTx.CreateTree(DeleteRevisionEtagSlice); foreach (var collection in step.DocumentsStorage.RevisionsStorage.GetCollections(step.ReadTx)) { var collectionName = new CollectionName(collection); var tableName = collectionName.GetTableName(CollectionTableType.Revisions); var readTable = step.ReadTx.OpenTable(RevisionsSchema, tableName); if (readTable == null) { continue; } var writeTable = step.DocumentsStorage.RevisionsStorage.EnsureRevisionTableCreated(step.WriteTx, collectionName); foreach (var read in readTable.SeekForwardFrom(RevisionsSchema.FixedSizeIndexes[CollectionRevisionsEtagsSlice], 0, 0)) { using (TableValueReaderUtil.CloneTableValueReader(context, read)) using (writeTable.Allocate(out TableValueBuilder write)) { var flags = TableValueToFlags((int)Columns.Flags, ref read.Reader); write.Add(read.Reader.Read((int)Columns.ChangeVector, out int size), size); write.Add(read.Reader.Read((int)Columns.LowerId, out size), size); write.Add(read.Reader.Read((int)Columns.RecordSeparator, out size), size); write.Add(read.Reader.Read((int)Columns.Etag, out size), size); write.Add(read.Reader.Read((int)Columns.Id, out size), size); write.Add(read.Reader.Read((int)Columns.Document, out size), size); write.Add((int)flags); if ((flags & DocumentFlags.DeleteRevision) == DocumentFlags.DeleteRevision) { write.Add(read.Reader.Read((int)Columns.Etag, out size), size); // set the DeletedEtag } else { write.Add(NotDeletedRevisionMarker); } write.Add(read.Reader.Read((int)Columns.LastModified, out size), size); write.Add(read.Reader.Read((int)Columns.TransactionMarker, out size), size); writeTable.Set(write, true); } } } } return(true); }
private void AddUpdateStep(UpdateStep step) { var connId = step.DestinationTable.ServerId; if (!_executionPlanByServer.ContainsKey(connId)) { _executionPlanByServer.Add(connId, new ExecutionPlan()); } _executionPlanByServer[connId].UpdateSteps.Add(step); }
void StartNextStep(UpdateStep updateStepOn) { // begin the next step switch (updateStepOn) { case UpdateStep.CheckForUpdate: if (!string.IsNullOrEmpty(version)) { // there's an update available if (internalUpdateType == UpdateType.CheckAndDownload || internalUpdateType == UpdateType.Automatic) { UpdateStepOn = UpdateStepOn.UpdateAvailable; // begin downloading the update DownloadUpdate(); } else { // show the update ready mark UpdateReady(); } } else //no update { // tell the user they're using the latest version AlreadyUpToDate(); } break; case UpdateStep.DownloadUpdate: // begin extraction if (internalUpdateType == UpdateType.Automatic) { ExtractUpdate(); } else { UpdateReadyToExtract(); } break; case UpdateStep.BeginExtraction: // inform the user that the update is ready to be installed UpdateReadyToInstall(); break; } }
public UpdateWriter(UpdateStep step, string identifierDelemiterStart, string identifierDelemiterEnd) { IdentifierDelemiterStart = identifierDelemiterStart; IdentifierDelemiterEnd = identifierDelemiterEnd; _sbSet.Append("UPDATE ") .Append(step.DestinationRow.Database) .Append(".") .Append(step.DestinationRow.Table) .Append(" SET "); }
void ServerReceivedData(byte[] message) { UpdateHelperData data = UpdateHelperData.FromByteArray(message); if (data.Action == UpdateAction.GetwyUpdateProcessID) { // send ProcessID pipeServer.SendMessage(new UpdateHelperData(UpdateAction.GetwyUpdateProcessID) { ProcessID = Process.GetCurrentProcess().Id }.GetByteArray()); return; } UpdateStep step = data.UpdateStep; if (step == UpdateStep.RestartInfo) { RestartInfoSent = true; // load the pre-install info if (data.ExtraData.Count > 0) { FileOrServiceToExecuteAfterUpdate = data.ExtraData[0]; IsAService = data.ExtraDataIsRTF[0]; } // load the AutoUpdateID (for writing to file whether the update failed or Succeeded) if (data.ExtraData.Count > 1) { AutoUpdateID = data.ExtraData[1]; } if (data.ExtraData.Count > 2) { ExecutionArguments = data.ExtraData[2]; } } else if (step == UpdateStep.Install) { // if we're already installing, don't bother to process the message again if (Installing) { return; } Installing = true; } if (RequestReceived != null) { RequestReceived(this, data.Action, step); } }
public bool Update(UpdateStep step) { var table = step.WriteTx.OpenTable(step.ConfigurationStorage.NotificationsStorage._actionsSchema, NotificationsStorage.NotificationsSchema.NotificationsTree); using (Slice.From(step.WriteTx.Allocator, PerformanceHint.GetKey(PerformanceHintType.SlowIO, string.Empty), out Slice slowIoHintPrefix)) { table.DeleteByPrimaryKeyPrefix(slowIoHintPrefix); } return(true); }
public void SystemOperations() { var entity = Manager.CreateEntity(); var transform = Manager.AddComponent <Transform>(entity); var rigidBody = Manager.AddComponent <RigidBody>(entity); var update = new UpdateStep(DeltaTime); Manager.Update(update); Assert.NotEqual(Vector2.Zero, rigidBody.Velocity); }
public bool Update(UpdateStep step) { step.DocumentsStorage.RevisionsStorage = new RevisionsStorage(step.DocumentsStorage.DocumentDatabase, step.WriteTx); // update revisions using (step.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext context)) { foreach (var collection in step.DocumentsStorage.RevisionsStorage.GetCollections(step.ReadTx)) { var collectionName = new CollectionName(collection); var tableName = collectionName.GetTableName(CollectionTableType.Revisions); var readTable = step.ReadTx.OpenTable(RevisionsSchema, tableName); if (readTable == null) { continue; } var writeTable = step.DocumentsStorage.RevisionsStorage.EnsureRevisionTableCreated(step.WriteTx, collectionName); foreach (var read in readTable.SeekForwardFrom(RevisionsSchema.FixedSizeIndexes[CollectionRevisionsEtagsSlice], 0, 0)) { using (TableValueReaderUtil.CloneTableValueReader(context, read)) using (writeTable.Allocate(out TableValueBuilder write)) { var flags = TableValueToFlags((int)Columns.Flags, ref read.Reader); var lastModified = TableValueToDateTime((int)Columns.LastModified, ref read.Reader); write.Add(read.Reader.Read((int)Columns.ChangeVector, out int size), size); write.Add(read.Reader.Read((int)Columns.LowerId, out size), size); write.Add(read.Reader.Read((int)Columns.RecordSeparator, out size), size); write.Add(read.Reader.Read((int)Columns.Etag, out size), size); write.Add(read.Reader.Read((int)Columns.Id, out size), size); write.Add(read.Reader.Read((int)Columns.Document, out size), size); write.Add((int)flags); write.Add(read.Reader.Read((int)Columns.DeletedEtag, out size), size); write.Add(lastModified.Ticks); write.Add(read.Reader.Read((int)Columns.TransactionMarker, out size), size); if ((flags & DocumentFlags.Resolved) == DocumentFlags.Resolved) { write.Add((int)DocumentFlags.Resolved); } else { write.Add(0); } write.Add(Bits.SwapBytes(lastModified.Ticks)); writeTable.Set(write, true); } } } } return(true); }
public UpdateWriter(UpdateStep step, string identifierDelemiterStart, string identifierDelemiterEnd, string stringDelemiter, string namedParameterPrefix) { IdentifierDelemiterStart = identifierDelemiterStart; IdentifierDelemiterEnd = identifierDelemiterEnd; StringDelemiter = stringDelemiter; NamedParameterPrefix = namedParameterPrefix; _sbSet.Append("UPDATE ") .Append(step.DestinationRow.Database) .Append(".") .Append(step.DestinationRow.Table) .Append(" SET "); }
IEnumerator OnDownloadlevelIndexFile() { LogModule.DebugLog("ger version form " + m_resServerUrl + "/" + ResLevelIndexFileName); WWW wwwResLevelFile = null; yield return(StartCoroutine(DownloadHelper.GetCDNWWW(m_resServerUrl + "/" + ResLevelIndexFileName, value => wwwResLevelFile = value))); if (!string.IsNullOrEmpty(wwwResLevelFile.error)) { LogModule.ErrorLog(wwwResLevelFile.error); UpdateFinish(UpdateResult.GetVersionFail); yield break; } m_remoteResLevelIndex = wwwResLevelFile.text; // check level string[] strLevels = m_remoteResLevelIndex.Split(','); if (strLevels.Length > 0) { int curLevel = 0; LogModule.DebugLog("level index string:" + m_remoteResLevelIndex); for (int i = 0; i < strLevels.Length; i++) { if (int.TryParse(strLevels[i], out curLevel)) { LogModule.DebugLog("level index:" + curLevel.ToString()); if (m_localResLevel < curLevel && m_playerNeedResLevel >= curLevel) { // need update LogModule.DebugLog("remote verion level is big than local, begin update"); m_curUpdateStep = UpdateStep.GetFileList; // 下载文件列表 m_versionFileDownloader = DownloadHelper.StartDownload(this, m_resServerUrl + "/" + ResFileListName, true, CacheVersionPath + "/" + ResFileListName, OnDownloadRemoteResFileList); yield break; } } else { LogModule.ErrorLog("parse level index file error " + strLevels[i]); } } } UpdateFinish(UpdateResult.Success); }
void updateHelper_UpdateStepMismatch(object sender, Response respType, UpdateStep previousStep) { // we can't install right now if (previousStep == UpdateStep.RestartInfo) { if (ClosingAborted != null) ClosingAborted(this, EventArgs.Empty); } if (respType == Response.Progress) { switch (updateHelper.UpdateStep) { case UpdateStep.CheckForUpdate: UpdateStepOn = UpdateStepOn.Checking; break; case UpdateStep.DownloadUpdate: UpdateStepOn = UpdateStepOn.DownloadingUpdate; break; case UpdateStep.BeginExtraction: UpdateStepOn = UpdateStepOn.ExtractingUpdate; break; } } if (UpdateStepMismatch != null) UpdateStepMismatch(this, EventArgs.Empty); }
public void SendFailed(string messageTitle, string messageBody, UpdateStep step) { pipeServer.SendMessage(new UpdateHelperData(Response.Failed, step, messageTitle, messageBody).GetByteArray()); }
public void SendProgress(int progress, UpdateStep step) { pipeServer.SendMessage(new UpdateHelperData(Response.Progress, step, progress).GetByteArray()); }
public void SendSuccess(UpdateStep step) { pipeServer.SendMessage(new UpdateHelperData(Response.Succeeded, step).GetByteArray()); }
public UpdateHelperData(UpdateStep step, string extraData) : this(step) { ExtraData.Add(extraData); ExtraDataIsRTF.Add(false); }
/// <summary> /// load file: GeoData - LastModified.txt /// if available then /// try to HTTP head the data source <see cref="http://download.geonames.org/export/dump/allCountries.zip"/> /// pull off last - modified header /// if newer than the file last-modified, do a GET to download /// else do a get to download /// </summary> internal Task Update(UpdateStep steps) { if (steps == UpdateStep.None) throw new InvalidOperationException("steps == UpdateStep.None"); return Task.Factory.StartNew(() => { lock (_lock) { var fs = new GeoFileSet(Root) { AllCountriesFile = Path.Combine(Root, DATA_FILE + ".zip"), CountryInfoFile = Path.Combine(Root, "countryInfo.txt"), FeatureCodes_EnFile = Path.Combine(Root, "featureCodes_en.txt"), TimeZonesFile = Path.Combine(Root, "timeZones.txt"), AllCountriesPostal = Path.Combine(Root, POSTAL_CODE + ".zip"), }; string lastModifiedFile = Path.Combine(Root, LAST_MODIFIED_FILE); string tmpFile = Path.Combine(Root, Guid.NewGuid().ToString()); bool canReadWrite = steps.HasFlag(UpdateStep.WriteCheck) ? CanWriteTest(tmpFile) : true; bool shouldDownload = steps.HasFlag(UpdateStep.UpdateCheck) ? ShouldDownloadCheck(canReadWrite, lastModifiedFile) : true; if (canReadWrite && shouldDownload) { var downloadTasks = new List<Task>(); if (steps.HasFlag(UpdateStep.Download)) { downloadTasks.Add(DownloadFile(COUNTRY_INFO_URL, fs.CountryInfoFile)); downloadTasks.Add(DownloadFile(FEATURE_CODES_EN_URL, fs.FeatureCodes_EnFile)); downloadTasks.Add(DownloadFile(TIME_ZONE_URL, fs.TimeZonesFile)); downloadTasks.Add(DownloadFile(POSTAL_CODE_URL, fs.AllCountriesPostal)); downloadTasks.Add(DownloadFile(ALL_COUNTRIES_URL, fs.AllCountriesFile, c => { try { if (steps.HasFlag(UpdateStep.ChangeModifiedDate)) { var headers = c.ResponseHeaders; foreach (string h in headers.Keys) { if (h.ToLowerInvariant() == "last-modified") { var header = headers[h]; DateTime headerDate = DateTime.Now; DateTime.TryParse(header.ToString(), out headerDate); File.WriteAllText(lastModifiedFile, headerDate.ToString()); break; } } } } catch (Exception dex) { string s = string.Format("DownloadFile: CallBack => {0}", new FileInfo(fs.AllCountriesFile).Name); _logger.Error(s, dex); } })); Task.WaitAll(downloadTasks.ToArray()); } if (steps.HasFlag(UpdateStep.Extraction)) { if (ConvertZipToDat(fs)) { if (steps.HasFlag(UpdateStep.Cleanup)) FileCleanup(fs); else _logger.Warn("Update: No Cleanup flags"); } else _logger.Warn("Update: Dat conversion failed"); } else _logger.Warn("Update: No Extraction flags"); } else _logger.WarnFormat("Update: Not running: canReadWrite=={0} && shouldDownload=={1}", canReadWrite, shouldDownload); } }); }
public UpdateHelperData(Response responseType, UpdateStep step) : this(step) { ResponseType = responseType; }
public UpdateHelperData(UpdateStep step) { Action = UpdateAction.UpdateStep; UpdateStep = step; }
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { bw.DoWork -= bw_DoWork; bw.RunWorkerCompleted -= bw_RunWorkerCompleted; bw.Dispose(); bw = null; // error occurs when a message fails to send or wyUpdate fails to start if (e.Error != null) { // if the process is running - try to kill it try { if (ClientProcess != null && !ClientProcess.HasExited) ClientProcess.Kill(); } catch { } // set the client process to null so it can be restarted // when the user retries. ClientProcess = null; // clear the to-send stack sendBuffer.Clear(); // inform the AutomaticUpdater that wyUpdate is no longer running if (PipeServerDisconnected != null) PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, e.Error.Message)); } else { // process the next in stack if (sendBuffer.Count > 0) { RecreateBackgroundWorker(); UpdateHelperData uhd = sendBuffer.Pop(); UpdateStep = uhd.UpdateStep; // begin sending to the client bw.RunWorkerAsync(uhd); } } }
/* void StartNewSelfAndClose() { bool checkForClients = false; // when this function is called in the constructor // (i.e. before the handle for the form is created) // then the pipeserver will not have yet been created if (!updateHelper.RunningServer) { checkForClients = true; updateHelper.StartPipeServer(this); } Process clientProcess = new Process { StartInfo = { FileName = newSelfLocation, //NOTE: (Very goddamn important - change this and die) // Arguments must have the "clear space" before the closing quote after // baseDirectory. "Why?" you ask, because Windows is the offspring // of a Unicorn and an Angel. Everyone knows that Angels don't // respect backslash-quote combos. // And Unicorns are racists. // The non-absurd reason is that if you have a baseDirectory variable with // a trailing slash then a quote character adjacent to this slash (i.e. // with no space between the slash and quote) the commandline args // get fubar-ed. A base directory with a trailing slash is valid // input, thus the slash-space-quote combo must remain. // start the client in automatic update mode (a.k.a. wait mode) Arguments = "-cdata:\"" + clientFileLoc + "\" -basedir:\"" + baseDirectory + " \" /autoupdate /ns", WindowStyle = ProcessWindowStyle.Hidden } }; clientProcess.Start(); if (checkForClients) { // there must be at least one client running to receive this message int timeSpent = 0; while (updateHelper.TotalConnectedClients == 0) { // if we've already waited 30 seconds, we've wait long enough // something has gone wrong with the AutomaticUpdater control // no point in waiting around any longer. if (timeSpent == 30000) break; // wait 1/3 of a second timeSpent += 300; Thread.Sleep(300); } } // tell all the clients that there's a new wyUpdate updateHelper.SendNewWyUpdate(UpdateHelperData.PipenameFromFilename(newSelfLocation), clientProcess.Id); CancelUpdate(true); } * */ void UpdateHelper_RequestReceived(object sender, UpdateAction a, UpdateStep s) { if (a == UpdateAction.Cancel) { CancelUpdate(true); return; } // filter out-of-order requests (never assume the step 's' is coming in the correct order) if (FilterBadRequest(s)) return; // set the current update step (ForceCheck == Check) autoUpdateStepProcessing = s == UpdateStep.ForceRecheckForUpdate ? UpdateStep.CheckForUpdate : s; switch (s) { case UpdateStep.ForceRecheckForUpdate: //TODO: perhaps delete old crufty files // show the checking frame regardless of the current step panelDisplaying.ClearText(); ShowFrame(Frame.Checking); CheckForUpdate(); break; case UpdateStep.CheckForUpdate: CheckForUpdate(); break; case UpdateStep.DownloadUpdate: ShowFrame(Frame.InstallUpdates); DownloadUpdate(); break; case UpdateStep.BeginExtraction: update.CurrentlyUpdating = UpdateOn.Extracting; InstallUpdates(update.CurrentlyUpdating); break; case UpdateStep.RestartInfo: // send a success signal (with the Window Handle) updateHelper.SendSuccess(autoUpdateStepProcessing, (int)Handle); break; case UpdateStep.Install: if (!updateHelper.IsAService) { // show self & make topmost Visible = true; TopMost = true; TopMost = false; } if (needElevation) { // save the RestartInfo details (file to launch, where to save the update success details) //SaveAutoUpdateData(UpdateStepOn.UpdateReadyToInstall); StartSelfElevated(); return; } // install the regular update update.CurrentlyUpdating = UpdateOn.ClosingProcesses; InstallUpdates(update.CurrentlyUpdating); break; } }
/// <summary>Filters bad request by responding with the required info.</summary> /// <param name="s">The requested step.</param> /// <returns>True if a bad request has been filtered, false otherwise</returns> bool FilterBadRequest(UpdateStep s) { switch (s) { case UpdateStep.ForceRecheckForUpdate: // if already checking ... if (frameOn == Frame.Checking && downloader != null) { // report progress of 0% updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); return true; } // ignore request when a download / extraction is pending if (frameOn != Frame.Checking && frameOn != Frame.UpdateInfo) return true; break; case UpdateStep.CheckForUpdate: // if already checking ... if (frameOn == Frame.Checking && downloader != null) { // report progress of 0% updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); return true; } // if on another step ... if (frameOn != Frame.Checking) { // report UpdateAvailable, with changes updateHelper.SendSuccess(ServerFile.NewVersion, panelDisplaying.GetChanges(true), true); return true; } break; case UpdateStep.DownloadUpdate: if (frameOn == Frame.Checking) { // waiting to be told to check for updates... if (downloader == null) { autoUpdateStepProcessing = UpdateStep.CheckForUpdate; // report 0% and begin checking updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); CheckForUpdate(); } else // already checking ... { // report 0% progress updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); } return true; } if (frameOn == Frame.InstallUpdates) { // if already downloading ... if (IsInDownloadState()) { // report 0% updateHelper.SendProgress(0, UpdateStep.DownloadUpdate); } else // on another step (extracting, etc.) ... { // report UpdateDownloaded updateHelper.SendSuccess(UpdateStep.DownloadUpdate); } return true; } break; case UpdateStep.BeginExtraction: if (frameOn == Frame.Checking) { // waiting to be told to check for updates... if (downloader == null) { autoUpdateStepProcessing = UpdateStep.CheckForUpdate; // report 0% and begin checking updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); CheckForUpdate(); } else // already checking ... { // report 0% progress updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); } return true; } // if we haven't downloaded yet... if (frameOn == Frame.UpdateInfo) { ShowFrame(Frame.InstallUpdates); autoUpdateStepProcessing = UpdateStep.DownloadUpdate; // report 0% progress & download updateHelper.SendProgress(0, UpdateStep.DownloadUpdate); DownloadUpdate(); return true; } if (frameOn == Frame.InstallUpdates) { // if already downloading ... if (IsInDownloadState()) { // report 0% updateHelper.SendProgress(0, UpdateStep.DownloadUpdate); return true; } // if done extracting... if (updtDetails != null) { // report extraction completed successfully updateHelper.SendSuccess(UpdateStep.BeginExtraction); return true; } if (currentlyExtracting) { // report extraction has begun updateHelper.SendProgress(0, UpdateStep.BeginExtraction); return true; } } break; case UpdateStep.RestartInfo: case UpdateStep.Install: if (frameOn == Frame.Checking) { // waiting to be told to check for updates... if (downloader == null) { autoUpdateStepProcessing = UpdateStep.CheckForUpdate; // report 0% and begin checking updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); CheckForUpdate(); } else // already checking ... { // report 0% progress updateHelper.SendProgress(0, UpdateStep.CheckForUpdate); } return true; } // if we haven't downloaded yet... if (frameOn == Frame.UpdateInfo) { ShowFrame(Frame.InstallUpdates); autoUpdateStepProcessing = UpdateStep.DownloadUpdate; // report 0% progress & download updateHelper.SendProgress(0, UpdateStep.DownloadUpdate); DownloadUpdate(); return true; } if (frameOn == Frame.InstallUpdates) { // if already downloading ... if (IsInDownloadState()) { // report 0% updateHelper.SendProgress(0, UpdateStep.DownloadUpdate); return true; } if (currentlyExtracting) { // report extraction has begun updateHelper.SendProgress(0, UpdateStep.BeginExtraction); return true; } } break; } // no bad request found - continue processing as usual return false; }
void StartNextStep(UpdateStep updateStepOn) { // begin the next step switch (updateStepOn) { case UpdateStep.CheckForUpdate: if (!string.IsNullOrEmpty(version)) { // there's an update available if (internalUpdateType == UpdateType.CheckAndDownload || internalUpdateType == UpdateType.Automatic) { UpdateStepOn = UpdateStepOn.UpdateAvailable; // begin downloading the update DownloadUpdate(); } else { // show the update ready mark UpdateReady(); } } else //no update { // tell the user they're using the latest version AlreadyUpToDate(); } break; case UpdateStep.DownloadUpdate: // begin extraction if (internalUpdateType == UpdateType.Automatic) ExtractUpdate(); else UpdateReadyToExtract(); break; case UpdateStep.BeginExtraction: // inform the user that the update is ready to be installed UpdateReadyToInstall(); break; } }
public void SendSuccess(UpdateStep step, int windowHandle) { pipeServer.SendMessage(new UpdateHelperData(Response.Succeeded, step) { ProcessID = windowHandle }.GetByteArray()); }
static UpdateStepOn UpdateStepToUpdateStepOn(UpdateStep us) { switch(us) { case UpdateStep.BeginExtraction: return UpdateStepOn.ExtractingUpdate; case UpdateStep.CheckForUpdate: return UpdateStepOn.Checking; case UpdateStep.DownloadUpdate: return UpdateStepOn.DownloadingUpdate; default: throw new Exception("UpdateStep not supported"); } }
public UpdateHelperData(Response responseType, UpdateStep step, int progress) : this(responseType, step) { Progress = progress; }
void SendAsync(UpdateHelperData uhd) { // if currently working, add the new message to the stack if (bw != null) { sendBuffer.Push(uhd); } else { RecreateBackgroundWorker(); // process immediately UpdateStep = uhd.UpdateStep == UpdateStep.ForceRecheckForUpdate ? UpdateStep.CheckForUpdate : uhd.UpdateStep; // begin sending to the client bw.RunWorkerAsync(uhd); } }
void ProcessReceivedMessage(UpdateHelperData data) { if (data.Action == UpdateAction.GetwyUpdateProcessID) { ClientProcess = Process.GetProcessById(data.ProcessID); return; } if (data.Action == UpdateAction.NewWyUpdateProcess) { // disconnect from the existing pipeclient pipeClient.Disconnect(); CreateNewPipeClient(); try { ClientProcess = Process.GetProcessById(data.ProcessID); } catch (Exception) { // inform the AutomaticUpdater that wyUpdate is no longer running if (PipeServerDisconnected != null) PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, "Failed to connect to the new version of wyUpdate.exe")); } TryToConnectToPipe(data.ExtraData[0]); // if the process is running - try to kill it if (!pipeClient.Connected) { // inform the AutomaticUpdater that wyUpdate is no longer running if (PipeServerDisconnected != null) PipeServerDisconnected(this, new UpdateHelperData(Response.Failed, UpdateStep, AUTranslation.C_PrematureExitTitle, "Failed to connect to the new version of wyUpdate.exe")); } // begin where we left off // if update step == RestartInfo, we need to send the restart info as well if (ResendRestartInfo != null && UpdateStep == UpdateStep.RestartInfo) ResendRestartInfo(this, EventArgs.Empty); else SendAsync(new UpdateHelperData(UpdateStep)); return; } if (data.UpdateStep != UpdateStep) { // this occurs when wyUpdate is on a separate step from the AutoUpdater UpdateStep prev = UpdateStep; // set new update step UpdateStep = data.UpdateStep; // tell AutoUpdater that the message we sent didn't respond in kind // e.g. we sent RestartInfo, and wyUpdate responded with DownloadUpdate // meaning we can't update yet, we're just begginning downloading the update if (UpdateStepMismatch != null) UpdateStepMismatch(this, data.ResponseType, prev); } // wyUpdate will give us its main Window Handle so we can pass focus to it if (data.Action == UpdateAction.UpdateStep && data.UpdateStep == UpdateStep.RestartInfo) ClientWindowHandleToShow = data.ProcessID; if (data.ResponseType != Response.Nothing && ProgressChanged != null) ProgressChanged(this, data); }