/// <summary> /// Generic add function. /// Technically 'mb' is not necessary as it can be retrieved by calling 'func.Target as MonoBehaviour'. /// Unfortunately Flash export fails to compile with that, claiming the following: /// "Error: Access of possibly undefined property Target through a reference with static type Function." /// </summary> void Add(MonoBehaviour mb, int updateOrder, OnUpdate func, List <UpdateEntry> list) { #if !UNITY_FLASH // Flash export fails at life. foreach (UpdateEntry ent in list) { if (ent.func == func) { return; } } #endif UpdateEntry item = new UpdateEntry(); item.index = updateOrder; item.func = func; item.mb = mb; item.isMonoBehaviour = (mb != null); list.Add(item); if (updateOrder != 0) { list.Sort(Compare); } }
public static void Update(string ip, UpdateEntry update) { Entry entry = null; if (entries.TryGetValue(ip, out entry)) { if (update == UpdateEntry.SolvedJob) { entry.SolvedJobs++; } else if (update == UpdateEntry.AuthFailure) { entry.AuthFailure++; } else if (update == UpdateEntry.AuthSuccess) { entry.AuthSuccess++; } else if (update == UpdateEntry.WrongHash) { entry.WrongHash++; } else if (update == UpdateEntry.Handshake) { entry.Handshake++; } } else { entries.TryAdd(ip, new Entry(ip)); } }
private object convertObject(object value, UpdateEntry ue) { switch (ue.type) { case EntryType.STRING: break; case EntryType.INTEGER: value = int.Parse((string)value); break; case EntryType.DATE: value = DateTime.Parse((string)value); break; case EntryType.BOOLEAN: value = bool.Parse((string)value); break; case EntryType.FLOAT: value = float.Parse((string)value); break; default: throw new Exception("Invalid entry type"); } return(value); }
private void Add(MonoBehaviour mb, int updateOrder, OnUpdate func, List <UpdateEntry> list) { var num = 0; var count = list.Count; while (num < count) { var entry = list[num]; if (entry.func == func) { return; } num++; } var item = new UpdateEntry { index = updateOrder, func = func, mb = mb, isMonoBehaviour = mb != null }; list.Add(item); if (updateOrder != 0) { list.Sort(Compare); } }
public override Stream GetOutputStream(string name, out IContentEntry entry) { ThrowIfObjectDisposed(); ThrowIfObjectNotUpdating(); name = NormalizePath(name); IContentEntry oldEntry; if (entries.TryGetValue(name, out oldEntry)) { if (oldEntry is IDisposable) { (oldEntry as IDisposable).Dispose(); } var source = new MemoryStream(); var updateEntry = new UpdateEntry(name, source, DateTime.Now, true, EntryOperation.AddOrUpdate); entries[name] = updateEntry; entry = updateEntry; return(updateEntry.Source.GetOutputStream()); } else { var source = new MemoryStream(); var updateEntry = new UpdateEntry(name, source, DateTime.Now, true, EntryOperation.AddOrUpdate); entry = updateEntry; entries.Add(name, updateEntry); return(updateEntry.Source.GetOutputStream()); } }
public DBUpdate(string entityType, string[] dimensionNames) { m_EntityType = entityType; m_Filter.Set(m_G_Entity); m_Filter.Set(m_G_Shard); m_Filter.Set(m_DateTime); m_Doc.Set(m_G_Entity); m_Doc.Set(m_G_Shard); m_Doc.Set(m_DateTime); foreach (var dimensionName in dimensionNames) { var element = new BSONStringElement(dimensionName, ""); var kvp = new KeyValuePair <string, BSONStringElement>(dimensionName, element); m_Dimensions.Add(kvp); m_Doc.Set(element); m_Filter.Set(element); } m_Inc.Set(m_Value); m_Inc.Set(m_Count); m_IncDoc.Set(new BSONDocumentElement("$setOnInsert", m_Doc)); m_IncDoc.Set(new BSONDocumentElement("$inc", m_Inc)); m_MongoUpdateEntry = new UpdateEntry(m_Filter, m_IncDoc, false, true); }
/// <summary> /// Creates a <see cref="UpdateEntry"/> from the contents of a <see cref="ZipArchive"/> /// </summary> /// <param name="zip"><see cref="ZipArchive"/> to grab data from</param> public static async Task <UpdateEntry?> CreateUpdateEntry(this ZipArchive zip) { var updateEntry = new UpdateEntry(); await updateEntry.LoadAsyncEnumerable(GetFilesFromPackage(zip)); return(updateEntry); }
/// <summary> /// Generic add function. /// Technically 'mb' is not necessary as it can be retrieved by calling 'func.Target as MonoBehaviour'. /// Unfortunately Flash export fails to compile with that, claiming the following: /// "Error: Access of possibly undefined property Target through a reference with static type Function." /// </summary> void Add(MonoBehaviour mb, int updateOrder, OnUpdate func, List <UpdateEntry> list) { #if !UNITY_FLASH // Flash export fails at life. for (int i = 0, imax = list.Count; i < imax; ++i) { UpdateEntry ent = list[i]; if (ent.func == func) { ent.index = updateOrder; ent.func = func; ent.mb = mb; ent.isMonoBehaviour = (mb != null); return; } } #endif UpdateEntry item = new UpdateEntry(); item.index = updateOrder; item.func = func; item.mb = mb; item.isMonoBehaviour = (mb != null); list.Add(item); if (updateOrder != 0) { list.Sort(Compare); } }
public async Task <IActionResult> OnPostUpdateEntry(UpdateEntry model, UpdateAction action) { if (action == UpdateAction.Del) { _logger.LogInformation("Removing single: {entryId}", model.EntryId); await _repo.Delete(model.EntryId); await _plRepo.Delete(model.EntryId); TempData["msg"] += $"Entry {model.EntryId} deleted!"; } else { _logger.LogInformation("Updating single: {entryId}", model.EntryId); await _repo.Insert(new VerifiedEntry( model.EntryId, model.FullName, model.EntryTeamName, model.VerifiedEntryType, model.Alias, model.Description)); TempData["msg"] += $"Entry {model.EntryId} updated!"; } await _mediator.Publish(new IndexEntry(model.EntryId)); return(RedirectToPage("Verified")); }
/// <summary> /// Update the specified list. /// </summary> void UpdateList(List <UpdateEntry> list, float delta) { for (int i = list.Count; i > 0;) { UpdateEntry ent = list[--i]; // If it's a monobehaviour we need to do additional checks if (ent.isMonoBehaviour) { // If the monobehaviour is null, remove this entry if (ent.mb == null) { list.RemoveAt(i); continue; } } // Call the function try { ent.func(delta); } catch (Exception e) { Debug.LogException(e); } } }
public override IContentEntry AddOrUpdate(string name, Stream source, DateTime lastWriteTime, bool isCloseStream = true) { ThrowIfObjectDisposed(); ThrowIfObjectNotUpdating(); name = NormalizePath(name); IContentEntry oldEntry; if (entries.TryGetValue(name, out oldEntry)) { if (oldEntry is IDisposable) { (oldEntry as IDisposable).Dispose(); } var updateEntry = new UpdateEntry(name, source, lastWriteTime, isCloseStream, EntryOperation.AddOrUpdate); entries[name] = updateEntry; return(updateEntry); } else { var updateEntry = new UpdateEntry(name, source, lastWriteTime, isCloseStream, EntryOperation.AddOrUpdate); entries.Add(name, updateEntry); return(updateEntry); } }
private void Add(MonoBehaviour mb, int updateOrder, OnUpdate func, List <UpdateEntry> list) { int num = 0; int count = list.Count; while (num < count) { UpdateEntry entry = list[num]; if (entry.func == func) { return; } num++; } UpdateEntry item = new UpdateEntry { index = updateOrder, func = func, mb = mb, isMonoBehaviour = mb != null }; list.Add(item); if (updateOrder != 0) { list.Sort(new Comparison <UpdateEntry>(UpdateManager.Compare)); } }
/// <summary> /// Update the specified list. /// </summary> void UpdateList(List <UpdateEntry> list, float delta) { for (int i = list.Count; i > 0;) { UpdateEntry ent = list[--i]; // If it's a monobehaviour we need to do additional checks if (ent.isMonoBehaviour) { // If the monobehaviour is null, remove this entry if (ent.mb == null) { list.RemoveAt(i); continue; } // If the monobehaviour or its game object are disabled, move on to the next entry if (!ent.mb.enabled || !NGUITools.GetActive(ent.mb.gameObject)) { continue; } } // Call the function ent.func(delta); } }
SET "; //({1}) = {2} public static List <string> GetUpdateScripts( string cubeName, string updeteScript, List <UpdateEntry> entries) { string commandText = string.Empty; if (string.IsNullOrEmpty(updeteScript)) { commandText = string.Format(UPDATE_COMMAND_TEMPLATE, cubeName); } List <string> commands = new List <string>(); for (int i = 0; i < entries.Count; i++) { UpdateEntry entry = entries[i]; StringBuilder sb = new StringBuilder(); foreach (ShortMemberInfo mi in entry.Tuple) { if (sb.Length > 0) { sb.Append(','); } sb.Append(mi.UniqueName); } string tuple = sb.ToString(); sb = null; string lexeme = Environment.NewLine; if (i > 0) { if (string.IsNullOrEmpty(updeteScript)) { lexeme += ','; } } if (string.IsNullOrEmpty(updeteScript)) { lexeme += string.Format("({0}) = {1}", tuple, entry.NewValue); commandText += lexeme; } else { string cmd = updeteScript; ParseHierarchies(ref cmd, entry.Tuple, entry.NewValue, entry.OldValue); lexeme += cmd; commands.Add(lexeme); } } if (string.IsNullOrEmpty(updeteScript)) { commands.Add(commandText); } return(commands); }
public void RemoveChange(CellInfo cell) { if (cell != null) { UpdateEntry entry = new UpdateEntry(cell); RemoveChange(entry); } }
public void RemoveChange(UpdateEntry args) { UpdateEntry change = FindChange(args); if (change != null) { CellChanges.Remove(change); } }
/// <summary> /// Ищет в кэше изменений ячейку /// </summary> /// <param name="args"></param> /// <returns></returns> public UpdateEntry FindChange(CellInfo cell) { if (cell != null) { UpdateEntry entry = new UpdateEntry(cell); return(FindChange(entry)); } return(null); }
/// <summary> /// Ищет в кэше изменений ячейку /// </summary> /// <param name="args"></param> /// <returns></returns> public UpdateEntry FindChange(UpdateEntry args) { foreach (UpdateEntry arg in CellChanges) { if (CompareTuples(arg.Tuple, args.Tuple)) { return(arg); } } return(null); }
private void EnsureUpdateEntry() { if (this.updateEntry == null) { this.updateEntry = liteRepository.SingleOrDefault <UpdateEntry>(x => x.Id == 1, "Update"); if (this.updateEntry == null) { this.updateEntry = new UpdateEntry(); liteRepository.Insert(this.updateEntry, "Update"); } } }
private static int Compare(UpdateEntry a, UpdateEntry b) { if (a.index < b.index) { return(1); } if (a.index > b.index) { return(-1); } return(0); }
/// <summary> /// Update entity. /// </summary> /// <param name="client">SugarRestClient object.</param> /// <param name="request">The request object.</param> /// <param name="modelInfo">The entity model info.</param> /// <returns>SugarRestResponse object.</returns> public static SugarRestResponse ExecuteUpdate(this SugarRestClient client, SugarRestRequest request, ModelInfo modelInfo) { var sugarRestResponse = new SugarRestResponse(); var loginResponse = new LoginResponse(); try { var loginRequest = new LoginRequest { Url = request.Url, Username = request.Username, Password = request.Password }; loginResponse = Authentication.Login(loginRequest); JObject jobject = JsonConverterHelper.Serialize(request.Parameter, modelInfo.Type); var selectFields = modelInfo.GetJsonPropertyNames(request.Options.SelectFields); var updateEntryResponse = UpdateEntry.Run(loginResponse.SessionId, loginRequest.Url, request.ModuleName, jobject, selectFields); if (updateEntryResponse != null) { sugarRestResponse.JsonRawRequest = updateEntryResponse.JsonRawRequest; sugarRestResponse.JsonRawResponse = updateEntryResponse.JsonRawResponse; if (!string.IsNullOrEmpty(updateEntryResponse.Id)) { sugarRestResponse.Data = updateEntryResponse.Id; sugarRestResponse.JData = (updateEntryResponse.Id == null) ? null : JToken.FromObject(updateEntryResponse.Id).ToString(); sugarRestResponse.StatusCode = updateEntryResponse.StatusCode; } else { sugarRestResponse.Error = updateEntryResponse.Error; sugarRestResponse.StatusCode = updateEntryResponse.StatusCode; } } return(sugarRestResponse); } catch (Exception exception) { sugarRestResponse.StatusCode = HttpStatusCode.InternalServerError; sugarRestResponse.Error = ErrorResponse.Format(exception, string.Empty); } finally { Authentication.Logout(request.Url, loginResponse.SessionId); } return(sugarRestResponse); }
static void Main(string[] args) { var u = UpdateFile.Create(@"c:\temp\test.app"); var e = UpdateEntry.Create(); u.Add(e, @"c:\temp\v1.14.zip"); var crc = UpdateEntry.Create(); u.AddChecksum(crc); u = UpdateFile.Open(@"c:\temp\test.app"); u.Remove(0); u = UpdateFile.Open(@"c:\temp\test.app"); }
void Del(OnUpdate func, List <UpdateEntry> list) { for (int i = list.Count - 1; i >= 0; --i) { UpdateEntry ent = list[i]; if (ent.func == func) { ent.isMonoBehaviour = true; ent.mb = null; break; } } }
private void patchForwardBranches() { // now patch forward branches //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" for (System.Collections.IEnumerator i = updates.GetEnumerator(); i.MoveNext();) { //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" UpdateEntry entry = (UpdateEntry)i.Current; switch (entry.source.code) { case flash.swf.ActionConstants_Fields.sactionIf: case flash.swf.ActionConstants_Fields.sactionJump: int target = getLabelOffset(((Branch)entry.source).target); writer.writeSI16at(entry.updatePos, target - entry.anchor); break; case flash.swf.ActionConstants_Fields.sactionWith: int endWith = getLabelOffset(((With)entry.source).endWith); writer.writeUI16at(entry.updatePos, endWith - entry.anchor); break; case flash.swf.ActionConstants_Fields.sactionWaitForFrame: case flash.swf.ActionConstants_Fields.sactionWaitForFrame2: int skipTarget = getLabelCount(((WaitForFrame)entry.source).skipTarget); writer.writeUI8at(entry.updatePos, skipTarget - entry.anchor); break; case flash.swf.ActionConstants_Fields.sactionTry: Try t = (Try)entry.source; int endTry = getLabelOffset(t.endTry); writer.writeUI16at(entry.updatePos, endTry - entry.anchor); entry.anchor = endTry; if (t.hasCatch()) { int endCatch = getLabelOffset(t.endCatch); writer.writeUI16at(entry.updatePos + 2, endCatch - entry.anchor); entry.anchor = endCatch; } if (t.hasFinally()) { int endFinally = getLabelOffset(t.endFinally); writer.writeUI16at(entry.updatePos + 4, endFinally - entry.anchor); } break; default: Debug.Assert(false, "invalid action in UpdateEntry"); break; } } }
public GroupProp(ActorParts.MuscleGroup muscleGroup, UpdateEntry v) { curProp = new PropsBase(0, 0, 0, 0, 0); buffProp = new VisibleProp(this, 0, 0, 0, 0, 0); equipProp = new VisibleProp(this, 0, 0, 0, 0, 0); //print(muscleBasePropsGroup.props.knockOutDistance); stateProp = new UnVisibleProp(this, 1, 1, 1, 1, 0.1f); this.muscleGroup = muscleGroup; Muscle m = muscleGroup.muscles[0]; name = muscleGroup.groupName; this.updateEntry = v; }
public UpdateResult DoUpdate(UpdateInstruction UpdateInstruction) { string AnalyticsMessageResult = ""; var updateResultReturn = new UpdateResult() { ID = UpdateInstruction.ID, IsSuccess = false, //Message = "No update found. Nothing to update!", UpdateInstructionID = UpdateInstruction.ID }; try { UpdateEntry updateEntry = this.HasUpdate(UpdateInstruction); JobStatus JobStatus = _JobService.GetQueuePosition(new JobStatus() { ID = UpdateInstruction.ID }); if (updateEntry.HasUpdate) { updateResultReturn = ExecuteUpdate(updateEntry); AnalyticsMessageResult = !updateResultReturn.IsSuccess ? $"Job '{JobStatus.QueuePosition}' failed to update '{updateEntry.ProductName}' from '{updateEntry.CurrentVersion}' to '{updateEntry.CurrentVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}.\r\nSee details:\r\n\r\n{ JsonConvert.SerializeObject(updateResultReturn.Messages, Formatting.Indented)}" : AnalyticsMessageResult = $"Job '{JobStatus.QueuePosition}' updated '{updateEntry.ProductName}' from '{updateEntry.CurrentVersion}' to '{updateEntry.NewVersion}'. Alepsed time is: {this.ConvertMillisecondsToTimeString(updateResultReturn.TimeSpentMilliseconds)}."; } else { AnalyticsMessageResult = $"Job '{JobStatus.QueuePosition}' did not found update for '{updateEntry.ProductName}' with version '{updateEntry.CurrentVersion}'. You have the latest version avaliable."; updateResultReturn.AddMessage(AnalyticsMessageResult, UpdateResultMessage.eMessageType.INFORMATION); } } catch (Exception ex) { throw ex; } finally { _JobService.CreateUpdateJobStatus(new JobStatus() { ID = UpdateInstruction.ID, CurrentStatus = JobStatusTyes.Completed }); } this._UpdateRepository.WriteUpdateInstructionResult(updateResultReturn); this.SendAnalyticsData("UpdateService.DoUpdate.Results", AnalyticsMessageResult); return(updateResultReturn); }
private bool MatchesConditions(UpdateEntry entry, Dictionary <string, string> systemInfos) { foreach (var attribute in entry) { if (systemInfos.ContainsKey(attribute.Key)) { var valueMatches = attribute.Value.ToString() != systemInfos[attribute.Key]; if (valueMatches) { return(false); } } } return(true); // None of the conditions did not match the entry }
/// <summary> /// IComparable.CompareTo implementation. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance is less than obj. Zero This instance is equal to obj. Greater than zero This instance is greater than obj. /// </returns> /// <exception cref="T:System.ArgumentException">obj is not the same type as this instance. </exception> public int CompareTo(object obj) { if (obj is UpdateEntry) { UpdateEntry upd = ( UpdateEntry )obj; if (VersionNumber.CompareTo(upd.VersionNumber) == 0) //Version numbers are equal { return(Version.CompareTo(upd.Version)); } else { return(VersionNumber.CompareTo(upd.VersionNumber)); } } throw new ArgumentException("object is not a UpdateEntry"); }
/// <summary> /// Generate Update Command from give object /// </summary> /// <param name="tableName"></param> /// <param name="input"></param> /// <param name="keyGetter"></param> /// <returns></returns> public static SqlCommand GenerateUpdateCommand(UpdateEntry entry) { SqlCommand cmd = new SqlCommand(); var command = new StringBuilder(); command.AppendLine("UPDATE " + entry.TableName + " SET"); foreach (var k in entry.Data.Properties()) { if (k.Name.StartsWith("$") || k.Name == entry.KeyName) { continue; } command.AppendLine(k.Name + " = @" + k.Name + ","); } command.Remove(command.Length - 3, 3); command.AppendLine("\r\nWHERE " + entry.KeyName + " = @IDParameter"); cmd.CommandText = command.ToString(); foreach (var k in entry.Data.Properties()) { if (k.Name.StartsWith("$") || k.Name == entry.KeyName) { continue; } var value = entry.Data[k.Name].ToObject(SQLDatabaseAccess.GetTypeFromJTokenType(entry.Data[k.Name].Type)); if (value != null) { cmd.Parameters.AddWithValue("@" + k.Name, value); } else { cmd.Parameters.AddWithValue("@" + k.Name, DBNull.Value); } } cmd.Parameters.AddWithValue("@IDParameter", entry.Data[entry.KeyName].ToObject( SQLDatabaseAccess.GetTypeFromJTokenType(entry.Data[entry.KeyName].Type))); return(cmd); }
/// <summary> /// Generate Update Command from give object /// </summary> /// <param name="tableName"></param> /// <param name="input"></param> /// <param name="keyGetter"></param> /// <returns></returns> public static SqlCommand GenerateUpdateCommand( UpdateEntry entry) { SqlCommand cmd = new SqlCommand(); var command = new StringBuilder(); command.AppendLine("UPDATE " + entry.TableName + " SET"); foreach (var k in entry.Data.Properties()) { if (k.Name.StartsWith("$") || k.Name == entry.KeyName) { continue; } command.AppendLine(k.Name + " = @" + k.Name + ","); } command.Remove(command.Length - 3, 3); command.AppendLine("\r\nWHERE " + entry.KeyName + " = @IDParameter"); cmd.CommandText = command.ToString(); foreach (var k in entry.Data.Properties()) { if (k.Name.StartsWith("$") || k.Name == entry.KeyName) { continue; } var value = entry.Data[k.Name].ToObject(SQLDatabaseAccess.GetTypeFromJTokenType(entry.Data[k.Name].Type)); if (value != null) { cmd.Parameters.AddWithValue("@" + k.Name, value); } else { cmd.Parameters.AddWithValue("@" + k.Name, DBNull.Value); } } cmd.Parameters.AddWithValue("@IDParameter", entry.Data[entry.KeyName].ToObject( SQLDatabaseAccess.GetTypeFromJTokenType(entry.Data[entry.KeyName].Type))); return cmd; }
public override bool Remove(string name) { ThrowIfObjectDisposed(); ThrowIfObjectNotUpdating(); name = NormalizePath(name); IContentEntry entry; if (entries.TryGetValue(name, out entry)) { var updateEntry = entry as UpdateEntry; if (updateEntry != null) { updateEntry.Dispose(); switch (updateEntry.Operation) { case EntryOperation.AddOrUpdate: entries.Remove(name); return(true); case EntryOperation.Remove: return(true); default: throw new IndexOutOfRangeException(updateEntry.Operation.ToString()); } } else { updateEntry = new UpdateEntry(name, EntryOperation.Remove); entries[name] = updateEntry; return(true); } } else { return(false); } }
void CellsControl_PerformControlAction(object sender, ControlActionEventArgs<CellInfo> e) { switch (e.Action) { case ControlActionType.ShowMDX: UpdateEntry entry = new UpdateEntry(e.UserData); try { entry.OldValue = e.UserData.CellDescr.Value.Value.ToString(); } catch { } UpdateEntry change = PivotGrid.LocalChanges.FindChange(e.UserData); if (change != null) { entry.NewValue = change.NewValue; } GetDataSourceInfo(entry); break; case ControlActionType.ShowProperties: ModalDialog dlg = new ModalDialog() {Width = 400, Height = 300, DialogStyle = ModalDialogStyles.OK }; CellPropertiesControl properties = new CellPropertiesControl(); properties.Initialize(e.UserData); dlg.Content = properties; dlg.Caption = Localization.CellPropertiesDialog_Caption; Panel panel = GetRootPanel(this); if (panel != null) { panel.Children.Add(dlg.Dialog.PopUpControl); } // На время убираем контекстное меню сводной таблицы dlg.DialogClosed += new EventHandler<DialogResultArgs>(Dlg_DialogClosed); PivotGrid.UseContextMenu = false; dlg.Show(); break; case ControlActionType.ValueDelivery: ShowValueDeliveryDialog(e.UserData); break; case ControlActionType.ValueCopy: ShowValueCopyDialog(e.UserData); break; case ControlActionType.Copy: CopyCellsToClipboard(e.UserData); break; case ControlActionType.Paste: PasteCellsFromClipboard(e.UserData); break; case ControlActionType.DrillThrough: DrillThroughCell(e.UserData); break; } }
public virtual DataSourceInfoArgs GetDataSourceInfo(UpdateEntry entry) { DataSourceInfoArgs res = new DataSourceInfoArgs(); try { using (MdxDomProvider provider = MdxDomProvider.CreateProvider()) { StringBuilder sb = new StringBuilder(); provider.GenerateMdxFromDom(this.CreateWrappedStatement(), sb, new MdxGeneratorOptions()); String new_Query = sb.ToString(); res.MDXQuery = new_Query; res.MovedAxes_MDXQuery = MoveAxes(new_Query); } } catch (Exception ex) { res.MDXQuery = ex.ToString(); } //res.ConnectionString = Connection.ConnectionID; res.UpdateScript = UpdateScript; return res; }
static int Compare(UpdateEntry a, UpdateEntry b) { if (a.index < b.index) return 1; if (a.index > b.index) return 1; return 0; }
/// <summary> /// Generic add function. /// Technically 'mb' is not necessary as it can be retrieved by calling 'func.Target as MonoBehaviour'. /// Unfortunately Flash export fails to compile with that, claiming the following: /// "Error: Access of possibly undefined property Target through a reference with static type Function." /// </summary> void Add(MonoBehaviour mb, int updateOrder, OnUpdate func, List<UpdateEntry> list) { #if !UNITY_FLASH // Flash export fails at life. for (int i = 0, imax = list.Count; i < imax; ++i) { UpdateEntry ent = list[i]; if (ent.func == func) return; } #endif UpdateEntry item = new UpdateEntry(); item.index = updateOrder; item.func = func; item.mb = mb; item.isMonoBehaviour = (mb != null); list.Add(item); if (updateOrder != 0) list.Sort(Compare); }
/// <summary> /// Применяет изменения, внесенные в контрол редактирования /// </summary> internal void EndEdit() { // Проверяем что редактирование в принципе начато на данный момент if (FocusedCell != null && FocusedCell.IsEditing) { FocusedCell.IsEditing = false; if (m_CellEditor != null && FocusedCell.Cell != null) { ItemsLayoutRoot.Children.Remove(m_CellEditor.Editor); if (CellEditor.Value == null || String.IsNullOrEmpty(CellEditor.Value.ToString())) return; //// Проверяем, что произошло изменение значения //if (FocusedCell.Cell.CellDescr.Value != null && FocusedCell.Cell.CellDescr.Value.Value != null) //{ // if (FocusedCell.Cell.CellDescr.Value.Value.ToString() == value) // return; //} String value = CellEditor.Value.ToString(); // Проверяем чтобы значение изменилось if (FocusedCell.Cell.ValueToString != value) { var entry = new UpdateEntry(FocusedCell.Cell, value); var changes = new List<UpdateEntry>(); changes.Add(entry); FocusedCell.NotRecalculatedChange = entry; // В качестве разделителя для числа обязательно должна использоватьеся точка (т.к. эта строка будет помещена в МDX) value = value.Replace(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator, "."); Raise_CellValueChanged(changes); } } } this.Focus(); }
public void ChangeCell(CellInfo cell, UpdateEntry entry) { if (cell != null) { if (m_CellControls_Dict.ContainsKey(cell)) { CellControl cell_control = m_CellControls_Dict[cell]; if (cell_control != null) { cell_control.NotRecalculatedChange = entry; } } } }
void CellsControl_PerformControlAction(object sender, ControlActionEventArgs<CellInfo> e) { switch (e.Action) { case ControlActionType.ShowMDX: UpdateEntry entry = new UpdateEntry(e.UserData); try { if (e.UserData != null) entry.OldValue = e.UserData.CellDescr.Value.Value.ToString(); } catch { } UpdateEntry change = PivotGrid.LocalChanges.FindChange(e.UserData); if (change != null) { entry.NewValue = change.NewValue; } ShowDataSourceInfo(GetDataSourceInfo(entry)); break; case ControlActionType.ShowProperties: ModalDialog dlg = new ModalDialog() { Width = 400, Height = 300, DialogStyle = ModalDialogStyles.OK }; CellPropertiesControl properties = new CellPropertiesControl(); properties.Initialize(e.UserData); dlg.Content = properties; dlg.Caption = Localization.CellPropertiesDialog_Caption; Panel panel = GetRootPanel(this); if (panel != null) { panel.Children.Add(dlg.Dialog.PopUpControl); } ShowDialog(dlg); break; case ControlActionType.ValueDelivery: ShowValueDeliveryDialog(e.UserData); break; case ControlActionType.ValueCopy: ShowValueCopyDialog(e.UserData); break; case ControlActionType.Copy: CopyCellsToClipboard(e.UserData); break; case ControlActionType.Paste: PasteCellsFromClipboard(e.UserData); break; case ControlActionType.DrillThrough: DrillThroughCell(e.UserData); break; case ControlActionType.DataReorganizationType_None: ChangeDataReorganizationType(DataReorganizationTypes.None); break; case ControlActionType.DataReorganizationType_HitchToParent: ChangeDataReorganizationType(DataReorganizationTypes.LinkToParent); break; case ControlActionType.DataReorganizationType_MergeNeighbors: ChangeDataReorganizationType(DataReorganizationTypes.MergeNeighbors); break; } }
void PasteCellsFromClipboard(CellInfo cell) { // На всякий случай проверим if (!PivotGrid.CanEdit || !PivotGrid.EditMode) return; String text = Clipboard.GetClipboardText(); if (!String.IsNullOrEmpty(text)) { // В буфере ячейки хранятся разделенные табуляцией и переходом на новую строку. // Например ячейки (* - пустая): // 3 * * * // * * * * // 5 * 6 * // * * * * // В буфере при копировании из Excel это выглядит так: "3\t\t\t\r\n\r\n5\t\t6" // Буфер, в который накапливаются значения из Clipboard List<List<String>> buff = new List<List<string>>(); // Разделим содержимое буфера на строки text = text.Trim(); String[] rows_list = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); if (rows_list != null) { // Разделим содержимое каждой строки foreach (String str in rows_list) { List<String> row_Buff = new List<string>(); String[] columns_list = str.Split(new string[] { "\t" }, StringSplitOptions.None); if (columns_list != null) { foreach (String val in columns_list) { row_Buff.Add(val); } } buff.Add(row_Buff); } } // Буфер с целью оптимизации не содержит пустые ячейки, если они вляются последними в строке. // Поэтому чтобы найти реальный размер копируемой области по ширине нужно взять максимальную длину из имеющихся int width = 0; foreach (List<String> row in buff) { width = Math.Max(width, row.Count); } // Обходим буфер и меняем значения ячеек int row_index = 0; List<UpdateEntry> changes = new List<UpdateEntry>(); int start_ColumnIndex = 0; int start_RowIndex = 0; if (cell != null) { start_ColumnIndex = cell.CellDescr.Axis0_Coord; start_RowIndex = cell.CellDescr.Axis1_Coord; } foreach (List<String> row in buff) { for (int col_index = 0; col_index < width; col_index++) { String val = String.Empty; if (col_index < row.Count) val = row[col_index]; // Пытаемся по координате получить ячейку CellInfo destination_cell = m_CellSetProvider.GetCellInfo(start_ColumnIndex + col_index, start_RowIndex + row_index); //FAST CellControl destination_cell = PivotPanelControl.CellsControl.GetCell(start_ColumnIndex + col_index, start_RowIndex + row_index); if (destination_cell != null && destination_cell.IsUpdateable) { if (String.IsNullOrEmpty(val)) { // КC: // записывать НОЛЬ только в том случае если у нас было какое-то число, если числа не было (в ячейке было null) то оставлять null if (destination_cell.Value != null || PivotGrid.LocalChanges.FindChange(destination_cell) != null) { UpdateEntry entry = new UpdateEntry(destination_cell, "0"); PivotGrid.ChangeCell(destination_cell, entry); changes.Add(entry); continue; } } else { try { // Пытаемся преобразовать строку в число double new_val = 0; new_val = Convert.ToDouble(val); if (destination_cell.Value != null) { double x = 0; x = Convert.ToDouble(destination_cell.Value.ToString()); if (x == new_val) continue; } UpdateEntry entry = new UpdateEntry(destination_cell, new_val.ToString()); PivotGrid.ChangeCell(destination_cell, entry); changes.Add(entry); } catch { } } } } row_index++; } if (changes.Count > 0) PerformCellChanges(changes); } }
/// <summary> /// В случае необходимости выводит диалог с запросом на сохранение изменений /// </summary> //private PopUpQuestionDialog SaveChangesDlg //{ // get // { // PopUpQuestionDialog dlg = new PopUpQuestionDialog(); // dlg.Caption = "Warning..."; // dlg.ContentCtrl.Text = "Cache contains unsaved data! Save cached changes?"; // dlg.ContentCtrl.DialogType = DialogButtons.YesNo; // return dlg; // } //} /// <summary> /// Получает информацию о источнике данных /// </summary> /// <param name="userData"></param> void GetDataSourceInfo(UpdateEntry userData) { if (DataManager != null) { DataSourceInfoArgs info = DataManager.GetDataSourceInfo(userData); info.ConnectionString = Connection; ShowDataSourceInfo(info); } }
/// <summary> /// The run db update. /// </summary> /// <param name="connectionString"> /// The connection string. /// </param> /// <returns> /// The run db update. /// </returns> /// <remarks> /// </remarks> public bool RunDBUpdate(string connectionString) { CurrentCache.Insert(Portal.UniqueID + "_ConnectionString", connectionString); var databaseVersion = DatabaseVersion; var xmlDocument = new XmlDocument(); var tempScriptsList = new List<UpdateEntry>(); try { if (databaseVersion < Portal.CodeVersion) { ErrorHandler.Publish( LogLevel.Debug, string.Format("db:{0} Code:{1}", databaseVersion, Portal.CodeVersion)); // load the history file var docPath = HttpContext.Current.Server.MapPath("~/Setup/Scripts/History.xml"); xmlDocument.Load(docPath); // get a list of <Release> nodes if (xmlDocument.DocumentElement != null) { var releases = xmlDocument.DocumentElement.SelectNodes("Release"); if (releases != null) { // iterate over the <Release> nodes // (we can do this because XmlNodeList implements IEnumerable) foreach (XmlNode release in releases) { var updateEntry = new UpdateEntry(); // get the header information // we check for null to avoid exception if any of these nodes are not present if (release.SelectSingleNode("ID") != null) { updateEntry.VersionNumber = Int32.Parse(release.SelectSingleNode("ID/text()").Value); } if (release.SelectSingleNode("Version") != null) { updateEntry.Version = release.SelectSingleNode("Version/text()").Value; } if (release.SelectSingleNode("Script") != null) { updateEntry.ScriptNames.Add(release.SelectSingleNode("Script/text()").Value); } if (release.SelectSingleNode("Date") != null) { updateEntry.Date = DateTime.Parse(release.SelectSingleNode("Date/text()").Value); } // We should apply this patch if (databaseVersion < updateEntry.VersionNumber) { // Appleseed.Framework.Helpers.LogHelper.Logger.Log(Appleseed.Framework.Site.Configuration.LogLevel.Debug, "Detected version to apply: " + myUpdate.Version); updateEntry.Apply = true; // get a list of <Installer> nodes var installers = release.SelectNodes("Modules/Installer/text()"); // iterate over the <Installer> Nodes (in original document order) // (we can do this because XmlNodeList implements IEnumerable) foreach (XmlNode installer in installers) { // and build an ArrayList of the scripts... updateEntry.Modules.Add(installer.Value); // Appleseed.Framework.Helpers.LogHelper.Logger.Log(Appleseed.Framework.Site.Configuration.LogLevel.Debug, "Detected module to install: " + installer.Value); } // get a <Script> node, if any var sqlScripts = release.SelectNodes("Scripts/Script/text()"); // iterate over the <Installer> Nodes (in original document order) // (we can do this because XmlNodeList implements IEnumerable) foreach (XmlNode sqlScript in sqlScripts) { // and build an ArrayList of the scripts... updateEntry.ScriptNames.Add(sqlScript.Value); // Appleseed.Framework.Helpers.LogHelper.Logger.Log(Appleseed.Framework.Site.Configuration.LogLevel.Debug, "Detected script to run: " + sqlScript.Value); } tempScriptsList.Add(updateEntry); } } } } // If we have some version to apply... if (tempScriptsList.Count <= 0) { // No update is needed } else { this.scriptsList = tempScriptsList.ToArray(); // by Manu. Versions are sorted by version number Array.Sort(this.scriptsList); // Create a flat version for binding var currentVersion = 0; var databindList = new List<string>(); foreach (var updateEntry in this.scriptsList.Where(updateEntry => updateEntry.Apply)) { if (currentVersion != updateEntry.VersionNumber) { databindList.Add(string.Format("Version: {0}", updateEntry.VersionNumber)); currentVersion = updateEntry.VersionNumber; } databindList.AddRange( updateEntry.ScriptNames.Where(scriptName => scriptName.Length > 0).Select( scriptName => string.Format("-- Script: {0}", scriptName))); databindList.AddRange( updateEntry.Modules.Where(moduleInstaller => moduleInstaller.Length > 0).Select( moduleInstaller => string.Format("-- Module: {0}", moduleInstaller))); } var errors = new List<object>(); // var messages = new List<object>(); foreach (var updateEntry in this.scriptsList) { if (updateEntry.Apply && DatabaseVersion < updateEntry.VersionNumber && DatabaseVersion < Portal.CodeVersion) { // Version check (a script may update more than one version at once) foreach (var scriptName in updateEntry.ScriptNames) { if (scriptName.Length <= 0) { continue; } // It may be a module update only var currentScriptName = HttpContext.Current.Server.MapPath( System.IO.Path.Combine("~/Setup/Scripts/", scriptName)); ErrorHandler.Publish( LogLevel.Info, string.Format( "CODE: {0} - DB: {1} - CURR: {2} - Applying: {3}", Portal.CodeVersion, DatabaseVersion, updateEntry.VersionNumber, currentScriptName)); var myerrors = DBHelper.ExecuteScript(currentScriptName, true); errors.AddRange(myerrors); // Display errors if any if (myerrors.Count <= 0) { continue; } errors.Insert(0, string.Format("<p>{0}</p>", scriptName)); ErrorHandler.Publish( LogLevel.Error, string.Format( "Version {0} completed with errors. - {1}", updateEntry.Version, scriptName)); break; } // Installing modules foreach (var currentModuleInstaller in from string moduleInstaller in updateEntry.Modules select HttpContext.Current.Server.MapPath(System.IO.Path.Combine("~/", moduleInstaller))) { try { ModuleInstall.InstallGroup(currentModuleInstaller, true); } catch (Exception ex) { ErrorHandler.Publish( LogLevel.Fatal, string.Format( "Exception in UpdateDatabaseCommand installing module: {0}", currentModuleInstaller), ex); if (ex.InnerException != null) { // Display more meaningful error message if InnerException is defined ErrorHandler.Publish( LogLevel.Warn, string.Format( "Exception in UpdateDatabaseCommand installing module: {0}", currentModuleInstaller), ex.InnerException); errors.Add( string.Format( "Exception in UpdateDatabaseCommand installing module: {0}<br />{1}<br />{2}", currentModuleInstaller, ex.InnerException.Message, ex.InnerException.StackTrace)); } else { ErrorHandler.Publish( LogLevel.Warn, string.Format( "Exception in UpdateDatabaseCommand installing module: {0}", currentModuleInstaller), ex); errors.Add(ex.Message); } } } if (Equals(errors.Count, 0)) { // Update db with version var versionUpdater = string.Format( "INSERT INTO [rb_Versions] ([Release],[Version],[ReleaseDate]) VALUES('{0}','{1}', CONVERT(datetime, '{2}/{3}/{4}', 101))", updateEntry.VersionNumber, updateEntry.Version, updateEntry.Date.Month, updateEntry.Date.Day, updateEntry.Date.Year); DBHelper.ExeSQL(versionUpdater); ErrorHandler.Publish( LogLevel.Info, string.Format("Version number: {0} applied successfully.", updateEntry.Version)); // Mark this update as done ErrorHandler.Publish( LogLevel.Info, string.Format("Successfully applied version: {0}", updateEntry.Version)); } } else { ErrorHandler.Publish( LogLevel.Info, string.Format( "CODE: {0} - DB: {1} - CURR: {2} - Skipping: {3}", Portal.CodeVersion, DatabaseVersion, updateEntry.VersionNumber, updateEntry.Version)); } } } } } catch (Exception exception) { ErrorHandler.Publish(LogLevel.Error, "An error occurred during the installation process.", exception); throw exception; } return true; }
/// <summary> /// В случае необходимости выводит диалог с запросом на сохранение изменений /// </summary> //private PopUpQuestionDialog SaveChangesDlg //{ // get // { // PopUpQuestionDialog dlg = new PopUpQuestionDialog(); // dlg.Caption = "Warning..."; // dlg.ContentCtrl.Text = "Cache contains unsaved data! Save cached changes?"; // dlg.ContentCtrl.DialogType = DialogButtons.YesNo; // return dlg; // } //} /// <summary> /// Получает информацию о источнике данных /// </summary> /// <param name="userData"></param> public virtual DataSourceInfoArgs GetDataSourceInfo(UpdateEntry userData) { if (DataManager != null) { DataSourceInfoArgs info = DataManager.GetDataSourceInfo(userData); info.ConnectionString = Connection; return info; } return null; }
void ValueDeliveryDialog_OkButtonClick(object sender, DialogResultArgs e) { ModalDialog dlg = sender as ModalDialog; if (dlg != null) { ValueDeliveryControl DeliveryControl = dlg.Content as ValueDeliveryControl; if (DeliveryControl != null && DeliveryControl.Cell != null) { if (DeliveryControl.IsDelivered) { double new_Val = DeliveryControl.OriginalValue - DeliveryControl.DeliveredValue; String value = new_Val.ToString(); // В качестве разделителя для числа обязательно должна использоватьеся точка (т.к. эта строка будет помещена в МDX) value = value.Replace(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator, "."); List<UpdateEntry> entries = new List<UpdateEntry>(); UpdateEntry entry = new UpdateEntry(DeliveryControl.Cell, value); DeliveryControl.GetDeliveredMembers(); entries.Add(entry); IList<MemberItem> changes = DeliveryControl.GetDeliveredMembers(); foreach (MemberItem item in changes) { value = item.NewValue.ToString(); // В качестве разделителя для числа обязательно должна использоватьеся точка (т.к. эта строка будет помещена в МDX) value = value.Replace(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator, "."); UpdateEntry item_entry = new UpdateEntry(); foreach (var tuple_item in DeliveryControl.Cell.Tuple) { String uniqueName = String.Empty; if (tuple_item.Key != item.Member.HierarchyUniqueName) { uniqueName = tuple_item.Value; } else { uniqueName = item.Member.UniqueName; } item_entry.Tuple.Add(tuple_item.Key, uniqueName); } item_entry.NewValue = value; try { item_entry.OldValue = item.Cell.CellDescr.Value.Value.ToString(); } catch { } entries.Add(item_entry); } SaveChanges(entries); } } } }