/// <summary> /// This bot saves the messages received in the specified file, with some filters and date/time tagging. /// </summary> /// <param name="file">The file to save the log in</param> /// <param name="filter">The kind of messages to save</param> /// <param name="AddDateAndTime">Add a date and time before each message</param> public ChatLog(string file, MessageFilter filter, bool AddDateAndTime) { dateandtime = AddDateAndTime; logfile = file; switch (filter) { case MessageFilter.AllText: saveOther = true; savePrivate = true; saveChat = true; break; case MessageFilter.AllMessages: saveOther = false; savePrivate = true; saveChat = true; break; case MessageFilter.OnlyChat: saveOther = false; savePrivate = false; saveChat = true; break; case MessageFilter.OnlyWhispers: saveOther = false; savePrivate = true; saveChat = false; break; } }
EndpointDispatcher(EndpointDispatcher baseEndpoint, IEnumerable<AddressHeader> headers) { EndpointAddressBuilder builder = new EndpointAddressBuilder(baseEndpoint.EndpointAddress); foreach (AddressHeader h in headers) { builder.Headers.Add(h); } EndpointAddress address = builder.ToEndpointAddress(); this.addressFilter = new EndpointAddressMessageFilter(address); // channelDispatcher is Attached this.contractFilter = baseEndpoint.ContractFilter; this.contractName = baseEndpoint.ContractName; this.contractNamespace = baseEndpoint.ContractNamespace; this.dispatchRuntime = baseEndpoint.DispatchRuntime; // endpointFilter is lazy this.filterPriority = baseEndpoint.FilterPriority + 1; this.originalAddress = address; if (PerformanceCounters.PerformanceCountersEnabled) { this.perfCounterId = baseEndpoint.perfCounterId; this.perfCounterBaseId = baseEndpoint.perfCounterBaseId; } this.id = baseEndpoint.id; }
public static void ClassInit(TestContext context) { _msgFilter = new MessageFilter(); var dteType = Type.GetTypeFromProgID("VisualStudio.DTE.12.0", true); _dte = (EnvDTE80.DTE2)Activator.CreateInstance(dteType, true); _testEnv = new TestEnv(); _dte.Solution.Open(_testEnv.SolutionFile); }
/// <summary> /// Adds a message filter. /// </summary> /// <param name="filter">The filter to add.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="filter" /> is <see langword="null" />. /// </exception> public void AddFilter(MessageFilter filter) { if (filter == null) { throw new ArgumentNullException("filter"); } _FILTERS.Add(filter); }
public UdpDiscoveryMessageFilter(MessageFilter innerFilter) { if (innerFilter == null) { throw FxTrace.Exception.ArgumentNull("innerFilter"); } this.innerFilter = innerFilter; }
public StrictAndMessageFilter (MessageFilter filter1, MessageFilter filter2) { if (filter1 == null) throw new ArgumentNullException ("filter1"); if (filter2 == null) throw new ArgumentNullException ("filter2"); this.filter1 = filter1; this.filter2 = filter2; }
public bool Matches(DateTime minTime, MessageFilter filter) { if (this.log.Timestamp < minTime) return false; if (this.log.Type == LogMessageType.Message && (filter & MessageFilter.TypeMessage) == MessageFilter.None) return false; if (this.log.Type == LogMessageType.Warning && (filter & MessageFilter.TypeWarning) == MessageFilter.None) return false; if (this.log.Type == LogMessageType.Error && (filter & MessageFilter.TypeError) == MessageFilter.None) return false; if (this.log.Source == Log.Core && (filter & MessageFilter.SourceCore) == MessageFilter.None) return false; if (this.log.Source == Log.Editor && (filter & MessageFilter.SourceEditor) == MessageFilter.None) return false; if (this.log.Source == Log.Game && (filter & MessageFilter.SourceGame) == MessageFilter.None) return false; return true; }
/// <summary> /// Installs a retry message filter. /// </summary> /// <param name="retryTimeout">The retry timeout.</param> /// <exception cref="InvalidOperationException">Thrown if the filter has already been installed.</exception> public static void Install(TimeSpan retryTimeout) { lock (syncRoot) { if (oldFilter != null) throw new InvalidOperationException("The retry message filter has already been installed."); newFilter = new MessageFilter(retryTimeout); NativeMethods.CoRegisterMessageFilter(newFilter, out oldFilter); } }
public static void Register() { if (null != _newFilter) return; var newFilter = new MessageFilter(); long hresult = CoRegisterMessageFilter(newFilter, out _oldFilter); if (hresult == S_OK) { _newFilter = newFilter; } }
/// <summary> /// Gets the personal messages list /// </summary> /// <param name="type">type of messages: inbox or outbox</param> /// <param name="filter">message filter. null allowed</param> /// <param name="offset">offset. null allowed</param> /// <param name="count">count messages to be returned. null allowed</param> /// <param name="previewLen">messages preview len. null allowed</param> /// <param name="timeOffset">messages time offset. null allowed</param> /// <returns>Messages list</returns> public List<Message> Get(MessageType type, MessageFilter? filter, int? offset, int? count, int? previewLen, int? timeOffset) { this.Manager.Method("messages.get"); this.Manager.Params("out", (int)type); if (filter != null) { this.Manager.Params("filters", (int)filter); } if (offset != null) { this.Manager.Params("offset", offset); } if (count != null) { this.Manager.Params("count", count); } if (previewLen != null) { this.Manager.Params("preview_length", previewLen); } if (timeOffset != null) { this.Manager.Params("time_offset", timeOffset); } string resp = this.Manager.Execute().GetResponseString(); if (this.Manager.MethodSuccessed) { XmlDocument x = this.Manager.GetXmlDocument(resp); if (x.SelectSingleNode("/response").InnerText.Equals("0")) { return null; } if (type == MessageType.Outgoing) { this.OutgoingMessagesCount = Convert.ToInt32(x.SelectSingleNode("/response/count").InnerText); } else { this.IncomingMessagesCount = Convert.ToInt32(x.SelectSingleNode("/response/count").InnerText); } switch (type) { case MessageType.History: return this.buildMessagesList(x, MessageType.History); break; case MessageType.Incoming: return this.buildMessagesList(x, MessageType.Incoming); break; case MessageType.Outgoing: return this.buildMessagesList(x, MessageType.Outgoing); break; } } return null; }
public static void ClassCleanup() { if (_dte != null) { _dte.Quit(); _dte = null; } if (_msgFilter != null) { _msgFilter.Dispose(); _msgFilter = null; } }
/// <summary> /// Gets messages filtered by different criteria. /// </summary> /// <param name="direction">Incoming\outgoing messages.</param> /// <param name="offset">Used for paged results.</param> /// <param name="count">Count of messages to return.</param> /// <param name="filter">MessageFilter to filter messages.</param> /// <param name="maxMsgLength">Max message length to load. Pass 0 to load complete messages.</param> /// <param name="timeOffset">If specified, returns messages not older than timeOffset seconds.</param> /// <returns>List of messages.</returns> public List<Message> GetList(MessageDirection direction, int? offset, int? count, MessageFilter filter, int? maxMsgLength, int? timeOffset) { var request = new Request("messages.get"); request.Parameters.Add("out", ((int)direction).ToString()); if (offset.HasValue) request.Parameters.Add("offset", offset.ToString()); if (count.HasValue) request.Parameters.Add("count", count.ToString()); if (filter != MessageFilter.None) request.Parameters.Add("filters", ((int)filter).ToString()); if (maxMsgLength.HasValue) request.Parameters.Add("preview_length", maxMsgLength.ToString()); if (timeOffset.HasValue) request.Parameters.Add("time_offset", timeOffset.ToString()); return Api.Call<MessageListResponse>(request).Messages; }
public static string filter2str(MessageFilter filter) { switch (filter) { case MessageFilter.AllMessages: return("messages"); case MessageFilter.OnlyChat: return("chat"); case MessageFilter.OnlyWhispers: return("private"); default: return("all"); } }
protected void Page_Load(object sender, EventArgs e) { MessageFilter filter = null; try { string itemGuid = Request.QueryString["ItemGuid"]; GetMessageControl(); filter = new MessageFilter(); filter.Guid = new Guid(itemGuid); var resultObj = a_control.GetMessageTrackByGuid(filter); a_result = JsonConvert.SerializeObject(resultObj); } catch (Exception) { } }
public async Task <MessageListDTO> ListDialogMessages(MessageFilter filter, int page = 0) { IQuery <MessageDTO> query = GetMessageQuery(filter); query.Skip = (page > 0 ? page - 1 : 0) * ChatMessagePageSize; query.Take = ChatMessagePageSize; query.AddSortCriteria(s => s.Time, SortDirection.Descending); return(new MessageListDTO { RequestedPage = page, ResultCount = query.GetTotalRowCount(), ResultMessages = query.Execute(), Filter = filter }); }
internal MessageFilter CreateFilter(XmlNamespaceManager xmlNamespaces, FilterElementCollection filters) { MessageFilter filter; switch (this.FilterType) { case FilterType.Action: filter = new ActionMessageFilter(this.FilterData); break; case FilterType.EndpointAddress: filter = new EndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false); break; case FilterType.PrefixEndpointAddress: filter = new PrefixEndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false); break; case FilterType.And: MessageFilter filter1 = filters[this.Filter1].CreateFilter(xmlNamespaces, filters); MessageFilter filter2 = filters[this.Filter2].CreateFilter(xmlNamespaces, filters); filter = new StrictAndMessageFilter(filter1, filter2); break; case FilterType.EndpointName: filter = new EndpointNameMessageFilter(this.FilterData); break; case FilterType.MatchAll: filter = new MatchAllMessageFilter(); break; case FilterType.Custom: filter = CreateCustomFilter(this.CustomType, this.FilterData); break; case FilterType.XPath: filter = new XPathMessageFilter(this.FilterData, xmlNamespaces); break; default: // We can't really ever get here because set_FilterType performs validation. throw FxTrace.Exception.AsError(new InvalidOperationException()); } return(filter); }
public async void Returns_ThreadOutWithMessages_when_ThreadExistsAndContainsMessages() { ThreadOut threadOut = new ThreadOut { ID = Guid.NewGuid(), Messages = new List <MessageOut>() { new MessageOut { ID = Guid.NewGuid(), SentDate = DateTime.Now }, new MessageOut { ID = Guid.NewGuid(), SentDate = DateTime.Now } } }; StatusCode <ThreadOut> status = new StatusCode <ThreadOut>(StatusCodes.Status200OK, threadOut); Mock <IMessageService> messageService = new Mock <IMessageService>(); messageService.Setup(_ => _.GetMessagesByThreadAndFilterAndUser(It.IsAny <Guid>(), It.IsAny <MessageFilter>(), It.IsAny <string>())) .Returns(Task.FromResult(status)); MessagesController messagesController = new MessagesController(messageService.Object, UserManagerHelper.GetUserManager(ADMIN_USERNAME)); messagesController.Authenticate(ADMIN_USERNAME); MessageFilter messageFilter = new MessageFilter { NumberOfLastMessage = 5 }; IActionResult result = await messagesController.GetMessagesFromThread(Guid.NewGuid(), messageFilter); Assert.NotNull(result); OkObjectResult okObjectResult = result as OkObjectResult; Assert.NotNull(okObjectResult); Assert.NotNull(okObjectResult.Value); Assert.IsType <ThreadOut>(okObjectResult.Value); Assert.Equal(2, (okObjectResult.Value as ThreadOut).Messages.Count); }
private void createAll(List <ResultItem> all, string directory, string d) { ReportFromTemplate report = new ReportFromTemplate(); report.CreateNewDucument(directory); int number = 2; int picIndex = 1; foreach (ResultItem s in allValue) { int m_iErrCnt = 0; while (s.District == d) { try { MessageFilter.Register(); report.CopyTable(); if (report.InsertInfo(ref number, s, ref picIndex, dstPath + @"\截图")) { number++; } MessageFilter.Revoke(); break; } catch (SystemException err) { m_iErrCnt++; if (m_iErrCnt < 3) { System.Threading.Thread.Sleep(1000); } else { break; } } } //if (number > 20) break; } report.deletePage(1); string output = @"D:\三个区\" + d + ".docx"; report.SaveDocument(output); }
private void method_0(ObjectId[] objectId_0) { Database workingDatabase = HostApplicationServices.WorkingDatabase; Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; ProgressMeter progressMeter = new ProgressMeter(); MessageFilter messageFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter(messageFilter); try { progressMeter.SetLimit(objectId_0.Length + 1); if ((double)objectId_0.Length > 10000.0) { progressMeter.Start("Blurring points..."); } CoordinateSystem ceometricUcs = Conversions.GetCeometricUcs(); CoordinateSystem actualCS = CoordinateSystem.Global(); CoordinateTransformator coordinateTransformator = new CoordinateTransformator(actualCS, ceometricUcs); CoordinateTransformator inverseTransformation = coordinateTransformator.GetInverseTransformation(); using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction()) { for (int i = 0; i < objectId_0.Length; i++) { DBPoint dBPoint = (DBPoint)transaction.GetObject(objectId_0[i], (OpenMode)1, true); Point point = Conversions.ToCeometricPoint(dBPoint); coordinateTransformator.Transform(point); point.X += RandomGenerator.NextDouble(-PointBlurring.double_0, PointBlurring.double_0); point.Y += RandomGenerator.NextDouble(-PointBlurring.double_0, PointBlurring.double_0); inverseTransformation.Transform(point); Point3d position = new Point3d(point.X, point.Y, point.Z); dBPoint.Position = (position); progressMeter.MeterProgress(); messageFilter.CheckMessageFilter((long)i, 1000); } transaction.Commit(); progressMeter.Stop(); editor.WriteMessage(objectId_0.Length + " points blurred."); } } catch (System.Exception ex) { progressMeter.Stop(); throw; } }
protected AbstractIntegrationTest(VisualStudioInstanceFactory instanceFactory) { Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); // Install a COM message filter to handle retry operations when the first attempt fails _messageFilter = RegisterMessageFilter(); _instanceFactory = instanceFactory; try { Helper.Automation.TransactionTimeout = 20000; } catch { _messageFilter.Dispose(); throw; } }
private void Run() { object application = GetAcadApplication(process); using (MessageFilter.Register(Stopwatch.StartNew())) { try { SendCommand(application, command); result.Complete(null); } catch (Exception e) { result.Complete(e); } } }
public bool FilterApplies(MessageFilter filter, Dictionary <string, string> contextVariables) { if (contextVariables.ContainsKey(filter.FieldName)) { var value = contextVariables[filter.FieldName]; string pattern = filter.Pattern; if (!filter.IsRegularExpression) { // wildcard filter pattern = $"^{Regex.Escape(pattern).Replace(@"\*", ".*?")}$"; } return(Regex.IsMatch(value, pattern)); } return(false); }
public void CannotFilterBasedOnNonExistantWord() { try { MessageFilter filter = new MessageFilter(); var messages = ReadMessages(); string content = "Non-Existant"; List <Message> returnMessages = filter.Filter(messages, new string[] { content }).ToList(); Assert.IsNotNull(returnMessages); Assert.AreNotEqual(messages, returnMessages); Assert.IsTrue(returnMessages.Count() == 0); } catch (MessageNotFoundException) { Assert.IsTrue(true); } }
public void FilterNumberStartsWithTest() { //Arrange List <Message> messages = new List <Message>(); messages.Add(new Message("+3801", "+38 777", $"Message #1")); messages.Add(new Message("+3802", "+38 777", $"Message #2")); messages.Add(new Message("+3802", "+38 777", $"Message #3")); messages.Add(new Message("+3803", "+38 777", $"Message #4")); messages.Add(new Message("+3802", "+38 777", $"Message #5")); string expectedResult = "+3801"; //Act MessageFilter messageFilter = new MessageFilter(); List <Message> filteredMessages = messageFilter.NumberStartsWith(messages, "+3801"); //Assert Assert.AreEqual(expectedResult, filteredMessages[0].SenderNumber); }
public void WildcardComplexMatch() { MessageFiltering filtering = new MessageFiltering(null, null); MessageFilter filter = new MessageFilter() { FieldName = "myField", IsRegularExpression = false, Pattern = "*{}:<£R$L>A*" }; Dictionary <string, string> variables = new Dictionary <string, string>() { { "myField", @"$%^IEGRSI(££%Y""NS(HG{]';lp)@:F{}:<£R$L>AW£{RQ!${L%EYLFCG{TR:{4~##" } }; Assert.True(filtering.FilterApplies(filter, variables)); }
// Umm, this API is ugly, since it or its members will // anyways require ServiceEndpoint, those arguments are // likely to be replaced by ServiceEndpoint (especially // considering about possible EndpointAddress inconsistency). public EndpointDispatcher (EndpointAddress address, string contractName, string contractNamespace) { if (contractName == null) throw new ArgumentNullException ("contractName"); if (contractNamespace == null) throw new ArgumentNullException ("contractNamespace"); if (address == null) throw new ArgumentNullException ("address"); this.address = address; contract_name = contractName; contract_ns = contractNamespace; dispatch_runtime = new DispatchRuntime (this, null); this.address_filter = new EndpointAddressMessageFilter (address); }
public void WildcardFail() { MessageFiltering filtering = new MessageFiltering(null, null); MessageFilter filter = new MessageFilter() { FieldName = "myField", IsRegularExpression = false, Pattern = "*fox jumped*" }; Dictionary <string, string> variables = new Dictionary <string, string>() { { "myField", "The quick brown fox jumps over the lazy dog." } }; Assert.False(filtering.FilterApplies(filter, variables)); }
void SetKeyboardFilter() { Trace.WriteLine("Keybd Fltr: set"); UnmanagedCode.Assert(); try { if (_filter == null) { _filter = new MessageFilter(this); } Application.AddMessageFilter(_filter); } finally { CodeAccessPermission.RevertAssert(); } }
private void UI_Load(object sender, EventArgs e) { StartServer(); InvokerMainThread = InvokeOnMainThread; var messageFilter = new MessageFilter(); Application.AddMessageFilter(messageFilter); GUI = new ServerGameUI(this, messageFilter, true) { TopLevel = false, ControlBox = false, Bounds = new Rectangle(0, 0, panelGameUI.Width, panelGameUI.Height), Dock = DockStyle.Fill }; panelGameUI.Controls.Add(GUI); // Decomment these lines when at the final version GUI.Show(); //GUI.Controller.EnableDrawing = false; }
public void RegExFail() { MessageFiltering filtering = new MessageFiltering(null, null); MessageFilter filter = new MessageFilter() { FieldName = "myField", IsRegularExpression = true, Pattern = "^[0-9]+$" }; Dictionary <string, string> variables = new Dictionary <string, string>() { { "myField", "A123" }, { "otherField", "ABC" } }; Assert.False(filtering.FilterApplies(filter, variables)); }
/// <summary> /// Run a second message pump that will filter messages asyncronously /// </summary> /// <param name="provideHandle">A delegate that provide a window handle for /// resource initializing</param> /// <param name="messageFilter">A delegate for message filtering</param> /// <param name="cleanResources">A delegate for proper resource cleaning /// before quitting the loop</param> /// <param name="background">State if the loop should be run on a background /// thread or not. If background = false, please be aware of the /// possible race conditions on application shut-down.</param> public MessageLoop(HandleProvider initializeResources, MessageFilter messageFilter, HandleProvider cleanResources, bool background) { _Lock = new Object(); _ResourceCleaner = cleanResources; _Completion = new ManualResetEvent(false); _Disposed = false; Thread thread = new Thread(delegate() { _ApplicationContext = new ApplicationContext(); Form form = new Form(); initializeResources(form.Handle); _MessageFilter = new CustomMessageFilter(messageFilter); Application.AddMessageFilter(_MessageFilter); // Signal resources initalizated _Completion.Set(); // If background = true, do resource cleaning on ProcessExit event if (background) { AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); } // Run the message loop Application.Run(_ApplicationContext); // Clean resource before leaving the thread cleanResources(form.Handle); // Signal resources cleaned _Completion.Set(); }); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = background; thread.Start(); // Before returning the instace, wait for thread resources initialization _Completion.WaitOne(); }
/// <summary> /// Called when the add-in is about to be unloaded. /// </summary> private void ThisAddIn_Shutdown(object sender, EventArgs e) { if (!MessageFilter.Revoke()) { SyncServiceTrace.W("Failed to unregister message handler"); } Settings.Default.Save(); AssemblyInit.Instance.Dispose(); AIT.TFS.SyncService.Adapter.TFS2012.AssemblyInit.Instance.Dispose(); AIT.TFS.SyncService.Adapter.Word2007.AssemblyInit.Instance.Dispose(); // Make sure the temp folder is not deleted by "Nested Adapters" when generating test reports. var counter = Process.GetProcesses().Count(process => process.ProcessName.Contains("WINWORD")); if (counter == 1) { TempFolder.ClearTempFolder(); } }
public object[] HandleRecieveMessage(string message, MessageFilter pointer, NetConnection senderConnection) { var callMessage = DeserializeCallMessage(message); var args = new object[pointer.Types.Length]; for (var i = 0; i < pointer.Types.Length; i++) { var pointerArgType = pointer.Types[i]; if (pointerArgType == typeof(NetConnection)) { args[i] = senderConnection; } else { args[i] = DeserializeArgument(callMessage.Args[i], pointerArgType); } } return(args); }
public override void Start() { DeserializationFilter deserializationFilter = new DeserializationFilter(); deserializationFilter.UseLegacyCollection = GetIsLegacyCollection(); ServiceMapFilter serviceMapFilter = new ServiceMapFilter(this); ProcessFilter processFilter = new ProcessFilter(this); MessageFilter messageFilter = new MessageFilter(this); SerializationFilter serializationFilter = new SerializationFilter(); serializationFilter.UseLegacyCollection = GetIsLegacyCollection(); deserializationFilter.Next = serviceMapFilter; serviceMapFilter.Next = processFilter; processFilter.Next = messageFilter; messageFilter.Next = serializationFilter; _filterChain = new FilterChain(deserializationFilter); }
/// <summary> /// Filter /// </summary> /// <param name="filter"></param> /// <param name="pagination"></param> /// <returns></returns> public PagedList <Message> Filter(MessageFilter filter, PaginationParams pagination) { try { var query = _context.Messages.AsQueryable(); if (filter.Id != null) { query = query.Where(x => x.Id == filter.Id); } if (filter.UserId != null) { query = query.Where(x => x.UserId == filter.UserId); } if (filter.ConversationId != null) { query = query.Where(x => x.ConversationId == filter.ConversationId); } if (filter.CreateDateEq != null) { query = query.Where(x => x.CreateDate == filter.CreateDateEq); } if (filter.CreateDateGte != null) { query = query.Where(x => x.CreateDate >= filter.CreateDateGte); } if (filter.CreateDateLte != null) { query = query.Where(x => x.CreateDate <= filter.CreateDateLte); } return(query.ToPagedList(pagination)); } catch { throw; } }
/// <summary> /// Gets the personal messages list /// </summary> /// <param name="type">type of messages: inbox or outbox</param> /// <param name="filter">message filter. null allowed</param> /// <param name="offset">offset. null allowed</param> /// <param name="count">count messages to be returned. null allowed</param> /// <param name="previewLen">messages preview len. null allowed</param> /// <param name="timeOffset">messages time offset. null allowed</param> /// <returns>Messages list</returns> public List<Message> Get(MessageType type, MessageFilter? filter, int? offset, int? count, int? previewLen, int? timeOffset) { this.Manager.Method("messages.get", new object[] { "out", (int)type, "offset", offset, "count", count, "preview_length", previewLen, "time_offset", timeOffset }); if (filter != null) { this.Manager.Params("filters", (int)filter); } XmlDocument x = this.Manager.Execute().GetResponseXml(); if (x.InnerText.Equals("")) { this.Manager.DebugMessage(string.Format("No messages found with Type: {0}; MessageFilter: {1}; Offset: {2}", type, filter, timeOffset)); return null; } if (type == MessageType.Outgoing) { this.OutgoingMessagesCount = Convert.ToInt32(x.SelectSingleNode("/response/count").InnerText); } else { this.IncomingMessagesCount = Convert.ToInt32(x.SelectSingleNode("/response/count").InnerText); } switch (type) { case MessageType.History: return this.buildMessagesList(x, MessageType.History); //break; case MessageType.Incoming: return this.buildMessagesList(x, MessageType.Incoming); //break; case MessageType.Outgoing: return this.buildMessagesList(x, MessageType.Outgoing); //break; } return null; }
private bool IsValidMessage(DiplomaticStatus diplomaticStatus, MessageFilter filter) { if (diplomaticStatus == null) return false; switch (diplomaticStatus.Status) { case BilateralStatus.AtWar: if (IsSet(filter, MessageFilter.Enemies)) return true; break; case BilateralStatus.Peace: if (IsSet(filter, MessageFilter.Friends)) return true; break; } return false; }
/// <summary> /// This bot saves the messages received in the specified file, with some filters and date/time tagging. /// </summary> /// <param name="file">The file to save the log in</param> /// <param name="filter">The kind of messages to save</param> /// <param name="AddDateAndTime">Add a date and time before each message</param> public ChatLog(string file, MessageFilter filter, bool AddDateAndTime) { dateandtime = AddDateAndTime; logfile = file; switch (filter) { case MessageFilter.AllText: saveOther = true; savePrivate = true; saveChat = true; break; case MessageFilter.AllMessages: saveOther = false; savePrivate = true; saveChat = true; break; case MessageFilter.OnlyChat: saveOther = false; savePrivate = false; saveChat = true; break; case MessageFilter.OnlyWhispers: saveOther = false; savePrivate = true; saveChat = false; break; case MessageFilter.OnlyInternalCommands: saveOther = false; savePrivate = false; saveChat = false; saveInternal = true; break; } if (String.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { LogToConsoleTranslated("bot.chatLog.invalid_file", file); UnloadBot(); } }
/// <summary> /// 执行消息,会立刻调用对应filter的函数 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="msg"></param> public static void Send <T>(T msg) { if (isLocked /* GameSystem.instance.connection.IsLockEvent()*/) { MessageBus.Post <T>(msg); } else { MessageFilter <T> msgFilter = MessageFilter <T> .getInstance(); if (msgFilter != null && msgFilter.hanlderList.Count != 0) { for (int i = 0; i < msgFilter.hanlderList.Count; i++) { (msgFilter.hanlderList[i])(msg); } } } }
/// <summary> /// 反注册,取消监听时调用 /// </summary> /// <typeparam name="T">filter类型</typeparam> /// <param name="hanlder">取消注册的hanlder</param> public static void UnRegister <T>(MessageFilter <T> .MessageBusHanlder hanlder) { MessageFilter <T> msgFilter = MessageFilter <T> .getInstance(); if (msgFilter != null && msgFilter.hanlderList.Count > 0) { for (int i = 0; i < msgFilter.hanlderList.Count; ++i) { if (msgFilter.hanlderList.Contains(hanlder)) { msgFilter.hanlderList.Remove(hanlder); } else { return; } } } }
private static int BuildSolution(string fileName, bool convertToX86) { //Separate name of Solution string solutionName = FlatRedBall.IO.FileManager.RemovePath(fileName); //Register MessageFilter to prevent failed RPC messages MessageFilter.Register(); mInstance.Solution.Open(fileName); mInstance.Solution.SolutionBuild.SolutionConfigurations.Item("Debug").Activate(); object o = mInstance.Solution.SolutionBuild.ActiveConfiguration; if (convertToX86) { foreach (EnvDTE.Project proj in mInstance.Solution.Projects) { if (proj.ConfigurationManager == null) { continue; } System.Diagnostics.Trace.WriteLine(proj.Name); EnvDTE.Configuration config = proj.ConfigurationManager.ActiveConfiguration; EnvDTE.Property prop = config.Properties.Item("PlatformTarget"); prop.Value = "x86"; } } mInstance.Solution.SolutionBuild.Build(true); if (mInstance.Solution.SolutionBuild.LastBuildInfo == 0) { // instanceHandle.Quit(); // MessageFilter.Revoke(); return(0); } else { mInstance.MainWindow.Activate(); MessageFilter.Revoke(); return(mInstance.Solution.SolutionBuild.LastBuildInfo); } }
public Task <IMessage[]> AwaitMessagesAsync(IChannel channel, MessageFilter messageFilter = null, int maxMessages = int.MaxValue, int maxTime = 10000) { if (channel is null) { throw new System.ArgumentNullException(nameof(channel)); } TaskCompletionSource <IMessage[]> promise = new TaskCompletionSource <IMessage[]>(); Task.Run(() => { CancellationTokenSource cts = new CancellationTokenSource(); List <IMessage> result = new List <IMessage>(); Task MessageHandler(IMessage message) { if (messageFilter != null && !messageFilter(message)) { return(Task.CompletedTask); } result.Add(message); if (result.Count >= maxMessages) { cts.Cancel(); return(Task.CompletedTask); } return(Task.CompletedTask); } _client.MessageReceived += MessageHandler; _ = Task.Run(async() => { try { await Task.Delay(maxTime, cts.Token); } catch { } _client.MessageReceived -= MessageHandler; promise.TrySetResult(result.ToArray()); }); }); return(promise.Task); }
public static void TestMessageSearch() { var client = new Client(ClientUrl, timeout: int.MaxValue); try { var sw = Stopwatch.StartNew(); var loginStatus = client.Login(ClientUsername, ClientPassword, "0.0.0"); var channel = client.GetChannels("d24f9ca7-d696-4ffd-b86e-484669213fa8").Channels[0]; Console.WriteLine("Loaded Channel [{0}] in {1}ms ", channel.Name, sw.Elapsed.TotalMilliseconds.ToString("N2")); Console.WriteLine("Found {0} metadata columns: {1}", channel.Properties.MetaDataColumns.Items.Count, string.Join(",", channel.Properties.MetaDataColumns.Items.Select(x => x.Name).ToArray())); sw.Restart(); var maxMessageId = client.GetMaxMessageId(channel.Id); var filter = new MessageFilter() { MaxMessageId = maxMessageId, //Statuses = new List<string>() { "ERROR" }, //EndDate = DateTime.Now.Date.AddDays(-7), MetaDataSearch = new List <MetaDataSearchCriteria> { new MetaDataSearchCriteria { ColumnName = "PATIENT_ID", Value = new MetaDataSearchCriteriaValue("00556249"), Operator = MetaDataSearchOperator.STARTS_WITH, IgnoreCase = "true", }, }, MinMessageId = 896930, }; var messageCount = client.GetMessageCount(channel.Id, filter); Console.WriteLine("Counted {0} messages in {1}ms", messageCount, sw.Elapsed.TotalMilliseconds.ToString("N2")); sw.Restart(); var messages_nocontent = client.GetMessages(channel.Id, filter, false, 0, 51); Console.WriteLine("Loaded {0} messages in {1}ms", messages_nocontent.Messages.Count, sw.Elapsed.TotalMilliseconds.ToString("N2")); var messages_rows = messages_nocontent.Messages.SelectMany(x => x.AsFlatMessageRows()).ToArray(); } finally { client.Logout(); } }
/// <summary> /// Gets the messages. /// </summary> /// <param name="filter">The filter.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// filter - Filter cannot be null /// or /// Direction - Direction filter cannot be empty /// </exception> /// <exception cref="Eu.EDelivery.AS4.Fe.BusinessException">No messages found</exception> public async Task <MessageResult <Message> > GetMessages(MessageFilter filter) { if (filter == null) { throw new ArgumentNullException(nameof(filter), @"Filter cannot be null"); } if (filter.Direction == null) { throw new ArgumentNullException(nameof(filter.Direction), @"Direction filter cannot be empty"); } IQueryable <InMessage> inMessageQuery = context.InMessages; IQueryable <OutMessage> outMessageQuery = context.OutMessages; var inMessages = filter.Direction.Contains(Direction.Inbound) ? filter.ApplyFilter(inMessageQuery).ProjectTo <Message>(mapperConfig) : null; var outMessages = filter.Direction.Contains(Direction.Outbound) ? filter.ApplyFilter(outMessageQuery).ProjectTo <Message>(mapperConfig) : null; IQueryable <Message> result = null; if (inMessages != null && outMessages != null) { result = inMessages.Concat(outMessages); } else if (inMessages != null) { result = inMessages; } else if (outMessages != null) { result = outMessages; } if (result == null) { throw new BusinessException("No messages found"); } var returnValue = await filter.ToResult(filter.ApplyStatusFilter(result).OrderByDescending(msg => msg.InsertionTime)); UpdateHasExceptions(returnValue, await GetExceptionIds(returnValue)); return(returnValue); }
public void TestReleaseBuildIsAnyCPU() { MessageFilter.Register(); DTE2 dte2 = GetCurrent(); Assert.IsNotNull(dte2); foreach (SolutionConfiguration2 config in dte2.Solution.SolutionBuild.SolutionConfigurations) { if (config.PlatformName.Contains("Mixed Platforms") || config.PlatformName.Contains("Any CPU")) { foreach (SolutionContext context in config.SolutionContexts) { Assert.AreEqual("Any CPU", context.PlatformName, string.Format("{0} is configured {1} in {2}/{3}", context.ProjectName, context.PlatformName, config.PlatformName, config.Name)); } } } MessageFilter.Revoke(); }
public EndpointDispatcher(EndpointAddress address, string contractName, string contractNamespace, bool isSystemEndpoint) { this.originalAddress = address; this.contractName = contractName; this.contractNamespace = contractNamespace; if (address != null) { this.addressFilter = new EndpointAddressMessageFilter(address); } else { this.addressFilter = new MatchAllMessageFilter(); } this.contractFilter = new MatchAllMessageFilter(); this.dispatchRuntime = new DispatchRuntime(this); this.filterPriority = 0; this.isSystemEndpoint = isSystemEndpoint; }
public Heartbeat(Guid heartbeatId, TimeSpan interval, PublishRequest heartbeatRequest, PublishRequest successRequest, PublishRequest failureRequest, MessageFilter responseFilter, TimeSpan timeout) : this() { if (failureRequest == null) { throw new ArgumentNullException("failureRequest"); } if (heartbeatRequest == null) { throw new ArgumentNullException("heartbeatRequest"); } if (responseFilter == null) { throw new ArgumentNullException("responseFilter"); } if (interval == TimeSpan.Zero) { throw new ArgumentException("Interval must not be zero."); } if (timeout == TimeSpan.Zero) { throw new ArgumentException("Timeout must not be zero."); } HeartbeatId = heartbeatId; Interval = interval; HearbeatRequest = heartbeatRequest; SuccessRequest = successRequest; FailureRequest = failureRequest; ResponseFilter = responseFilter; Timeout = timeout; }
/// <summary> /// Initializes a new instance of the <see cref="NuGenControlReflector"/> class. /// </summary> /// <param name="serviceProvider"> /// <para>Requires:</para> /// <para><see cref="INuGenReflectedImageGenerator"/></para> /// </param> /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="serviceProvider"/> is <see langword="null"/>. /// </para> /// </exception> public NuGenControlReflector(INuGenServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } _serviceProvider = serviceProvider; _msgFilter = new MessageFilter(); _msgFilter.TargetControlPaint += _msgFilter_TargetControlPaint; this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.Selectable, false); this.BackColor = Color.Transparent; this.TabStop = false; }
// Start the filter. public static void Register() { IOleMessageFilter newFilter = new MessageFilter(); IOleMessageFilter oldFilter = null; CoRegisterMessageFilter(newFilter, out oldFilter); }
public void SetFilterFlag(MessageFilter flag, bool isSet) { if (isSet) this.DisplayFilter |= flag; else this.DisplayFilter &= ~flag; }
/// <summary>Возвращает список входящих либо исходящих личных сообщений текущего пользователя.</summary> /// <param name="out">если этот параметр равен 1, сервер вернет исходящие сообщения</param> /// <param name="filters">фильтр возвращаемых сообщений: 1 - только непрочитанные; 2 - не из чата; 4 - сообщения от друзей</param> /// <param name="preview_length">Количество символов, по которому нужно обрезать сообщение</param> /// <param name="time_offset">Максимальное время, прошедшее с момента отправки сообщения до текущего момента в секундах</param> /// <param name="offset">смещение, необходимое для выборки определенного подмножества сообщений</param> /// <param name="count">количество сообщений, которое необходимо получить (но не более 100)</param> /// <returns>Ответ сервера в XML или JSON формате.</returns> public VKResponseBase Get(System.Boolean? @out, MessageFilter? filters = null, System.Int32? preview_length = null, System.Int32? time_offset = null, System.Int32? offset = null, System.Int32? count = null) { return get(@out, offset, count, filters, preview_length, time_offset); }
/// <summary> /// Initializes a new manager on the specified form. /// </summary> /// <param name="form">The form.</param> public ThumbButtonManager(Form form) { _form = form; Application.AddMessageFilter(_filter = new MessageFilter(this)); }
/// <summary> /// Initializes a new instance of the <see cref="NuGenSketchCanvas"/> class. /// </summary> /// <param name="hWnd">Specifies the handle of the window to associate.</param> /// <param name="serviceProvider"><para>Requires:</para> /// <para><see cref="INuGenButtonStateService"/></para> /// <para><see cref="INuGenControlStateService"/></para> /// <para><see cref="INuGenButtonLayoutManager"/></para> /// <para><see cref="INuGenButtonRenderer"/></para> /// <para><see cref="INuGenComboBoxRenderer"/></para> /// <para><see cref="INuGenDirectorySelectorRenderer"/></para> /// <para><see cref="INuGenImageListService"/></para> /// <para><see cref="INuGenPanelRenderer"/></para> /// <para><see cref="INuGenProgressBarLayoutManager"/></para> /// <para><see cref="INuGenProgressBarRenderer"/></para> /// <para><see cref="INuGenScrollBarRenderer"/></para> /// <para><see cref="INuGenSwitchButtonLayoutManager"/></para> /// <para><see cref="INuGenSwitchButtonRenderer"/></para> /// <para><see cref="INuGenTextBoxRenderer"/></para> /// <para><see cref="INuGenTrackBarRenderer"/></para> /// <para><see cref="INuGenThumbnailLayoutManager"/></para> /// <para><see cref="INuGenThumbnailRenderer"/></para> /// <para><see cref="INuGenToolStripRenderer"/></para> /// <para><see cref="INuGenValueTrackerService"/></para> /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="serviceProvider"/> is <see langword="null"/>.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="hWnd"/> does not represent a window. /// </para> /// </exception> public NuGenSketchCanvas(IntPtr hWnd, INuGenServiceProvider serviceProvider) { if (!User32.IsWindow(hWnd)) { throw new ArgumentException(string.Format(Resources.Argument_InvalidHWnd, hWnd.ToInt32())); } if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } _hWnd = hWnd; _serviceProvider = serviceProvider; _painter = new Painter(this); _msgFilter = new MessageFilter(_hWnd); _msgFilter.MouseDown += _msgFilter_MouseDown; _msgFilter.MouseMove += _msgFilter_MouseMove; _msgFilter.MouseUp += _msgFilter_MouseUp; _msgFilter.Paint += _msgFilter_Paint; _showPointerTimer = new Timer(); _showPointerTimer.Interval = 50; _showPointerTimer.Tick += _showPointerTimer_Tick; }
private bool IsSet(MessageFilter value, MessageFilter test) { return (value & test) == test; }
internal static IDisposable Register(Stopwatch elapsed) { var filter = new MessageFilter(elapsed); CoRegisterMessageFilter(filter, out filter.oldFilter); return filter; }
/// <summary> /// </summary> /// <param name="disposing"> /// <see langword="true"/> to dispose both managed and unmanaged resources; /// <see langword="false"/> to dispose only unmanaged resources. /// </param> protected override void Dispose(bool disposing) { if (disposing) { if (_msgFilter != null) { _msgFilter.ReleaseHandle(); _msgFilter.MouseDown -= _msgFilter_MouseDown; _msgFilter.MouseMove -= _msgFilter_MouseMove; _msgFilter.MouseUp -= _msgFilter_MouseUp; _msgFilter.Paint -= _msgFilter_Paint; _msgFilter = null; } if (_showPointerTimer != null) { _showPointerTimer.Tick -= _showPointerTimer_Tick; _showPointerTimer.Dispose(); } } base.Dispose(disposing); }
static void Main(string[] args) { // set up a simple logging configuration XmlConfigurator.Configure(); if (!LogManager.GetRepository().Configured) Debug.Fail("Logging not configured!\n Press ignore to continue"); // MessageFilter oFilter = new MessageFilter(); System.Windows.Forms.Application.AddMessageFilter( (IMessageFilter)oFilter); // note: arguments are handled within FormMain constructor // using Environment.GetCommandLineArgs() // force CultureToUse culture if specified in config file string specifiedCulture = treeDiM.StackBuilder.Desktop.Properties.Settings.Default.CultureToUse; if (!string.IsNullOrEmpty(specifiedCulture)) { try { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(specifiedCulture); Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(specifiedCulture); } catch (Exception ex) { _log.Error(string.Format("Specified culture in config file ({0}) appears to be invalid: {1}", specifiedCulture, ex.Message)); } } // get current culture _log.Info(string.Format("Starting {0} with user culture {1}", Application.ProductName, Thread.CurrentThread.CurrentUICulture)); // set unit system UnitsManager.CurrentUnitSystem = (UnitsManager.UnitSystem)Properties.Settings.Default.UnitSystem; // file association RegisterFileType(); // initialize database with containing folder PalletSolutionDatabase.Directory = Settings.Default.PalletSolutionsPath; // *** crash reporting Application.ThreadException += (sender, threadargs) => SendCrashReport(threadargs.Exception); AppDomain.CurrentDomain.UnhandledException += (sender, threadargs) => { SendCrashReport((Exception)threadargs.ExceptionObject); Environment.Exit(0); }; // *** crash reporting Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // if this application does not need updating, // show main form Updater updater = new Updater(); if (!updater.Update()) Application.Run(new FormMain()); _log.Info("Closing " + Application.ProductName); }
void filter_CalleeBusy(object sender, MessageFilter.CalleeBusyEventArgs args) { if (args.TickCount > 2000) { var res = MessageFilter.OleUiBusyDialog.Show(this, args.TaskHandle, "Test"); if (res == MessageFilter.OleUiBusyDialog.OLEUIFlags.OLEUI_CANCEL) { args.Cancel = true; } } args.RetryDelay = 500; }
public FilteringEndpointBehavior(MessageFilter addressFilter, MessageFilter contractFilter) { this.addressFilter = addressFilter; this.contractFilter = contractFilter; }
public InputEventMessageRedirector(Control target, MessageFilter filter, params MessageType[] types) { this.redirectTo = target; this.filter = filter; this.redirectMsg = types.ToList(); }