static void Main(string[] args) { MessageHelper msg = new MessageHelper(); int result = 0; //First param can be null int hWnd = msg.getWindowId(null, "Splashy"); if (hWnd != 0) { if (args.Length > 0) { Console.WriteLine("Sending: " + args[0]); result = msg.sendWindowsStringMessage(hWnd, 0, args[0]); } else { Console.WriteLine("Nothing to send arg is not defined"); } } else { Console.WriteLine("Nothing to send - window not found"); } }
public void DetectVersion_WithCustomFieldSeparator_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH$^~\&$$$$$$$$$$2.5.1$$" }{ Consts.LineTerminator }") == Hl7Version.V251); }
public void DetectVersion_WithMultipleComponentsInPositionTwelve_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH|^~\&||||||||||2.5.1^something else||" }{ Consts.LineTerminator }") == Hl7Version.V251); }
private static int Main(string[] args) { if (!ReadOptions(args)) return R_ERR; if (opt.ShowVersion) { Console.WriteLine("Ela {0}", ElaVersionInfo.Version); return R_OK; } //var p = new ElaParser(); //var r = p.Parse(new FileInfo(opt.FileName)); //Console.WriteLine(r.Program.ToString()); //return 0; helper = new MessageHelper(opt); helper.PrintLogo(); if (!helper.ValidateOptions()) return R_ERR; if (opt.ShowHelp) { helper.PrintHelp(); return R_OK; } try { if (String.IsNullOrEmpty(opt.FileName)) { helper.PrintInteractiveModeLogo(); StartInteractiveMode(); return R_OK; } if (opt.Compile || opt.ParseOnly) { if (!CheckExists(opt.FileName)) { helper.PrintError("File '{0}' doesn't exist.", opt.FileName); return R_ERR; } return opt.Compile ? Compile() : Parse(); } else return InterpretFile(opt.FileName); } finally { if (vm != null) vm.Dispose(); } }
protected override async void SendExecute() { var user = SelectedItems.FirstOrDefault(); if (user == null) { return; } Task <MTProtoResponse <TLUpdatesBase> > task = null; if (_item is TLChannel channel) { task = ProtoService.InviteToChannelAsync(channel.ToInputChannel(), new TLVector <TLInputUserBase> { user.ToInputUser() }); } else if (_item is TLChat chat) { var count = 100; var config = CacheService.GetConfig(); if (config != null) { count = config.ForwardedCountMax; } task = ProtoService.AddChatUserAsync(chat.Id, user.ToInputUser(), count); } if (task == null) { return; } var response = await task; if (response.IsSucceeded) { NavigationService.GoBack(); if (response.Result is TLUpdates updates) { var newMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage; if (newMessage != null) { Aggregator.Publish(newMessage.Message); } var newChannelMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage; if (newChannelMessage != null) { Aggregator.Publish(newChannelMessage.Message); } } } else { if (response.Error.TypeEquals(TLErrorType.PEER_FLOOD)) { var dialog = new TLMessageDialog(); dialog.Title = "Telegram"; dialog.Message = AppResources.PeerFloodAddContact; dialog.PrimaryButtonText = "More info"; dialog.SecondaryButtonText = "OK"; var confirm = await dialog.ShowQueuedAsync(); if (confirm == ContentDialogResult.Primary) { MessageHelper.HandleTelegramUrl("t.me/SpamBot"); } } else if (response.Error.TypeEquals(TLErrorType.USERS_TOO_MUCH)) { await TLMessageDialog.ShowAsync(AppResources.UsersTooMuch, "Telegram", "OK"); } else if (response.Error.TypeEquals(TLErrorType.BOTS_TOO_MUCH)) { await TLMessageDialog.ShowAsync(AppResources.BotsTooMuch, "Telegram", "OK"); } else if (response.Error.TypeEquals(TLErrorType.USER_NOT_MUTUAL_CONTACT)) { await TLMessageDialog.ShowAsync(AppResources.UserNotMutualContact, "Telegram", "OK"); } Execute.ShowDebugMessage("channels.inviteToChannel error " + response.Error); } }
public MultiRecipientAnswer MultiSendEmailWithLocalFiles() { // Create a files list path : physical path List <string> files = new List <string>(); // Get the project path // Append the file to send and encrypt files.Add(Path.Combine(RootPath, "Files", "logo-full.png")); // Fill this list if your have memory file to encrypt and send has attachment List <FileArgs> filesArgs = null; // Configure the message body, and the subject string HTMLBody = "<strong>This is my html message</strong>"; string EmailSubject = "This is my public subject"; // Create a list of recipient. Phone number could be filled to received SMS // WARNING : the SendMethodEnum must be set to msgEmailCodeSms to received an email with a sms code to open it List <RecipientInfo> recipients = new List <RecipientInfo>(); // Please enter the email and Phone number here recipients.Add(new RecipientInfo() { Email = "*****@*****.**", Phone = "" }); // That is a password protection level string messagePassword = _globalPassword; // Define the sending mode // OnlyEmail - no additional protection, only a email need to provide the email in the recipient // msgSMSOnly - no additional protection, only a sms need to provide the phone number in the recipient // msgEmailCodeSms - send a email with a 6 digit autogenerated code by sms, need to provide the phone number and email in each in the recipient // msgSMSCodeEmail - send a SMS with a 6 digit autogenerated code by email, need to provide the phone number and email in each in the recipient SendMethodEnum sendingMode = SendMethodEnum.onlyEmail; // If set to true, will return the HTML message obfuscated, and protected, you need to send it by email // If set to false, Secure Exchanges will send the message for you bool sendMessageByMyself = true; // Received the notify by email, when the message will be read bool getNotify = true; // The culture of the message. Currently support "fr-CA" and "en-CA" string culture = "fr-CA"; //Create the message args var args = new MutliRecipientArgs( EndPointURI, TestSerialNumber, TestAPIUser, TestAPIPsw, recipients, HTMLBody, EmailSubject, messagePassword, filesArgs, sendingMode, sendMessageByMyself, true, getNotify, culture, 1, 5) { FilesPath = files }; // Call the multicecipient method MultiRecipientAnswer answer = MessageHelper.MultiRecipientMessage(args); // if the status is set to 200 the call was made successfully. See in answer.Data if the status is not 200 if (answer.Status == 200) { foreach (var a in answer.RecipientsAnswer) { // Here use a.Answer.HtmlMsg to send your email with your SMTP server // a.Answer.Guid -- this is the reference of a messageid. Keep it in your système to retreived log about this message } } else { throw new Exception($"Erreur {answer.Status}"); } return(answer); }
/// <summary> /// Perform the second step of 2-phase load. Fully initialize the entity instance. /// After processing a JDBC result set, we "resolve" all the associations /// between the entities which were instantiated and had their state /// "hydrated" into an array /// </summary> public static async Task InitializeEntityAsync(object entity, bool readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); //TODO: Should this be an InitializeEntityEventListener??? (watch out for performance!) bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; var stopWath = new Stopwatch(); if (statsEnabled) { stopWath.Start(); } IPersistenceContext persistenceContext = session.PersistenceContext; EntityEntry entityEntry = persistenceContext.GetEntry(entity); if (entityEntry == null) { throw new AssertionFailure("possible non-threadsafe access to the session"); } IEntityPersister persister = entityEntry.Persister; object id = entityEntry.Id; object[] hydratedState = entityEntry.LoadedState; if (log.IsDebugEnabled()) { log.Debug("resolving associations for {0}", MessageHelper.InfoString(persister, id, session.Factory)); } IType[] types = persister.PropertyTypes; for (int i = 0; i < hydratedState.Length; i++) { object value = hydratedState[i]; if (!Equals(LazyPropertyInitializer.UnfetchedProperty, value) && !(Equals(BackrefPropertyAccessor.Unknown, value))) { hydratedState[i] = await(types[i].ResolveIdentifierAsync(value, session, entity, cancellationToken)).ConfigureAwait(false); } } //Must occur after resolving identifiers! if (session.IsEventSource) { preLoadEvent.Entity = entity; preLoadEvent.State = hydratedState; preLoadEvent.Id = id; preLoadEvent.Persister = persister; IPreLoadEventListener[] listeners = session.Listeners.PreLoadEventListeners; for (int i = 0; i < listeners.Length; i++) { await(listeners[i].OnPreLoadAsync(preLoadEvent, cancellationToken)).ConfigureAwait(false); } } persister.SetPropertyValues(entity, hydratedState); ISessionFactoryImplementor factory = session.Factory; if (persister.HasCache && session.CacheMode.HasFlag(CacheMode.Put)) { if (log.IsDebugEnabled()) { log.Debug("adding entity to second-level cache: {0}", MessageHelper.InfoString(persister, id, session.Factory)); } object version = Versioning.GetVersion(hydratedState, persister); CacheEntry entry = new CacheEntry(hydratedState, persister, entityEntry.LoadedWithLazyPropertiesUnfetched, version, session, entity); CacheKey cacheKey = session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName); bool put = await(persister.Cache.PutAsync(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version, persister.IsVersioned ? persister.VersionType.Comparator : null, UseMinimalPuts(session, entityEntry), cancellationToken)).ConfigureAwait(false); if (put && factory.Statistics.IsStatisticsEnabled) { factory.StatisticsImplementor.SecondLevelCachePut(persister.Cache.RegionName); } } bool isReallyReadOnly = readOnly; if (!persister.IsMutable) { isReallyReadOnly = true; } else { object proxy = persistenceContext.GetProxy(entityEntry.EntityKey); if (proxy != null) { // there is already a proxy for this impl // only set the status to read-only if the proxy is read-only isReallyReadOnly = ((INHibernateProxy)proxy).HibernateLazyInitializer.ReadOnly; } } if (isReallyReadOnly) { //no need to take a snapshot - this is a //performance optimization, but not really //important, except for entities with huge //mutable property values persistenceContext.SetEntryStatus(entityEntry, Status.ReadOnly); } else { //take a snapshot TypeHelper.DeepCopy(hydratedState, persister.PropertyTypes, persister.PropertyUpdateability, hydratedState, session); persistenceContext.SetEntryStatus(entityEntry, Status.Loaded); } persister.AfterInitialize(entity, entityEntry.LoadedWithLazyPropertiesUnfetched, session); if (session.IsEventSource) { postLoadEvent.Entity = entity; postLoadEvent.Id = id; postLoadEvent.Persister = persister; IPostLoadEventListener[] listeners = session.Listeners.PostLoadEventListeners; for (int i = 0; i < listeners.Length; i++) { listeners[i].OnPostLoad(postLoadEvent); } } if (log.IsDebugEnabled()) { log.Debug("done materializing entity {0}", MessageHelper.InfoString(persister, id, session.Factory)); } if (statsEnabled) { stopWath.Stop(); factory.StatisticsImplementor.LoadEntity(persister.EntityName, stopWath.Elapsed); } }
/// <summary> /// Initializes a new instance of the <see cref="ControlManager"/> class. /// </summary> /// <param name="repository">The repository.</param> public ControlManager(DataRepository repository) : base(repository) { MessageHelper = new MessageHelper(repository); }
public static void ChangeValue(string parameter, string newValue) { MessageHelper.SendDataMessage(InstanceHelper.GetMainProcess(), "change SettingProperty \"" + parameter + "\" \"" + newValue + "\""); }
private void modifyFindRegionBtn_Click(object sender, EventArgs e) { if (currentImage == null) { MessageHelper.ShowWarning("请获取图像后再修改搜索框"); return; } if (currentFindRegionComb.SelectedItem == null) { MessageHelper.ShowWarning("请选择一个模板进行修改搜索框"); return; } ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info == null) { MessageHelper.ShowWarning("无法修改模板搜索框,请删除该模板后重新创建!"); return; } if (info.FindModelROIParam != null) { switch (info.FindModelROIParam.type) { case ROI.Line: break; case ROI.Circle: CircleParam circle = info.FindModelROIParam as CircleParam; if (circle != null) { bDrawFindROI = false; bModifyFindROI = true; displayForm.DrawCircleROI(Convert.ToInt32(circle.CircleRow), Convert.ToInt32(circle.CircleColumn), circle.Radius); } else { MessageHelper.ShowError("创建搜索框失败,请删除后再重新创建!"); } break; case ROI.Ellipse: EllipseParam ellipse = info.FindModelROIParam as EllipseParam; if (ellipse != null) { bDrawFindROI = false; bModifyFindROI = true; displayForm.DrawEllipseROI(ellipse.EllipseCenterRow, ellipse.EllipseCenterColumn, ellipse.EllipseAngle, ellipse.EllipseRadius1, ellipse.EllipseRadius2); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; case ROI.Rectangle1: Rectangle1Param rectangle1 = info.FindModelROIParam as Rectangle1Param; if (rectangle1 != null) { bDrawFindROI = false; bModifyFindROI = true; displayForm.DrawRectangle1ROI(rectangle1.RectangleStartRow, rectangle1.RectangleStartColumn, rectangle1.RectangleEndRow, rectangle1.RectangleEndColumn); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; case ROI.Rectangle2: Rectangle2Param rectangle2 = info.FindModelROIParam as Rectangle2Param; if (rectangle2 != null) { bDrawFindROI = false; bModifyFindROI = true; displayForm.DrawRectangle2ROI(rectangle2.Rectangle2CenterRow, rectangle2.Retangle2CenterColumn, rectangle2.Retangle2Angle, rectangle2.Rectangle2Length1, rectangle2.Rectangle2Length2); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; default: break; } } }
private void ModifyBtn_Click(object sender, EventArgs e) { if (CurrentModelComb.SelectedItem != null) { if (Info != null) { switch (Info.ModelROIParam.type) { case ROI.Line: break; case ROI.Circle: CircleParam circle = Info.ModelROIParam as CircleParam; if (circle != null) { bModifyModelROI = true; displayForm.DrawCircleROI(Convert.ToInt32(circle.CircleRow), Convert.ToInt32(circle.CircleColumn), circle.Radius); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; case ROI.Ellipse: EllipseParam ellipse = Info.ModelROIParam as EllipseParam; if (ellipse != null) { bModifyModelROI = true; displayForm.DrawEllipseROI(ellipse.EllipseCenterRow, ellipse.EllipseCenterColumn, ellipse.EllipseAngle, ellipse.EllipseRadius1, ellipse.EllipseRadius2); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; case ROI.Rectangle1: Rectangle1Param rectangle1 = Info.ModelROIParam as Rectangle1Param; if (rectangle1 != null) { bModifyModelROI = true; displayForm.DrawRectangle1ROI(rectangle1.RectangleStartRow, rectangle1.RectangleStartColumn, rectangle1.RectangleEndRow, rectangle1.RectangleEndColumn); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; case ROI.Rectangle2: Rectangle2Param rectangle2 = Info.ModelROIParam as Rectangle2Param; if (rectangle2 != null) { bModifyModelROI = true; displayForm.DrawRectangle2ROI(rectangle2.Rectangle2CenterRow, rectangle2.Retangle2CenterColumn, rectangle2.Retangle2Angle, rectangle2.Rectangle2Length1, rectangle2.Rectangle2Length2); } else { MessageHelper.ShowError("修改模板出现错误,请删除当前模板后重修创建"); } break; default: break; } } } }
private void DisplayForm_CircleROIEvent(int t1, int t2, double t3, object t4, object t5) { if (!bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { if (!string.IsNullOrEmpty(newModelName)) { //Create a new setting info ShapeMatchToolInfo info = new ShapeMatchToolInfo(); info.ToolName = newModelName; info.ModelROIParam = new CircleParam() { CircleRow = t1, CircleColumn = t2, Radius = t3, GraphName = newModelName }; //Create a new match tool ShapeMatchTool tool = new ShapeMatchTool(info, displayForm); if (!tool.CreateMatchTool()) { MessageHelper.ShowError("模板创建失败,请重新创建"); return; } Infos.Add(info); Tools.Add(info.ToolName, tool); CurrentModelComb.Items.Add(info.ToolName); currentFindRegionComb.Items.Add(info.ToolName); } } else if (bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { bModifyModelROI = false; if (Info != null) { CircleParam circle = Info.ModelROIParam as CircleParam; if (circle != null) { circle.CircleRow = t1; circle.CircleColumn = t2; circle.Radius = t3; } } } else if (!bModifyModelROI && !bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { info.FindModelROIParam = new CircleParam() { GraphName = currentFindRegionComb.SelectedItem.ToString(), CircleRow = t1, CircleColumn = t2, Radius = t3 }; } } else if (!bModifyModelROI && bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; bModifyFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { CircleParam circle = info.FindModelROIParam as CircleParam; if (circle != null) { circle.CircleRow = t1; circle.CircleColumn = t2; circle.Radius = t3; } } } }
private void DisplayForm_Rectangle1ROIEvent(double t1, double t2, double t3, double t4, object t5) { if (!bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { if (!string.IsNullOrEmpty(newModelName)) { //Create a new setting info ShapeMatchToolInfo info = new ShapeMatchToolInfo(); info.ToolName = newModelName; info.ModelROIParam = new Rectangle1Param() { RectangleStartRow = t1, RectangleStartColumn = t2, RectangleEndRow = t3, RectangleEndColumn = t4, GraphName = newModelName }; //Create a new match tool ShapeMatchTool tool = new ShapeMatchTool(info, displayForm); if (!tool.CreateMatchTool()) { MessageHelper.ShowError("模板创建失败,请重新创建"); return; } Infos.Add(info); Tools.Add(info.ToolName, tool); CurrentModelComb.Items.Add(info.ToolName); currentFindRegionComb.Items.Add(info.ToolName); } } else if (bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { bModifyModelROI = false; if (Info != null) { Rectangle1Param rectangle1 = Info.ModelROIParam as Rectangle1Param; if (rectangle1 != null) { rectangle1.RectangleStartRow = t1; rectangle1.RectangleStartColumn = t2; rectangle1.RectangleEndRow = t3; rectangle1.RectangleEndColumn = t4; } } } else if (!bModifyModelROI && !bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { info.FindModelROIParam = new Rectangle1Param() { GraphName = currentFindRegionComb.SelectedItem.ToString(), RectangleStartRow = t1, RectangleStartColumn = t2, RectangleEndRow = t3, RectangleEndColumn = t4, }; } } else if (!bModifyModelROI && bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; bModifyFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { Rectangle1Param rectangle1 = info.FindModelROIParam as Rectangle1Param; if (rectangle1 != null) { rectangle1.RectangleStartRow = t1; rectangle1.RectangleStartColumn = t2; rectangle1.RectangleEndRow = t3; rectangle1.RectangleEndColumn = t4; } } } }
private void DisplayForm_EllipseROIEvent(double t1, double t2, double t3, double t4, double t5) { if (!bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { if (!string.IsNullOrEmpty(newModelName)) { //Create a new setting info ShapeMatchToolInfo info = new ShapeMatchToolInfo(); info.ToolName = newModelName; info.ModelROIParam = new EllipseParam() { EllipseCenterRow = t1, EllipseCenterColumn = t2, EllipseAngle = t3, EllipseRadius1 = t4, EllipseRadius2 = t5, GraphName = newModelName }; //Create a new match tool ShapeMatchTool tool = new ShapeMatchTool(info, displayForm); if (!tool.CreateMatchTool()) { MessageHelper.ShowError("模板创建失败,请重新创建"); return; } Infos.Add(info); Tools.Add(info.ToolName, tool); CurrentModelComb.Items.Add(info.ToolName); currentFindRegionComb.Items.Add(info.ToolName); } } else if (bModifyModelROI && !bModifyFindROI && !bDrawFindROI) { bModifyModelROI = false; if (Info != null) { EllipseParam ellipse = Info.ModelROIParam as EllipseParam; if (ellipse != null) { ellipse.EllipseCenterRow = t1; ellipse.EllipseCenterColumn = t2; ellipse.EllipseAngle = t3; ellipse.EllipseRadius1 = t4; ellipse.EllipseRadius2 = t5; } } } else if (!bModifyModelROI && !bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { info.FindModelROIParam = new EllipseParam() { GraphName = currentFindRegionComb.SelectedItem.ToString(), EllipseCenterRow = t1, EllipseCenterColumn = t2, EllipseAngle = t3, EllipseRadius1 = t4, EllipseRadius2 = t5 }; } } else if (!bModifyModelROI && bModifyFindROI && bDrawFindROI) { bDrawFindROI = false; bModifyFindROI = false; ShapeMatchToolInfo info = Infos.Find(p => p.ToolName == currentFindRegionComb.SelectedItem.ToString()); if (info != null) { EllipseParam ellipse = info.FindModelROIParam as EllipseParam; if (ellipse != null) { ellipse.EllipseCenterRow = t1; ellipse.EllipseCenterColumn = t2; ellipse.EllipseAngle = t3; ellipse.EllipseRadius1 = t4; ellipse.EllipseRadius2 = t5; } } } }
public void DetectVersion_WithLessThan12Positions_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH|^~\&||||||" }{ Consts.LineTerminator }") == Hl7Version.None); }
public void DetectVersion_With250Specified_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH|^~\&||||||||||2.5.0||" }{ Consts.LineTerminator }") == Hl7Version.V250); }
private void EndLoadingCollection( LoadingCollectionEntry lce, ICollectionPersister persister, Action <CachePutData> cacheBatchingHandler, bool skipCache) { if (log.IsDebugEnabled()) { log.Debug("ending loading collection [{0}]", lce); } var persistenceContext = LoadContext.PersistenceContext; var session = persistenceContext.Session; Stopwatch stopWatch = null; if (session.Factory.Statistics.IsStatisticsEnabled) { stopWatch = Stopwatch.StartNew(); } bool hasNoQueuedOperations = lce.Collection.EndRead(persister); // warning: can cause a recursive calls! (proxy initialization) if (persister.CollectionType.HasHolder()) { persistenceContext.AddCollectionHolder(lce.Collection); } CollectionEntry ce = persistenceContext.GetCollectionEntry(lce.Collection); if (ce == null) { ce = persistenceContext.AddInitializedCollection(persister, lce.Collection, lce.Key); } else { ce.PostInitialize(lce.Collection, persistenceContext); } bool addToCache = hasNoQueuedOperations && !skipCache && persister.HasCache && session.CacheMode.HasFlag(CacheMode.Put) && // and this is not a forced initialization during flush !ce.IsDoremove; if (addToCache) { AddCollectionToCache(lce, persister, cacheBatchingHandler); } if (!hasNoQueuedOperations) { lce.Collection.ApplyQueuedOperations(); } if (log.IsDebugEnabled()) { log.Debug("collection fully initialized: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); } if (stopWatch != null) { stopWatch.Stop(); session.Factory.StatisticsImplementor.LoadCollection(persister.Role, stopWatch.Elapsed); } }
private static void RunLogic(CommandlineOptions o) { int numberOfFiles = 0; options = o; message = new MessageHelper(options); message.Verbose($"Documentation folder: {options.DocFolder}"); message.Verbose($"Verbose : {options.Verbose}"); message.Verbose($"Check structure only: {options.CheckOnly}"); message.Verbose($"Key : {options.Key}"); message.Verbose($"Location : {options.Location}"); if (string.IsNullOrEmpty(options.Key) && !options.CheckOnly) { message.Error($"ERROR: you have to have an Azure Cognitive Service key if you are not only checking the structure."); returnvalue = 1; return; } subscriptionKey = options.Key; location = string.IsNullOrEmpty(options.Location) ? DefaultLocation : options.Location; if (!Directory.Exists(options.DocFolder)) { message.Error($"ERROR: Documentation folder '{options.DocFolder}' doesn't exist."); returnvalue = 1; return; } // Here we take the root directory passed for example ./userdocs // We expect to have sub folders like ./userdocs/en ./userdocs/de, etc string rootDirectopry = options.DocFolder; var allLanguagesDirectories = FindAllRootLangauges(rootDirectopry); foreach (var langDir in allLanguagesDirectories) { // Get all the Markdown files var allMarkdowns = FindAllMarkdownFiles(langDir); // checked that the file exists in other directories foreach (var markdown in allMarkdowns) { foreach (var lgDir in allLanguagesDirectories) { if (langDir == lgDir) { continue; } var filName = markdown.Replace(langDir, lgDir); if (!File.Exists(filName)) { if (options.CheckOnly) { message.Error($"ERROR: file {filName} is missing."); numberOfFiles++; returnvalue = 1; } else { #pragma warning disable CA1308 // The langauge has to be lowercase TranslateMarkdown( markdown, langDir.Substring(langDir.Length - 2).ToLower(CultureInfo.InvariantCulture), filName, lgDir.Substring(lgDir.Length - 2).ToLower(CultureInfo.InvariantCulture)); #pragma warning restore CA1308 // The langauge has to be lowercase numberOfFiles++; } } } } } string finalOutput = $"Process finished."; if (options.CheckOnly && numberOfFiles > 0) { finalOutput += $" {numberOfFiles} missing. Please check the previous lines and create them or adjust those existing."; } else if (numberOfFiles > 0) { finalOutput += $" {numberOfFiles} translated and properly created. Please make sure to run the Markdown linter and also check the file links and images."; } Console.WriteLine(finalOutput); }
/// <summary> Add the collection to the second-level cache </summary> /// <param name="lce">The entry representing the collection to add </param> /// <param name="persister">The persister </param> /// <param name="cacheBatchingHandler">The action for handling cache batching</param> private void AddCollectionToCache(LoadingCollectionEntry lce, ICollectionPersister persister, Action <CachePutData> cacheBatchingHandler) { ISessionImplementor session = LoadContext.PersistenceContext.Session; ISessionFactoryImplementor factory = session.Factory; if (log.IsDebugEnabled()) { log.Debug("Caching collection: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); } if (!(session.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(session)) { // some filters affecting the collection are enabled on the session, so do not do the put into the cache. log.Debug("Refusing to add to cache due to enabled filters"); // todo : add the notion of enabled filters to the CacheKey to differentiate filtered collections from non-filtered; // but CacheKey is currently used for both collections and entities; would ideally need to define two separate ones; // currently this works in conjunction with the check on // DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from // cache with enabled filters). return; // EARLY EXIT!!!!! } IComparer versionComparator; object version; if (persister.IsVersioned) { versionComparator = persister.OwnerEntityPersister.VersionType.Comparator; object collectionOwner = LoadContext.PersistenceContext.GetCollectionOwner(lce.Key, persister); if (collectionOwner == null) { return; } version = LoadContext.PersistenceContext.GetEntry(collectionOwner).Version; } else { version = null; versionComparator = null; } CollectionCacheEntry entry = CollectionCacheEntry.Create(lce.Collection, persister); CacheKey cacheKey = session.GenerateCacheKey(lce.Key, persister.KeyType, persister.Role); if (persister.GetBatchSize() > 1) { cacheBatchingHandler( new CachePutData( cacheKey, persister.CacheEntryStructure.Structure(entry), version, versionComparator, factory.Settings.IsMinimalPutsEnabled && session.CacheMode != CacheMode.Refresh)); } else { bool put = persister.Cache.Put(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version, versionComparator, factory.Settings.IsMinimalPutsEnabled && session.CacheMode != CacheMode.Refresh); if (put && factory.Statistics.IsStatisticsEnabled) { factory.StatisticsImplementor.SecondLevelCachePut(persister.Cache.RegionName); } } }
public void SendSignFile() { // Create a list of recipient. Phone number could be filled to received SMS // WARNING : the SendMethodEnum must be set to msgEmailCodeSms to received an email with a sms code to open it List <RecipientInfo> recipients = new List <RecipientInfo>(); recipients.Add(new RecipientInfo() { Email = "*****@*****.**", Phone = "" }); recipients.Add(new RecipientInfo() { Email = "*****@*****.**", Phone = "" }); // Create a files list path : physical path List <string> files = new List <string>(); // The PDF File that need to be signed files.Add(Path.Combine(RootPath, "Files", "model.pdf")); /// Load the template associated with that serial number var loadTemplateAnswer = SerialHelper.LoadSignsTemplate(new LoadSignsTemplateArgs() { EndPointUri = EndPointURI, Serial = TestSerialNumber, ApiUser = TestAPIUser, ApiPassword = TestAPIPsw }); // Create a list of SignFilesRequired List <SignFilesRequired> signFiles = new List <SignFilesRequired>(); // Create a dictionnary of recipients info with FileDefinition signatures Dictionary <RecipientInfo, List <FileZoneDefinition> > recipientIndex = new Dictionary <RecipientInfo, List <FileZoneDefinition> >(); // Identify in the list of files, the file need to be signed foreach (string f in files) { // Retreived the SHA512 of file need to be signed string SHA512 = CryptoHelper.GetSHA512OfFile(f); // Add that checksum to the signFilesRequired list signFiles.Add(new SignFilesRequired() { SHA512 = SHA512 }); // Because the name of the zones defined in the template are client 1, client 2, ... int clientPos = 1; // iterate trhow the recipient to specify the defines zone for the specific file for each recipients foreach (var r in recipients) { // Validate that we found template. If no template exist, the signature will be in freemode if (loadTemplateAnswer.Status == 200 && loadTemplateAnswer.Template != null) { // Find the right Zonefiles definition for that file. We search the template by filename, because we juste saved the template with // the file name in the system // We could also find the right template by the checksum, but the checksum of the file must be identical of the template item.FileDefinition.UniqueName == SHA512 var template = loadTemplateAnswer.Template.Find(item => string.Compare(item.Name, Path.GetFileName(f), true) == 0); if (template != null) { // We add to the dictionnary the definition zone for that recipient. client 1 = recipient1, client2 = recipient2 etc ... SignHelper.AddFileZoneDefToRecipientIndex(recipientIndex, template.FileDefinition.ZonesDef, SHA512, new KeyValuePair <string, RecipientInfo>($"client {clientPos}", r)); } } clientPos++; } } // Configure the message body, and the subject string HTMLBody = "<strong>Please sign the files</strong>"; string EmailSubject = "Sign file"; string psw = "protected"; // Let you send the mail with your own smtp server bool sendWitMyOwnSMPTServer = false; //Create the message args var args = new MutliRecipientArgs( EndPointURI, TestSerialNumber, TestAPIUser, TestAPIPsw, recipients, HTMLBody, EmailSubject, psw, null, SecureExchangesSDK.SecureExchanges.SendMethodEnum.onlyEmail, sendWitMyOwnSMPTServer, true, true, "fr-CA", 1, 5) { FilesPath = files }; // Because we have some file to sign, we add them to the args // Notes that you can send files witout signature only to the first recipient, if you have multiple recipient. if (signFiles.Count > 0) { // Set the files to be sign args.FileToSign = signFiles; // If the owner of the licence need to sign the file, set the value to false. // If it's set to false, the licence owner will receive an email when the file will be ready to sign by him args.OwnerDontNeedToSign = true; // Set the recipient zone definition args.SignRecipientsZoneDef = SignHelper.ConvertRecipientIndexToList(recipientIndex); } // Call the multicecipient method MultiRecipientAnswer answer = MessageHelper.MultiRecipientMessage(args); if (answer.Status == 200) { foreach (var a in answer.RecipientsAnswer) { // Here use a.Answer.HtmlMsg to send your email with your SMTP server // a.Answer.Guid -- this is the reference of a messageid. Keep it in your système to retreived log about this message } } else { throw new Exception($"Erreur {answer.Status}"); } }
/// <summary> /// Retrieve the collection that is being loaded as part of processing this result set. /// </summary> /// <param name="persister">The persister for the collection being requested. </param> /// <param name="key">The key of the collection being requested. </param> /// <returns> The loading collection (see discussion above). </returns> /// <remarks> /// Basically, there are two valid return values from this method:<ul> /// <li>an instance of {@link PersistentCollection} which indicates to /// continue loading the result set row data into that returned collection /// instance; this may be either an instance already associated and in the /// midst of being loaded, or a newly instantiated instance as a matching /// associated collection was not found.</li> /// <li><i>null</i> indicates to ignore the corresponding result set row /// data relating to the requested collection; this indicates that either /// the collection was found to already be associated with the persistence /// context in a fully loaded state, or it was found in a loading state /// associated with another result set processing context.</li> /// </ul> /// </remarks> public IPersistentCollection GetLoadingCollection(ICollectionPersister persister, object key) { CollectionKey collectionKey = new CollectionKey(persister, key); if (log.IsDebugEnabled()) { log.Debug("starting attempt to find loading collection [{0}]", MessageHelper.InfoString(persister.Role, key)); } LoadingCollectionEntry loadingCollectionEntry = loadContexts.LocateLoadingCollectionEntry(collectionKey); if (loadingCollectionEntry == null) { // look for existing collection as part of the persistence context IPersistentCollection collection = loadContexts.PersistenceContext.GetCollection(collectionKey); if (collection != null) { if (collection.WasInitialized) { log.Debug("collection already initialized; ignoring"); return(null); // ignore this row of results! Note the early exit } else { // initialize this collection log.Debug("collection not yet initialized; initializing"); } } else { object owner = loadContexts.PersistenceContext.GetCollectionOwner(key, persister); bool newlySavedEntity = owner != null && loadContexts.PersistenceContext.GetEntry(owner).Status != Status.Loading; if (newlySavedEntity) { // important, to account for newly saved entities in query // todo : some kind of check for new status... log.Debug("owning entity already loaded; ignoring"); return(null); } else { // create one if (log.IsDebugEnabled()) { // Do not log the resultSet as-is, it is an IEnumerable which may get enumerated by loggers. // (Serilog does that.) See #1667. log.Debug("instantiating new collection [key={0}, rs={1}]", key, resultSet.GetType()); } collection = persister.CollectionType.Instantiate(loadContexts.PersistenceContext.Session, persister, key); } } collection.BeforeInitialize(persister, -1); collection.BeginRead(); localLoadingCollectionKeys.Add(collectionKey); loadContexts.RegisterLoadingCollectionXRef(collectionKey, new LoadingCollectionEntry(resultSet, persister, key, collection)); return(collection); } else { if (loadingCollectionEntry.ResultSet == resultSet) { log.Debug("found loading collection bound to current result set processing; reading row"); return(loadingCollectionEntry.Collection); } else { // ignore this row, the collection is in process of // being loaded somewhere further "up" the stack log.Debug("collection is already being initialized; ignoring row"); return(null); } } }
public virtual void OnRefresh(RefreshEvent @event, IDictionary refreshedAlready) { IEventSource source = @event.Session; bool isTransient = !source.Contains(@event.Entity); if (source.PersistenceContext.ReassociateIfUninitializedProxy(@event.Entity)) { if (isTransient) { source.SetReadOnly(@event.Entity, source.DefaultReadOnly); } return; } object obj = source.PersistenceContext.UnproxyAndReassociate(@event.Entity); if (refreshedAlready.Contains(obj)) { log.Debug("already refreshed"); return; } EntityEntry e = source.PersistenceContext.GetEntry(obj); IEntityPersister persister; object id; if (e == null) { persister = source.GetEntityPersister(null, obj); //refresh() does not pass an entityName id = persister.GetIdentifier(obj, source.EntityMode); if (log.IsDebugEnabled) { log.Debug("refreshing transient " + MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key = source.GenerateEntityKey(id, persister); if (source.PersistenceContext.GetEntry(key) != null) { throw new PersistentObjectException("attempted to refresh transient instance when persistent instance was already associated with the Session: " + MessageHelper.InfoString(persister, id, source.Factory)); } } else { if (log.IsDebugEnabled) { log.Debug("refreshing " + MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); } if (!e.ExistsInDatabase) { throw new HibernateException("this instance does not yet exist as a row in the database"); } persister = e.Persister; id = e.Id; } // cascade the refresh prior to refreshing this entity refreshedAlready[obj] = obj; new Cascade(CascadingAction.Refresh, CascadePoint.BeforeRefresh, source).CascadeOn(persister, obj, refreshedAlready); if (e != null) { EntityKey key = source.GenerateEntityKey(id, persister); source.PersistenceContext.RemoveEntity(key); if (persister.HasCollections) { new EvictVisitor(source).Process(obj, persister); } } if (persister.HasCache) { CacheKey ck = source.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName); persister.Cache.Remove(ck); } EvictCachedCollections(persister, id, source.Factory); // NH Different behavior : NH-1601 // At this point the entity need the real refresh, all elementes of collections are Refreshed, // the collection state was evicted, but the PersistentCollection (in the entity state) // is associated with a possible previous session. new WrapVisitor(source).Process(obj, persister); string previousFetchProfile = source.FetchProfile; source.FetchProfile = "refresh"; object result = persister.Load(id, obj, @event.LockMode, source); if (result != null) { if (!persister.IsMutable) { source.SetReadOnly(result, true); } else { source.SetReadOnly(result, (e == null ? source.DefaultReadOnly : e.IsReadOnly)); } } source.FetchProfile = previousFetchProfile; // NH Different behavior : we are ignoring transient entities without throw any kind of exception // because a transient entity is "self refreshed" if (!ForeignKeys.IsTransient(persister.EntityName, obj, result == null, @event.Session)) { UnresolvableObjectException.ThrowIfNull(result, id, persister.EntityName); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ConfigBLL configBll = new ConfigBLL(); CashierBLL cashierBll = new CashierBLL(); DeviceBLL deviceBll = new DeviceBLL(); string path = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Yunfu"; //第一次启动 if (!Directory.Exists(path))//不存在path路径 { Directory.CreateDirectory(path); } if (!File.Exists(path + "\\Cashier.xml")) { StaticData.Cashier.cashier_id = "0"; cashierBll.setConfig(StaticData.Cashier); } if (!File.Exists(path + "\\Device.xml")) { deviceBll.setConfig(StaticData.Device); } if (!File.Exists(path + "\\Config.xml")) { StaticData.Config.isPrint = "0"; StaticData.Config.isVoice = "1"; StaticData.Config.dualPrint = "1"; StaticData.Config.userLptPrint = "0"; StaticData.Config.LptName = "LPT1"; StaticData.Config.printerName = new PrintDocument().PrinterSettings.PrinterName; configBll.setConfig(StaticData.Config); } StaticData.Device = deviceBll.getConfig(); StaticData.Config = configBll.getConfig(); StaticData.Cashier = cashierBll.getConfig(); AlipayBLL ab = new AlipayBLL(); string xml = ab.verify(); try { string is_success = XMLStrHelper.GetXmlNodeByXpath(xml, "Alipay/is_success").InnerText; if (is_success == "T") { FormLogin frmLogin = new FormLogin(); frmLogin.ShowDialog(); if (frmLogin.DialogResult == DialogResult.OK) { Application.Run(new FormMain()); } else { Application.Exit(); } } else { try { string error_msg = XMLStrHelper.GetXmlNodeByXpath(xml, "Alipay/error_msg").InnerText; FormDevice frmDevice = new FormDevice(error_msg); frmDevice.ShowDialog(); } catch (Exception ex) { throw ex; } } } catch (Exception ex) { MessageHelper.ShowError("异常" + ex.Message); } }
/// <summary> /// Gets Message Part from XLANGMessage /// </summary> /// <param name="messageId"></param> /// <param name="partIndex"></param> /// <param name="xMessage"></param> /// <param name="part"></param> /// <returns></returns> private Part GetMessagePart(Guid messageId, int partIndex, XMessage xMessage, XLANGPart part) { Part prt = null; if (part != null) { prt = new Part(); prt.PartId = Guid.NewGuid(); prt.MessageId = messageId; prt.PartIndex = partIndex; prt.PartName = part.Name; prt.CharSet = "UTF-8"; if (part is PartWrapperForUserCode) { Type partWrapperType = typeof(PartWrapperForUserCode); partUnwrapMethod = partWrapperType.GetMethod("Unwrap", BindingFlags.Instance | BindingFlags.NonPublic); PartWrapperForUserCode partWrapper = (PartWrapperForUserCode)part; Microsoft.XLANGs.Core.Part xPart = (Microsoft.XLANGs.Core.Part)(partUnwrapMethod.Invoke(partWrapper, null)); if (xPart != null) { try { try { XmlDocument contentAsXmlDocument = (XmlDocument)part.RetrieveAs(typeof(XmlDocument)); if (contentAsXmlDocument != null) { prt.TextData = contentAsXmlDocument.OuterXml; prt.ContentType = "text/xml"; partType = MessageHelper.GetMessageType(contentAsXmlDocument); } } catch (Exception) { using (Stream partStream = (Stream)part.RetrieveAs(typeof(Stream))) { using (StreamReader streamReader = new StreamReader(partStream)) { prt.TextData = streamReader.ReadToEnd(); prt.ContentType = "text/plain"; partType = "FlatFile"; } } } } finally { // When the PartWrapperForUserCode is unrwapped the reference count for the // owning message is incremented, so we must release it now. xMessage.Release(); } } else { throw new Exception("Could not unwrap Part from PartWrapperForUserCode."); } } else { throw new Exception("Error constructing BizTalkMessagePart. Expected XLANGPart to be a PartWrapperForUserCode. " + part.GetType().FullName + " is not a recognized XLANGPart type."); } } return(prt); }
/// <summary> /// 保存 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveButton_Click(object sender, EventArgs e) { #region 检查 if (string.IsNullOrEmpty(ProjectId)) { MessageHelper.ShowMsg(MessageID.W000000002, MessageType.Alert, "项目"); return; } try { var total = Convert.ToDecimal(txtTotal.Text.ToString()); var used = Convert.ToDecimal(txtUsed.Text.ToString()); var transit = Convert.ToDecimal(txtTransit.Text.ToString()); if (total < 0 || used < 0 || transit < 0) { MessageBox.Show("输入金额不能低于0!"); return; } } catch { MessageBox.Show("输入的金额不符合规范!"); return; } //判断一下是修改还是新增,如果是修改,则不执行下面的代码 //liuxuexian 2017/6/30 #region if (ID.IsNullOrEmpty()) { decimal amount = GetAmount(); amount = amount - Convert.ToDecimal(txtTotal.Text.ToString()); if (amount < 0) { MessageBox.Show("超出合同金额"); return; } } #endregion #endregion DomainDLL.Cost cost = new DomainDLL.Cost(); cost.ID = ID; cost.CREATED = CREATED; cost.Explanation = txtExplanation.Text.ToString(); cost.Remaining = Convert.ToDecimal(string.IsNullOrEmpty(txtRemaining.Text.ToString()) ? "0" : txtRemaining.Text.ToString()); cost.Remark = txtRemark.Text.ToString(); cost.Tag = txtTag.Text.ToString(); cost.Total = Convert.ToDecimal(string.IsNullOrEmpty(txtTotal.Text.ToString()) ? "0" : txtTotal.Text.ToString()); cost.Transit = Convert.ToDecimal(string.IsNullOrEmpty(txtTransit.Text.ToString()) ? "0" : txtTransit.Text.ToString()); cost.Used = Convert.ToDecimal(string.IsNullOrEmpty(txtUsed.Text.ToString())?"0":txtUsed.Text.ToString()); cost.PID = ProjectId; cost.UPDATED = DateTime.Now; JsonResult json = bll.SaveCost(cost); if (!json.result) { MessageHelper.ShowRstMsg(json.result); } if (json.result) { ClearButton_Click(null, null); } DataBind(); }
private static bool ReadOptions(string[] args) { try { opt = new ElaOptions(); ConfigReader.ReadOptions(opt); var clp = new CommandLineParser(opt); clp.Parse(args); return true; } catch (ElaOptionException ex) { helper = new MessageHelper(null); helper.PrintInvalidOption(ex); return false; } }
private static async Task SearchGitHubCodeAsync(string match_codes, int page = 1, string dbstr = "") { string githubToken = ApplicationEnvironments.Site.GithubToken; string strUrl = "https://api.github.com/search/code?page=" + page + "&q=" + match_codes + "+in:file"; var res = await GetUrlBody(githubToken, strUrl); if (string.IsNullOrWhiteSpace(res)) { Console.WriteLine("Error:" + match_codes + "-" + page); return; } Console.WriteLine("INFO:" + match_codes + "-" + page); JObject jObject = JObject.Parse(res); long totalCount = Int64.Parse(jObject["total_count"].ToString()); int totalPage = (int)Math.Floor(totalCount / 30.0) + 1; Console.WriteLine(totalCount + "/" + totalPage); int itemsLength = jObject["items"].Count(); var items = jObject["items"]; Console.WriteLine(itemsLength); MongoContext context = new MongoContext(dbstr); var TabCodeModel = context.DataBase.GetCollection <CodeModel>("CodeModel"); for (int i = 0; i < itemsLength; i++) { var codeModel = new CodeModel() { url = items[i]["html_url"].ToString(), hash = items[i]["sha"].ToString(), match_codes = match_codes, path = items[i]["path"].ToString(), repository = items[i]["repository"].ToString(), }; Dictionary <string, object> dict = new Dictionary <string, object>(); dict.Add("hash", codeModel.hash); var query = new BsonDocument(dict); var oldList = TabCodeModel.FindSync <CodeModel>(query).ToList(); if (oldList.Any()) { continue; } string codeContent = await GetUrlBody(githubToken, codeModel.url); if (string.IsNullOrWhiteSpace(res)) { Console.WriteLine("Error02:" + codeModel.url); continue; } codeModel.code = codeContent; await TabCodeModel.InsertOneAsync(codeModel); string strMsg = "Codes:" + codeModel.match_codes + "" + " \nPath:" + codeModel.path + " \nURL:" + codeModel.url; MessageHelper.SendWxMsg(strMsg); } if (totalPage > page) { Console.WriteLine(totalPage + ":" + page); await SearchGitHubCodeAsync(match_codes, page + 1); } }
public void DetectVersion_WithCustomComponentSeparator_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH|$~\&||||||||||2.5.1$something else||" }{ Consts.LineTerminator }") == Hl7Version.V251); }
public virtual void OnReplicate(ReplicateEvent @event) { IEventSource source = @event.Session; if (source.PersistenceContext.ReassociateIfUninitializedProxy(@event.Entity)) { log.Debug("uninitialized proxy passed to replicate()"); return; } object entity = source.PersistenceContext.UnproxyAndReassociate(@event.Entity); if (source.PersistenceContext.IsEntryFor(entity)) { log.Debug("ignoring persistent instance passed to replicate()"); //hum ... should we cascade anyway? throw an exception? fine like it is? return; } IEntityPersister persister = source.GetEntityPersister(@event.EntityName, entity); // get the id from the object /*if ( persister.isUnsaved(entity, source) ) { * throw new TransientObjectException("transient instance passed to replicate()"); * }*/ object id = persister.GetIdentifier(entity); if (id == null) { throw new TransientObjectException("instance with null id passed to replicate()"); } ReplicationMode replicationMode = @event.ReplicationMode; object oldVersion; if (replicationMode == ReplicationMode.Exception) { //always do an INSERT, and let it fail by constraint violation oldVersion = null; } else { //what is the version on the database? oldVersion = persister.GetCurrentVersion(id, source); } if (oldVersion != null) { if (log.IsDebugEnabled) { log.Debug("found existing row for " + MessageHelper.InfoString(persister, id, source.Factory)); } // HHH-2378 object realOldVersion = persister.IsVersioned ? oldVersion : null; bool canReplicate = replicationMode.ShouldOverwriteCurrentVersion(entity, realOldVersion, persister.GetVersion(entity), persister.VersionType); if (canReplicate) { //will result in a SQL UPDATE: PerformReplication(entity, id, realOldVersion, persister, replicationMode, source); } else { //else do nothing (don't even reassociate object!) log.Debug("no need to replicate"); } //TODO: would it be better to do a refresh from db? } else { // no existing row - do an insert if (log.IsDebugEnabled) { log.Debug("no existing row, replicating new instance " + MessageHelper.InfoString(persister, id, source.Factory)); } bool regenerate = persister.IsIdentifierAssignedByInsert; // prefer re-generation of identity! EntityKey key = regenerate ? null : source.GenerateEntityKey(id, persister); PerformSaveOrReplicate(entity, key, persister, regenerate, replicationMode, source, true); } }
public void DetectVersion_WithExactly12Positions_ReturnsCorrectHl7Version() { Assert.True(MessageHelper.DetectVersion($"{ @"MSH|^~\&||||||||||2.5.1" }{ Consts.LineTerminator }") == Hl7Version.V251); }
public Message AddCustomMessage(string openid, string content, bool isNew, MessageType type, string detailInfo) { MessageHelper mh = new MessageHelper(); return(mh.AddCustomMessage(openid, content, isNew, type, detailInfo)); }
public void NewInstance_With29Specified_ReturnsCorrectHl7Version() { Assert.IsType <V290.Message>(MessageHelper.NewInstance(Hl7Version.V290)); }
public Message AddServerMessage(string content, string detailInfo, string ipStr) { MessageHelper mh = new MessageHelper(); return(mh.AddServerMessage(content, detailInfo, ipStr)); }
internal InteractiveCommands(ElaMachine machine, MessageHelper helper, ElaOptions opts) { this.machine = machine; this.helper = helper; this.opts = opts; }
public void SendSas() { var data = MessageHelper.CopyMessageHeadTo(TrunkMessageHead.S_SendSas); Send(data); }