public void SendSync(string[] numbers, SyncMode mode = SyncMode.Delta, SyncContext context = SyncContext.Background, int index = 0, bool last = true) { List<ProtocolTreeNode> users = new List<ProtocolTreeNode>(); foreach (string number in numbers) { string _number = number; if (!_number.StartsWith("+", StringComparison.InvariantCulture)) _number = string.Format("+{0}", number); users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(_number))); } ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("to", GetJID(this.phoneNumber)), new KeyValue("type", "get"), new KeyValue("id", TicketCounter.MakeId("sendsync_")), new KeyValue("xmlns", "urn:xmpp:whatsapp:sync") }, new ProtocolTreeNode("sync", new KeyValue[] { new KeyValue("mode", mode.ToString().ToLowerInvariant()), new KeyValue("context", context.ToString().ToLowerInvariant()), new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()), new KeyValue("index", index.ToString()), new KeyValue("last", last.ToString()) }, users.ToArray() ) ); this.SendNode(node); }
protected SynchronizedObject(SyncContext syncRoot) { SyncRoot = syncRoot == null ? new SyncContext() : syncRoot; }
public StepperInternalLoop(string name, SyncContext syncContext = null) : base(name, syncContext) { }
/// <summary> /// Send changes to server /// </summary> public async Task <(SyncContext, ChangesStatistics)> ApplyChangesAsync(SyncContext context, ScopeInfo fromScope, BatchInfo changes) { if (changes == null || changes.BatchPartsInfo.Count == 0) { return(context, new ChangesStatistics()); } SyncContext syncContext = null; ChangesStatistics changesStatistics = null; // Foreach part, will have to send them to the remote // once finished, return context foreach (var bpi in changes.BatchPartsInfo.OrderBy(bpi => bpi.Index)) { HttpMessage httpMessage = new HttpMessage(); httpMessage.Step = HttpStep.ApplyChanges; httpMessage.SyncContext = context; httpMessage.ApplyChanges = new HttpApplyChangesMessage(); httpMessage.ApplyChanges.ScopeInfo = fromScope; // If BPI is InMempory, no need to deserialize from disk // Set already contained in part.Set if (!changes.InMemory) { // get the batch var partBatch = bpi.GetBatch(); // get the surrogate dmSet if (partBatch != null) { httpMessage.ApplyChanges.Set = partBatch.DmSetSurrogate; } } else if (bpi.Set != null) { httpMessage.ApplyChanges.Set = new DmSetSurrogate(bpi.Set); } if (httpMessage.ApplyChanges.Set == null || httpMessage.ApplyChanges.Set.Tables == null || httpMessage.ApplyChanges.Set.Tables.Count == 0) { throw new ArgumentException("No changes to upload found."); } // no need to send filename httpMessage.ApplyChanges.BatchPartInfo = new BatchPartInfo { FileName = null, Index = bpi.Index, IsLastBatch = bpi.IsLastBatch, Tables = bpi.Tables }; httpMessage.ApplyChanges.InMemory = changes.InMemory; httpMessage.ApplyChanges.BatchIndex = bpi.Index; //Post request and get response var httpMessageResponse = await this.httpRequestHandler.ProcessRequest(httpMessage, cancellationToken); // Clear surrogate httpMessage.ApplyChanges.Set.Dispose(); httpMessage.ApplyChanges.Set = null; if (httpMessageResponse == null) { throw new Exception("Can't have an empty body"); } syncContext = httpMessageResponse.SyncContext; changesStatistics = httpMessageResponse.ApplyChanges.ChangesStatistics; } return(syncContext, changesStatistics); }
public async Task <(SyncContext, SyncConfiguration)> EnsureConfigurationAsync(SyncContext context, SyncConfiguration configuration = null) { HttpMessage httpMessage = new HttpMessage(); httpMessage.SyncContext = context; httpMessage.Step = HttpStep.EnsureConfiguration; //Post request and get response var httpMessageResponse = await this.httpRequestHandler.ProcessRequest(httpMessage, cancellationToken); if (httpMessageResponse == null) { throw new Exception("Can't have an empty body"); } if (httpMessageResponse.EnsureConfiguration == null || httpMessageResponse.EnsureConfiguration.Configuration == null || httpMessageResponse.EnsureConfiguration.ConfigurationSet == null || httpMessageResponse.EnsureConfiguration.ConfigurationSet.Tables.Count <= 0) { throw new ArgumentException("Configuration can't be null"); } // get config & deserialize set var conf = httpMessageResponse.EnsureConfiguration.Configuration; var set = httpMessageResponse.EnsureConfiguration.ConfigurationSet.ConvertToDmSet(); httpMessageResponse.EnsureConfiguration.ConfigurationSet.Clear(); httpMessageResponse.EnsureConfiguration.ConfigurationSet.Dispose(); httpMessageResponse.EnsureConfiguration.ConfigurationSet = null; conf.ScopeSet = set; // get context var syncContext = httpMessageResponse.SyncContext; // because we need it after this.syncConfiguration = conf; return(syncContext, conf); }
public void StartLoading() { ++LoadingCounter; SyncContext.Post(o => IsProcessing = LoadingCounter > 0U, null); }
public MDataTypeMapRepository(SyncContext context) : base(context) { }
internal bool Add(Entity item, SyncContext syncContext, RemovalContext removalContext) { if (Contains(item)) { return(false); } try { var operations = Session.Operations; using (var scope = operations.BeginRegistration(Operations.OperationType.System)) { var itemKey = item.Key; if (operations.CanRegisterOperation) { operations.RegisterOperation(new EntitySetItemAddOperation(Owner.Key, Field, itemKey)); } SystemBeforeAdd(item); int? index = null; var association = Field.GetAssociation(item.TypeInfo); Action finalizer = () => { var auxiliaryType = association.AuxiliaryType; if (auxiliaryType != null && association.IsMaster) { var combinedTuple = auxilaryTypeKeyTransform.Apply( TupleTransformType.Tuple, Owner.Key.Value, itemKey.Value); var combinedKey = Key.Create( Session.Domain, Session.StorageNodeId, auxiliaryType, TypeReferenceAccuracy.ExactType, combinedTuple); Session.CreateOrInitializeExistingEntity(auxiliaryType.UnderlyingType, combinedKey); Session.ReferenceFieldsChangesRegistry.Register(Owner.Key, itemKey, combinedKey, Field); } var state = State; state.Add(itemKey); Session.EntitySetChangeRegistry.Register(state); index = GetItemIndex(state, itemKey); }; operations.NotifyOperationStarting(); if (association.IsPaired) { Session.PairSyncManager.ProcessRecursively(syncContext, removalContext, OperationType.Add, association, Owner, item, finalizer); } else { finalizer.Invoke(); } // removalContext is unused here, since Add is never // invoked in reference cleanup process directly if (!skipOwnerVersionChange) { Owner.UpdateVersionInfo(Owner, Field); } SystemAdd(item, index); SystemAddCompleted(item, null); scope.Complete(); return(true); } } catch (Exception e) { SystemAddCompleted(item, e); throw; } }
/// <summary> /// Updates last date synchronization. /// </summary> /// <param name="userConnection">User connection.</param> /// <param name="context">Synchronization context.</param> protected abstract void UpdateLastSyncDate(UserConnection userConnection, SyncContext context);
/// <summary> /// Displays the given image. /// </summary> /// <param name="p_imgImage">The image to display.</param> /// <param name="p_strTitle">The title to display in the image viewer.</param> public void ShowImage(Image p_imgImage, string p_strTitle) { SyncContext.Send(x => ShowImageViewer(p_imgImage, p_strTitle), null); }
/// <summary> /// Displays text. /// </summary> /// <param name="p_strTitle">The title of the editor.</param> /// <param name="p_strInitialValue">The initial value of the editor.</param> public void ShowText(string p_strTitle, string p_strInitialValue) { SyncContext.Send(x => TextEditor.Show(p_strTitle, p_strInitialValue, true), null); }
public HttpMessageSendChangesResponse(SyncContext context) => this.SyncContext = context ?? throw new ArgumentNullException(nameof(context));
static public void Obj2Stream <T>(T obj, Stream dst) where T : IMarshallable { var writer = new MsgPackDataWriter(dst); Sync(SyncContext.NewWriter(writer), ref obj); }
static public void Stream2Obj <T>(Stream s, T obj, IFactory f = null) where T : IMarshallable { var reader = new MsgPackDataReader(s); Sync(SyncContext.NewReader(reader, f), ref obj); }
public void Initialize() { connection = Effort.DbConnectionFactory.CreateTransient(); context = new SyncContext(connection); repository = new UserRepository(context); }
public virtual byte[] Crawl(string uriString) { byte[] content = GetFromCache(uriString); if (content != null) { return content; } using (ManualResetEvent signal = new ManualResetEvent(false)) { SyncContext context = new SyncContext(signal); AsyncCrawl(uriString, SyncCallback, context); signal.WaitOne(); if (context.error != null) { throw context.error; } return context.data; } }
/// <summary> /// 解析数据 /// </summary> /// <param name="text"></param> public static void ParseXml(string text) { if (string.IsNullOrWhiteSpace(text)) { return; } XElement doc = XElement.Parse(text.Trim()); #region KEEPALIVE消息 if (StringUtils.EqualsEx(doc.Name.LocalName, "keepalive")) { LogHelper.Debug("收到 KeepAlive消息:" + doc.Value); //KEEPALIVE信息 return; } #endregion #region MSG消息 if (StringUtils.EqualsEx(doc.Name.LocalName, "msg")) { var meta = doc.Element("META"); string msgType = meta.GetValue("TYPE"); //消息类型 string subType = meta.GetValue("SUBTYPE"); //消息子类型 LogHelper.Info("接收到消息类型:{0},子类型:{1}.".FormatWith(msgType, subType)); #region 动态航班添加 修改 if (StringUtils.EqualsEx(msgType, "DYNFLIGHT") && (StringUtils.EqualsEx(subType, "ADD") || StringUtils.EqualsEx(subType, "MODIFY"))) { //添加动态航班 XElement dflt = doc.Element("DFLT"); Flight flight = new Flight(); //航班数 flight.Id = Guid.NewGuid(); //主键 flight.Flag = "Normal"; //正常航班 flight.FlightId = dflt.GetValue("ID"); //航班id 集成的标志 如: 558169 flight.FlightNo = dflt.GetValue("FLIGHTNO"); //航班号 4912 flight.FlightDate = DateTime.ParseExact(dflt.GetValue("FLIGHTDATE"), "yyyyMMdd", CultureInfo.InvariantCulture);; //航班日期 如10150923 flight.AirlineIata = dflt.GetValue("AIRLINE"); //航空公司二字码 如:SC flight.InOut = dflt.GetValue("ISARRFLIGHT") == "1" ? "I" : "O"; //1是进港,0是出港 flight.Task = dflt.GetValue("TASK"); //航班任务 如 W/Z string regionId = dflt.GetValue("REGIONID"); //区域属性 100001 DMST国内; INTER 100002 国际; ZONE 100003 地区; 100004 MIX混合 switch (regionId) { case "100001": flight.Region = "FD"; break; case "100002": flight.Region = "FI"; break; case "100003": flight.Region = "FA"; break; case "100004": flight.Region = "FF"; break; } flight.CraftNo = dflt.GetValue("CRAFT"); //机号 flight.CraftType = dflt.GetValue("CRAFTMODEL"); //机型 flight.Status = dflt.GetValue("STATUS"); //航班状态 LBD 催促登机 POK 登机截止 DEP 起飞 TBR 过站登机 BOR 本站登机 CKO 值机截止 CKI 值机开始 ARR 到达 ONR 前方起飞 flight.ExStatus = dflt.GetValue("ABNSTATUS"); //异常航班状态代码 CAN 取消 ALT 备降 RTN 返航 DLY 延误 string abnrsn = dflt.GetValue("ABNRSN"); //航班异常原因 如:前站天气 string alterStation = null; //变更站 备降 DateTime?planStartTime = null; //计划开始 DateTime?planStopTime = null; //计划结束 DateTime?alterStartTime = null; //变更开始 DateTime?alterStopTime = null; //变更结束 DateTime?realStartTime = null; //实际开始 DateTime?realStopTime = null; //实际结束 #region 经由 if (dflt.Element("ROUTELST") != null) { var routeList = dflt.Element("ROUTELST").Elements("ROUTE").ToList(); //航站列表 for (int i = 0; i < routeList.Count(); i++) { if (i == 0) { //出发站 flight.Departure = routeList[i].GetValue("AIRPORTIATA"); //出发站 routeList[i].Update(ref planStartTime, "PLANTAKEOFF"); //计划开始 routeList[i].Update(ref alterStartTime, "ALTERTAKEOFF"); routeList[i].Update(ref realStartTime, "REALTAKEOFF"); } else if (i == routeList.Count - 1 && routeList.Count >= 2) { //终点站 flight.Destination = routeList[i].GetValue("AIRPORTIATA"); routeList[i].Update(ref planStopTime, "PLANLANDING"); routeList[i].Update(ref alterStopTime, "ALTERLANDING"); routeList[i].Update(ref realStopTime, "REALLANDING"); } else { //经由 FlightVia via = new FlightVia(); via.FlightId = flight.Id; via.AirportIata = routeList[i].GetValue("AIRPORTIATA"); via.StartTime = routeList[i].GetTime("REALTAKEOFF") ?? routeList[i].GetTime("ALTERTAKEOFF") ?? routeList[i].GetTime("PLANTAKEOFF"); via.StopTime = routeList[i].GetTime("REALPLANDING") ?? routeList[i].GetTime("ALTERLANDING") ?? routeList[i].GetTime("PLANLANDING"); flight.FlightVias.Add(via); } if (routeList[i].GetValue("ISALTERAIRPORT") == "1") { //备降站 取第一个 alterStation = alterStation ?? flight.Departure; } } flight.PlanStartTime = planStartTime; flight.PlanStopTime = planStopTime; flight.AlterStartTime = alterStartTime; flight.AlterStopTime = alterStopTime; flight.RealStartTime = realStartTime; flight.RealStopTime = realStopTime; flight.AlterStation = alterStation; } #endregion #region 共享航班 if (dflt.Element("SHARELST") != null) { var shareList = dflt.Element("SHARELST").Elements("SHARE").ToList(); foreach (var share in shareList) { FlightShare flightShare = new FlightShare() { FlightId = flight.Id, AirlineIata = share.GetValue("AIRLINE"), FlightNo = share.GetValue("FLIGHTNO") }; flight.FlightShares.Add(flightShare); } } #endregion #region 值机柜台 if (dflt.Element("CKITIME") != null) { //值机柜台时间 var ckiTime = dflt.Element("CKITIME"); flight.StartCheckinTime = ckiTime.GetTime("REALOPENTIME") ?? ckiTime.GetTime("PLANOPENTIME"); flight.StopCheckinTime = ckiTime.GetTime("REALENDTIME") ?? ckiTime.GetTime("PLANENDTIME"); } if (dflt.Element("CKICLST") != null) { //值机柜台 var ckiList = dflt.Element("CKICLST").Elements("CKIC").ToList(); HashSet <string> counterDisplay = new HashSet <string>(); foreach (var check in ckiList) { string checkName = check.GetValue("CHICNAME"); if (string.IsNullOrEmpty(checkName)) { continue; } FlightInfrastructure flightInfrastructure = new FlightInfrastructure() { FlightId = flight.Id, InfrastructureType = "Counter", InfrastructureCode = checkName, StartTime = flight.StartCheckinTime, StopTime = flight.StopCheckinTime, Flag = "N" }; string ckicAreaCode = check.GetValue("CKICAREACODE"); if (!string.IsNullOrEmpty(ckicAreaCode)) { counterDisplay.Add(ckicAreaCode); } flight.FlightInfrastructures.Add(flightInfrastructure); } flight.CounterDisplay = string.Empty; foreach (var item in counterDisplay) { flight.CounterDisplay += item + ","; } flight.CounterDisplay = flight.CounterDisplay.TrimEnd(','); } #endregion #region 登机口 if (dflt.Element("GATETIME") != null) { var gateTime = dflt.Element("GATETIME"); flight.StartBoardTime = gateTime.GetTime("REALOPENTIME") ?? gateTime.GetTime("PLANOPENTIME"); flight.StopBoardTime = gateTime.GetTime("REALENDTIME") ?? gateTime.GetTime("PLANENDTIME"); } if (dflt.Element("GATELST") != null) { var gateList = dflt.Element("GATELST").Elements("GATE"); HashSet <string> gateDisplay = new HashSet <string>(); foreach (var gate in gateList) { string gateName = gate.GetValue("GATENAME"); if (string.IsNullOrEmpty(gateName)) { continue; } FlightInfrastructure flightInfrastructure = new FlightInfrastructure() { FlightId = flight.Id, InfrastructureType = "Gate", InfrastructureCode = gateName, StartTime = flight.StartBoardTime, StopTime = flight.StopBoardTime, Flag = "N" }; flight.FlightInfrastructures.Add(flightInfrastructure); gateDisplay.Add(gateName); } flight.GateDisplay = string.Empty; foreach (var item in gateDisplay) { flight.GateDisplay += item + ","; } flight.GateDisplay = flight.GateDisplay.TrimEnd(','); } #endregion #region 行李转盘 if (flight.InOut == "I") { //进港行李转盘 if (dflt.Element("ACRSLTIME") != null) { var claimTime = dflt.Element("ACRSLTIME"); flight.StartClaimTime = claimTime.GetTime("REALOPENTIME") ?? claimTime.GetTime("PLANOPENTIME"); flight.StopClaimTime = claimTime.GetTime("REALENDTIME") ?? claimTime.GetTime("PLANENDTIME"); } if (dflt.Element("ACRSLLST") != null) { var claimList = dflt.Element("ACRSLLST").Elements("ACRSL").ToList(); HashSet <string> claimDisplay = new HashSet <string>(); foreach (var claim in claimList) { string claimName = claim.GetValue("ACRSLNAME"); if (string.IsNullOrEmpty(claimName)) { continue; } FlightInfrastructure flightInfrastructure = new FlightInfrastructure() { FlightId = flight.Id, StartTime = flight.StartClaimTime, StopTime = flight.StopClaimTime, Flag = "N", InfrastructureType = "Claim", InfrastructureCode = claimName }; flight.FlightInfrastructures.Add(flightInfrastructure); claimDisplay.Add(claimName); } flight.ClaimDisplay = string.Empty; foreach (var item in claimDisplay) { flight.ClaimDisplay += item + ","; } flight.ClaimDisplay = flight.ClaimDisplay.TrimEnd(','); } } else { //出港行李转盘 if (dflt.Element("DCRSLTIME") != null) { var claimTime = dflt.Element("DCRSLTIME"); flight.StartClaimTime = claimTime.GetTime("REALOPENTIME") ?? claimTime.GetTime("PLANOPENTIME"); flight.StopClaimTime = claimTime.GetTime("REALENDTIME") ?? claimTime.GetTime("PLANENDTIME"); } if (dflt.Element("DCRSLLST") != null) { var claimList = dflt.Element("DCRSLLST").Elements("DCRSL").ToList(); HashSet <string> claimDisplay = new HashSet <string>(); foreach (var claim in claimList) { string claimName = claim.GetValue("DCRSLNAME"); if (string.IsNullOrEmpty(claimName)) { continue; } FlightInfrastructure flightInfrastructure = new FlightInfrastructure() { FlightId = flight.Id, StartTime = flight.StartClaimTime, StopTime = flight.StopClaimTime, Flag = "N", InfrastructureType = "Claim", InfrastructureCode = claimName }; flight.FlightInfrastructures.Add(flightInfrastructure); claimDisplay.Add(claimName); } flight.ClaimDisplay = string.Empty; foreach (var item in claimDisplay) { flight.ClaimDisplay += item + ","; } flight.ClaimDisplay = flight.ClaimDisplay.TrimEnd(','); } } #endregion #region 机位 if (dflt.Element("SEATTIME") != null) { var standTime = dflt.Element("SEATTIME"); flight.StartStandTime = standTime.GetTime("REALARVTIME") ?? standTime.GetTime("PLANARVTIME"); //进机位时间 有实际显实际 否则显计划 flight.StopStandTime = standTime.GetTime("REALDEPTIME") ?? standTime.GetTime("PLANDEPTIME"); //出机位时间 有实际显实际 否则显计划 } if (dflt.Element("SEATLST") != null) { var standList = dflt.Element("SEATLST").Elements("SEAT").ToList(); HashSet <string> standDisplay = new HashSet <string>(); foreach (var stand in standList) { string standName = stand.GetValue("SEATNAME"); if (string.IsNullOrEmpty(standName)) { continue; } FlightInfrastructure flightInfrastructure = new FlightInfrastructure() { FlightId = flight.Id, Flag = "N", InfrastructureCode = standName, InfrastructureType = "Stand", StartTime = flight.StartBoardTime, StopTime = flight.StopBoardTime }; flight.FlightInfrastructures.Add(flightInfrastructure); standDisplay.Add(standName); } flight.StandDisplay = string.Empty; foreach (var item in standDisplay) { flight.StandDisplay += item + ","; } flight.StandDisplay = flight.StandDisplay.TrimEnd(','); } #endregion #region 保存数据 using (SyncContext context = new SyncContext()) { //以航班号+航班日期+进出港为标记 var oldFlight = context.Flights.Where(r => (r.FlightId == flight.FlightId || (r.AirlineIata == flight.AirlineIata && r.FlightNo == flight.FlightNo && r.InOut == flight.InOut && SqlFunctions.DateDiff("day", r.FlightDate, flight.FlightDate) == 0))).Include(r => r.FlightVias).Include(r => r.FlightShares).Include(r => r.FlightInfrastructures).FirstOrDefault(); if (oldFlight != null) { if (StringUtils.EqualsEx(oldFlight.Flag, "Manual")) { //手工航班 return; } //更新状态时间 if (oldFlight.Status != flight.Status && !string.IsNullOrEmpty(flight.Status)) { flight.StatusTime = DateTime.Now; } Update(oldFlight, flight); int count = context.SaveChanges(); LogHelper.Info("计划修改1条航班,影响数据{0}行,操作类型:{1},子类型{2}".FormatWith(count, msgType, subType)); } else { //如果历史中包含,则不添加 var historyFlight = context.HistoryFlights.FirstOrDefault(r => r.FlightId == flight.FlightId && r.FlightNo == flight.FlightNo && r.AirlineIata == flight.AirlineIata && SqlFunctions.DateDiff("day", r.FlightDate, flight.FlightDate) <= 1); if (historyFlight != null) { LogHelper.Info("数据已经转历史,不执行添加操作,操作类型:{0},子类型{1}".FormatWith(msgType, subType)); } else { if (!string.IsNullOrEmpty(flight.Status)) { flight.StatusTime = DateTime.Now; } context.Flights.Add(flight); int count = context.SaveChanges(); LogHelper.Info("计划新增1条航班,影响数据{0}行,操作类型:{1},子类型{2}".FormatWith(count, msgType, subType)); } } } #endregion } #endregion #region 动态航班删除 if (StringUtils.EqualsEx(msgType, "DYNFLIGHT") && StringUtils.EqualsEx(subType, "DELETE")) { XElement dflt = doc.Element("DFLT"); string id = dflt.GetValue("ID"); if (string.IsNullOrEmpty(id)) { LogHelper.Info("没有删除任何数据"); } else { using (SyncContext context = new SyncContext()) { var fltRemove = context.Flights.Where(r => r.FlightId == id).Include(r => r.FlightVias).Include(r => r.FlightInfrastructures).Include(r => r.FlightShares).ToList(); if (fltRemove.Count > 0) { context.Flights.RemoveRange(fltRemove); int count = context.SaveChanges(); LogHelper.Info("计划删除{0}条航班,操作类型:{1},子类型:{2},影像数据{3}行。".FormatWith(fltRemove.Count, msgType, subType, count)); } else { LogHelper.Info("没有获取到匹配id={0}的数据,没有删除任何数据".FormatWith(id)); } } } } #endregion return; } #endregion LogHelper.Warn("该消息未被识别,未被处理"); }
/// <summary> /// Updates last synchtonization date. /// </summary> /// <param name="context">Synchronization context.</param> public override void CommitChanges(SyncContext context) { UpdateLastSyncDate(context.UserConnection, context); }
internal bool Remove(Entity item, SyncContext syncContext, RemovalContext removalContext) { if (!Contains(item)) { return(false); } try { var operations = Session.Operations; var scope = operations.BeginRegistration(Operations.OperationType.System); try { var itemKey = item.Key; if (operations.CanRegisterOperation) { operations.RegisterOperation(new EntitySetItemRemoveOperation(Owner.Key, Field, itemKey)); } SystemBeforeRemove(item); int? index = null; var association = Field.GetAssociation(item.TypeInfo); Action finalizer = () => { var auxiliaryType = association.AuxiliaryType; if (auxiliaryType != null && association.IsMaster) { var combinedTuple = auxilaryTypeKeyTransform.Apply( TupleTransformType.Tuple, Owner.Key.Value, itemKey.Value); var combinedKey = Key.Create( Session.Domain, Session.StorageNodeId, auxiliaryType, TypeReferenceAccuracy.ExactType, combinedTuple); Session.RemoveOrCreateRemovedEntity(auxiliaryType.UnderlyingType, combinedKey); } var state = State; index = GetItemIndex(state, itemKey); state.Remove(itemKey); Session.EntitySetChangeRegistry.Register(state); }; operations.NotifyOperationStarting(); if (association.IsPaired) { Session.PairSyncManager.ProcessRecursively(syncContext, removalContext, OperationType.Remove, association, Owner, item, finalizer); } else { finalizer.Invoke(); } if (removalContext != null) { // Postponing finalizers (events) removalContext.EnqueueFinalizer(() => { try { try { index = GetItemIndex(State, itemKey); // Necessary, since index can be already changed if (!skipOwnerVersionChange) { Owner.UpdateVersionInfo(Owner, Field); } SystemRemove(item, index); SystemRemoveCompleted(item, null); scope.Complete(); } finally { scope.DisposeSafely(); } } catch (Exception e) { SystemRemoveCompleted(item, e); throw; } }); return(true); } if (!skipOwnerVersionChange) { Owner.UpdateVersionInfo(Owner, Field); } SystemRemove(item, index); SystemRemoveCompleted(item, null); scope.Complete(); return(true); } finally { if (removalContext == null) { scope.DisposeSafely(); } } } catch (Exception e) { SystemRemoveCompleted(item, e); throw; } }
public LookupHtsRepository(SyncContext context) { Context = context; }
/// <summary> /// Initializes a new instance of the <see cref="UserRepository"/> class. /// </summary> /// <param name="context">The <see cref="SyncContext"/> object.</param> public UserRepository(SyncContext context) { database = context; }
/// <summary> /// Updates last synchronization date value. /// </summary> /// <param name="context"><see cref="SyncContext"/> instance.</param> public override void CommitChanges(SyncContext context) { _provider.CommitChanges(context); }
private static async Task <ErrorCode> StartAppAsync(string[] args, RunOptions options) { SetDirectories(options); try { using (SyncContext = GlobalContext.Create()) { if (SyncContext.IsFirst) { // First instance, start like normal InitLogger(options); await InitProgramAsync(options); SyncContext.BeginListen(); try { SkipUpdateCheck = options.NoAutoUpdate; var code = (ErrorCode)BuildAvaloniaApp().StartWithClassicDesktopLifetime(args, ShutdownMode.OnMainWindowClose); if (code != ErrorCode.NoError) { Log.Warning("Application returned error code '{0}'", code); } else { Log.Debug("Application exited gracefully"); } return(code); } catch (Exception ex) { Log.Error(ex, "Application crashed"); return(ErrorCode.General); } finally { SyncContext.EndListen(); UnloadProgram(); } } else { // App already running, pass arguments and exit try { var message = Parser.Default.FormatCommandLine(options); await SyncContext.SendMessageAsync(message); return(ErrorCode.NoError); } catch { return(ErrorCode.General); } } } } finally { SyncContext = null; } }
/// <summary> /// <see cref="ExchangeSyncProvider.EnumerateChanges"/> /// </summary> public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context) { return(_provider.EnumerateChanges(context)); }
public async Task <(SyncContext, BatchInfo, ChangesStatistics)> GetChangeBatchAsync(SyncContext context, ScopeInfo scopeInfo) { // While we have an other batch to process var isLastBatch = false; // Create the BatchInfo and SyncContext to return at the end BatchInfo changes = new BatchInfo(); changes.Directory = BatchInfo.GenerateNewDirectoryName(); SyncContext syncContext = null; ChangesStatistics changesStatistics = null; while (!isLastBatch) { HttpMessage httpMessage = new HttpMessage(); httpMessage.SyncContext = context; httpMessage.Step = HttpStep.GetChangeBatch; httpMessage.GetChangeBatch = new HttpGetChangeBatchMessage { ScopeInfo = scopeInfo, BatchIndexRequested = changes.BatchIndex }; var httpMessageResponse = await this.httpRequestHandler.ProcessRequest(httpMessage, cancellationToken); if (httpMessageResponse == null) { throw new Exception("Can't have an empty body"); } if (httpMessageResponse.GetChangeBatch == null) { throw new Exception("Can't have an empty GetChangeBatch"); } changesStatistics = httpMessageResponse.GetChangeBatch.ChangesStatistics; changes.InMemory = httpMessageResponse.GetChangeBatch.InMemory; syncContext = httpMessageResponse.SyncContext; // get the bpi and add it to the BatchInfo var bpi = httpMessageResponse.GetChangeBatch.BatchPartInfo; if (bpi != null) { changes.BatchIndex = bpi.Index; changes.BatchPartsInfo.Add(bpi); isLastBatch = bpi.IsLastBatch; } else { changes.BatchIndex = 0; isLastBatch = true; // break the while { } story break; } if (changes.InMemory) { // load the DmSet in memory bpi.Set = httpMessageResponse.GetChangeBatch.Set.ConvertToDmSet(); } else { // Serialize the file ! var bpId = BatchInfo.GenerateNewFileName(changes.BatchIndex.ToString()); var fileName = Path.Combine(this.syncConfiguration.BatchDirectory, changes.Directory, bpId); BatchPart.Serialize(httpMessageResponse.GetChangeBatch.Set, fileName); bpi.FileName = fileName; bpi.Clear(); } // Clear the DmSetSurrogate from response, we don't need it anymore if (httpMessageResponse.GetChangeBatch.Set != null) { httpMessageResponse.GetChangeBatch.Set.Dispose(); httpMessageResponse.GetChangeBatch.Set = null; } // if not last, increment batchIndex for next request if (!isLastBatch) { changes.BatchIndex++; } } return(syncContext, changes, changesStatistics); }
/// <summary> /// <see cref="RemoteProvider.GetLocallyModifiedItemsMetadata"/> /// </summary> public override IEnumerable <ItemMetadata> GetLocallyModifiedItemsMetadata(SyncContext context, EntitySchemaQuery modifiedItemsEsq) { return(_provider.GetLocallyModifiedItemsMetadata(context, modifiedItemsEsq)); }
public static void Init() { const SyncContext mouseKeyContext = SyncContext.QueueOrder_Down | SyncContext.MapMouseCell; SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.GotoLocationOption), 0).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Goto SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 0).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Arrest SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 5).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Rescue SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 6).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Capture slave SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 7).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Capture prisoner SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 8).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Carry to cryptosleep casket SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 10).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Carry to shuttle SyncDelegate.Lambda(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.AddHumanlikeOrders), 27).CancelIfAnyFieldNull().SetContext(mouseKeyContext); // Reload SyncDelegate.Lambda(typeof(HealthCardUtility), nameof(HealthCardUtility.GenerateSurgeryOption), 1).CancelIfAnyFieldNull(allowed: "part"); // Add medical bill SyncDelegate.Lambda(typeof(Command_SetPlantToGrow), nameof(Command_SetPlantToGrow.ProcessInput), 2); // Set plant to grow SyncDelegate.Lambda(typeof(Building_Bed), nameof(Building_Bed.SetBedOwnerTypeByInterface), 0).RemoveNullsFromLists("bedsToAffect"); // Set bed owner type SyncDelegate.Lambda(typeof(ITab_Bills), nameof(ITab_Bills.FillTab), 2).SetContext(SyncContext.MapSelected).CancelIfNoSelectedMapObjects(); // Add bill SyncDelegate.Lambda(typeof(CompLongRangeMineralScanner), nameof(CompLongRangeMineralScanner.CompGetGizmosExtra), 1).SetContext(SyncContext.MapSelected); // Select mineral to scan for SyncMethod.Lambda(typeof(CompFlickable), nameof(CompFlickable.CompGetGizmosExtra), 1); // Toggle flick designation SyncMethod.Lambda(typeof(Pawn_PlayerSettings), nameof(Pawn_PlayerSettings.GetGizmos), 1); // Toggle release animals SyncMethod.Lambda(typeof(Building_TurretGun), nameof(Building_TurretGun.GetGizmos), 2); // Toggle turret hold fire SyncMethod.Lambda(typeof(Building_Trap), nameof(Building_Trap.GetGizmos), 1); // Toggle trap auto-rearm SyncMethod.Lambda(typeof(Building_Door), nameof(Building_Door.GetGizmos), 1); // Toggle door hold open SyncMethod.Lambda(typeof(Zone_Growing), nameof(Zone_Growing.GetGizmos), 1); // Toggle zone allow sow SyncMethod.Lambda(typeof(Zone_Growing), nameof(Zone_Growing.GetGizmos), 3); // Toggle zone allow cut SyncMethod.Lambda(typeof(PriorityWork), nameof(PriorityWork.GetGizmos), 0); // Clear prioritized work SyncMethod.Lambda(typeof(Building_TurretGun), nameof(Building_TurretGun.GetGizmos), 1); // Reset forced target SyncMethod.Lambda(typeof(UnfinishedThing), nameof(UnfinishedThing.GetGizmos), 0); // Cancel unfinished thing SyncMethod.Lambda(typeof(CompTempControl), nameof(CompTempControl.CompGetGizmosExtra), 2); // Reset temperature SyncDelegate.Lambda(typeof(CompTargetable), nameof(CompTargetable.SelectedUseOption), 0); // Use targetable SyncDelegate.LambdaInGetter(typeof(Designator), nameof(Designator.RightClickFloatMenuOptions), 0) // Designate all .TransformField("things", Serializer.SimpleReader(() => Find.CurrentMap.listerThings.AllThings)); SyncDelegate.LambdaInGetter(typeof(Designator), nameof(Designator.RightClickFloatMenuOptions), 1) // Remove all designations .TransformField("designations", Serializer.SimpleReader(() => Find.CurrentMap.designationManager.allDesignations)); SyncDelegate.Lambda(typeof(CaravanAbandonOrBanishUtility), nameof(CaravanAbandonOrBanishUtility.TryAbandonOrBanishViaInterface), 1, new[] { typeof(Thing), typeof(Caravan) }).CancelIfAnyFieldNull(); // Abandon caravan thing SyncDelegate.Lambda(typeof(CaravanAbandonOrBanishUtility), nameof(CaravanAbandonOrBanishUtility.TryAbandonOrBanishViaInterface), 0, new[] { typeof(TransferableImmutable), typeof(Caravan) }).CancelIfAnyFieldNull(); // Abandon caravan transferable SyncDelegate.Lambda(typeof(CaravanAbandonOrBanishUtility), nameof(CaravanAbandonOrBanishUtility.TryAbandonSpecificCountViaInterface), 0, new[] { typeof(Thing), typeof(Caravan) }).CancelIfAnyFieldNull(); // Abandon thing specific count SyncDelegate.Lambda(typeof(CaravanAbandonOrBanishUtility), nameof(CaravanAbandonOrBanishUtility.TryAbandonSpecificCountViaInterface), 0, new[] { typeof(TransferableImmutable), typeof(Caravan) }).CancelIfAnyFieldNull(); // Abandon transferable specific count SyncDelegate.Lambda(typeof(CaravanVisitUtility), nameof(CaravanVisitUtility.TradeCommand), 0).CancelIfAnyFieldNull(); // Caravan trade with settlement SyncDelegate.Lambda(typeof(FactionGiftUtility), nameof(FactionGiftUtility.OfferGiftsCommand), 0).CancelIfAnyFieldNull(); // Caravan offer gifts SyncDelegate.Lambda(typeof(Building_Bed), nameof(Building_Bed.GetFloatMenuOptions), 0).CancelIfAnyFieldNull(); // Use medical bed SyncMethod.Lambda(typeof(CompRefuelable), nameof(CompRefuelable.CompGetGizmosExtra), 1); // Toggle Auto-refuel SyncMethod.Lambda(typeof(CompRefuelable), nameof(CompRefuelable.CompGetGizmosExtra), 2).SetDebugOnly(); // Set fuel to 0 SyncMethod.Lambda(typeof(CompRefuelable), nameof(CompRefuelable.CompGetGizmosExtra), 3).SetDebugOnly(); // Set fuel to 0.1 SyncMethod.Lambda(typeof(CompRefuelable), nameof(CompRefuelable.CompGetGizmosExtra), 4).SetDebugOnly(); // Set fuel to max SyncMethod.Lambda(typeof(CompShuttle), nameof(CompShuttle.CompGetGizmosExtra), 1); // Toggle autoload SyncMethod.Lambda(typeof(ShipJob_Wait), nameof(ShipJob_Wait.GetJobGizmos), 1); // Send shuttle SyncDelegate.LocalFunc(typeof(RoyalTitlePermitWorker_CallShuttle), nameof(RoyalTitlePermitWorker_CallShuttle.CallShuttleToCaravan), "Launch").ExposeParameter(1); // Call shuttle permit on caravan SyncMethod.Lambda(typeof(MonumentMarker), nameof(MonumentMarker.GetGizmos), 1); // Build monument quest - monument marker: cancel/remove marker SyncMethod.Lambda(typeof(MonumentMarker), nameof(MonumentMarker.GetGizmos), 4).SetDebugOnly(); // Build monument quest - monument marker: dev build all SyncDelegate.Lambda(typeof(CompPlantable), nameof(CompPlantable.BeginTargeting), 3); // Select cell to plant in with confirmation SyncMethod.Lambda(typeof(CompPlantable), nameof(CompPlantable.CompGetGizmosExtra), 0); // Cancel planting all SyncMethod.Lambda(typeof(Pawn_ConnectionsTracker), nameof(Pawn_ConnectionsTracker.GetGizmos), 3); // Return to healing pod SyncMethod.Lambda(typeof(CompTreeConnection), nameof(CompTreeConnection.CompGetGizmosExtra), 1).SetDebugOnly(); // Spawn dryad SyncMethod.Lambda(typeof(CompTreeConnection), nameof(CompTreeConnection.CompGetGizmosExtra), 2).SetDebugOnly(); // Increase connection strength by 10% SyncMethod.Lambda(typeof(CompTreeConnection), nameof(CompTreeConnection.CompGetGizmosExtra), 3).SetDebugOnly(); // Decrease connection strength by 10% SyncMethod.Lambda(typeof(CompDryadHolder), nameof(CompDryadHolder.CompGetGizmosExtra), 0).SetDebugOnly(); // Complete dryad cocoon action SyncMethod.Lambda(typeof(CompNeuralSupercharger), nameof(CompNeuralSupercharger.CompGetGizmosExtra), 1); // Neural supercharger: allow temporary pawns to use // Biosculpter pod SyncDelegate.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.SelectPawnCycleOption), 0); // Start cycle (should be universal for all cycle types, even modded) SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 1); // Interrupt cycle (eject contents) SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 3); // Toggle auto load nutrition SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 5); // Toggle auto age reversal SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 6).SetDebugOnly(); // Dev complete cycle SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 7).SetDebugOnly(); // Dev advance by 1 day SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 8).SetDebugOnly(); // Dev complete biotuner timer SyncMethod.Lambda(typeof(CompBiosculpterPod), nameof(CompBiosculpterPod.CompGetGizmosExtra), 9).SetDebugOnly(); // Dev fill nutrition and ingredients SyncDelegate.Lambda(typeof(ITab_Pawn_Visitor), nameof(ITab_Pawn_Visitor.FillTab), 1).SetContext(SyncContext.MapSelected).CancelIfNoSelectedMapObjects(); // Select target prisoner ideology SyncDelegate.Lambda(typeof(ITab_Pawn_Visitor), nameof(ITab_Pawn_Visitor.FillTab), 8).SetContext(SyncContext.MapSelected).CancelIfNoSelectedMapObjects(); // Cancel setting slave mode to execution SyncMethod.Lambda(typeof(ShipJob_Wait), nameof(ShipJob_Wait.GetJobGizmos), 0); // Dismiss (unload) shuttle SyncMethod.Lambda(typeof(ShipJob_Wait), nameof(ShipJob_Wait.GetJobGizmos), 1); // Send loaded shuttle SyncMethod.Lambda(typeof(Building_PodLauncher), nameof(Building_PodLauncher.GetGizmos), 0); // Pod launcher gizmo: Build pod SyncMethod.Lambda(typeof(Pawn_CarryTracker), nameof(Pawn_CarryTracker.GetGizmos), 0) .TransformTarget(Serializer.New(t => t.pawn, (Pawn p) => p.carryTracker)); // Drop carried pawn InitRituals(); InitChoiceLetters(); }
/// <summary> /// <see cref="ExchangeSyncProvider.ApplyChanges"/> /// </summary> public override void ApplyChanges(SyncContext context, IRemoteItem syncItem) { _provider.ApplyChanges(context, syncItem); }
public override void Loop() { DebugTools.AddEvent("StepperInternalLoop.Loop", "Loop Start. Signalling and waiting on " + (SyncContext?.GetNumberOfRemainingParticipants() - 1) + ". Total participants = " + SyncContext?.GetNumberOfTotalParticipants() + " : " + this.Name); SyncContext?.SignalAndWait(); //DebugTools.AddEvent("StepperInternalLoop.Loop", "Loop Start. Signal received. Continuing: " + this.Name); while (true) { if (CurrentStep + 1 > EndStep) { CurrentStep = StartStep; break; } else { CurrentStep++; } while (PauseForTest) { Thread.Sleep(1); } DebugTools.AddEvent("StepperInternalLoop.Loop", "In While. Signalling and waiting on " + (SyncContext?.GetNumberOfRemainingParticipants() - 1) + ". Total participants = " + SyncContext?.GetNumberOfTotalParticipants() + " : " + this.Name); SyncContext?.SignalAndWait(); //DebugTools.AddEvent("StepperInternalLoop.Loop", "In While. Signal received. Continuing: " + this.Name); } DebugTools.AddEvent("StepperInternalLoop.Loop", "Loop End. Signalling and waiting on " + (SyncContext?.GetNumberOfRemainingParticipants() - 1) + ". Total participants = " + SyncContext?.GetNumberOfTotalParticipants() + " : " + this.Name); SyncContext?.SignalAndWait(); //DebugTools.AddEvent("StepperInternalLoop.Loop", "Loop End. Signal received. Continuing: " + this.Name); }
/// <summary> /// <see cref="RemoteProvider.CollectNewItems"/> /// </summary> public override IEnumerable <LocalItem> CollectNewItems(SyncContext context) { return(_provider.CollectNewItems(context)); }
SyncContextTest () { ctx = new SyncContext (); wc = new WebClient (); wc.DownloadProgressChanged += HandleDownloadProgressChanged; wc.DownloadDataCompleted += HandleDownloadDataCompleted; }
public Stepper(string name, SyncContext syncContext = null) : base(name, syncContext) { Name = name; }
private void OnProgressMonitorOnChanged(object sender, EventArgs e) { SyncContext.Post(cb => ProgressUpdate(), null); }
public SyncDelegate SetContext(SyncContext context) { this.context = context; return(this); }