public async Task cache_many_requests()
        {
            using (var inputWriter = new QueueWriter(cacheInputFormatName))
                using (var rr = new RequestReply(cacheInputFormatName, replyFormatName, postman))
                {
                    var cachedMsg = new Message {
                        Label = "some.value.1", AppSpecific = 1
                    };
                    await inputWriter.DeliverAsync(cachedMsg, postman, QueueTransaction.None);

                    var cachedMsg2 = new Message {
                        Label = "some.value.2", AppSpecific = 2
                    };
                    await inputWriter.DeliverAsync(cachedMsg2, postman, QueueTransaction.None);

                    var sw = new Stopwatch();
                    for (int j = 0; j < 5; j++)
                    {
                        for (int i = 1; i <= 2; i++)
                        {
                            sw.Restart();
                            var request = new Message {
                                Label = "cache.some.value." + i
                            };
                            var reply = await rr.SendRequestAsync(request);

                            Console.WriteLine($"took {sw.Elapsed.TotalMilliseconds:N1}MS");
                            Assert.AreEqual("some.value." + i, reply.Label, "Label");
                            Assert.AreEqual(i, reply.AppSpecific, "AppSpecific");
                        }
                    }
                }
        }
Esempio n. 2
0
        public async Task Merge(IEnumerable <int> requestIds, string userId, bool isTechnian)
        {
            //Requests shall be merged to the lowest possible Id in the collection
            if (requestIds.Count() < 2)
            {
                throw new InvalidOperationException("At least two ids are needed in order to merge.");
            }

            // if the database does not contain one of the provied ids, throw exception
            if (requestIds.Any(r => !this.repository.All().Select(req => req.Id).Contains(r)))
            {
                throw new ArgumentException("Invalid request id has been provided.");
            }

            IEnumerable <int> ids = requestIds.SkipLast(1).ToList();
            int lastId            = requestIds.Last();

            Request requestToMergeTo = await this.repository.All().FirstOrDefaultAsync(r => r.Id == lastId);

            if (!isTechnian && requestToMergeTo.RequesterId != userId)
            {
                throw new InvalidOperationException("A user can only merge his own requests!");
            }

            foreach (var id in ids)
            {
                Request request = await this.repository.All()
                                  .Include(r => r.Attachments)
                                  .FirstOrDefaultAsync(r => r.Id == id);

                if (!isTechnian && request.RequesterId != userId)
                {
                    throw new InvalidOperationException("A user can only merge his own requests!");
                }

                RequestReply reply = new RequestReply
                {
                    RequestId   = request.Id,
                    AuthorId    = request.RequesterId,
                    Subject     = request.Subject,
                    Description = request.Description,
                };

                foreach (var attachment in request.Attachments)
                {
                    reply.Attachments.Add(new ReplyAttachment
                    {
                        PathToFile = attachment.PathToFile,
                        FileName   = attachment.FileName
                    });
                }

                requestToMergeTo.Repiles.Add(reply);
            }

            await this.DeleteRange(ids);

            await this.SaveChangesAsync();
        }
        public void TestMethod1()
        {
            RequestReply requestReply = new RequestReply(cache);
            Response     res          = requestReply.Put(777, "Hello World");

            Console.Write("Response=" + res);
            Assert.AreEqual("Response [Id=777 ResValue=Hello World]", res.ToString());
        }
Esempio n. 4
0
        public bool purge(bool include_archives)
        {
            List <string> options    = new List <string>();
            string        all_option = Strings.GetLabelString("PurgeAllRoots");
            string        question;

            if (include_archives)
            {
                question = "PurgeGameAndArchivesQuestion";
            }
            else
            {
                question = "PurgeJustGameQuestion";
            }

            options.Add(all_option);
            foreach (DetectedLocationPathHolder root in DetectedLocations)
            {
                string path;
                if (root.Path == null)
                {
                    path = root.AbsoluteRoot;
                }
                else
                {
                    path = Path.Combine(root.AbsoluteRoot, root.Path);
                }
                if (!options.Contains(path))
                {
                    options.Add(path);
                }
            }

            RequestReply info = TranslatingRequestHandler.Request(RequestType.Choice, question, options[0], options, this.Name);

            if (info.Cancelled)
            {
                return(false);
            }
            if (info.SelectedIndex == 0)
            {
                foreach (DetectedLocationPathHolder delete_me in DetectedLocations)
                {
                    delete_me.delete();
                }
            }
            else
            {
                DetectedLocations[info.SelectedOption].delete();
            }
            return(true);
        }
Esempio n. 5
0
 public bool CheckBackuptPathForMonitor()
 {
     if (!Core.settings.IsBackupPathSet)
     {
         RequestReply reply = RequestHandler.Request(RequestType.BackupFolder, false);
         if (reply.Cancelled)
         {
             TranslatingMessageHandler.SendWarning("MonitorNeedsBackupPath");
             return(false);
             //throw new TranslateableException("BackupPathNotSet");
         }
     }
     return(true);
 }
Esempio n. 6
0
 public void start()
 {
     while (!Core.settings.IsBackupPathSet && !backuppathwarned)
     {
         RequestReply reply = RequestHandler.Request(RequestType.BackupFolder, false);
         if (reply.Cancelled)
         {
             TranslatingMessageHandler.SendWarning("MonitorNeedsBackupPath");
             backuppathwarned = true;
             //throw new TranslateableException("BackupPathNotSet");
         }
     }
     this.EnableRaisingEvents = true;
 }
        public async Task cache_returns_empty_message_when_label_not_in_cache()
        {
            using (var rr = new RequestReply(cacheInputFormatName, replyFormatName, postman))
            {
                var msg = new Message {
                    Label = "cache.some.value"
                };
                var sw = new Stopwatch();
                sw.Start();
                var reply = await rr.SendRequestAsync(msg);

                Console.WriteLine($"took {sw.ElapsedMilliseconds:N0}MS");
                Assert.AreEqual(null, reply.Body, "Body");
                Assert.AreEqual("some.value", reply.Label, "Label");
            }
        }
        public async Task Merge(IEnumerable <int> requestIds)
        {
            //Requests shall be merged to the lowest possible Id in the collection
            ICollection <int> ids = requestIds.SkipLast(1).ToList();
            int lastId            = requestIds.Last();

            Request requestToMergeTo = await this.repository.All().FirstOrDefaultAsync(r => r.Id == lastId);

            if (requestToMergeTo == null)
            {
                return;
            }

            foreach (var id in ids)
            {
                Request request = await this.repository.All().Include(r => r.Attachments).FirstOrDefaultAsync(r => r.Id == id);

                if (request == null)
                {
                    ids.Remove(id);
                    continue;
                }

                RequestReply reply = new RequestReply
                {
                    RequestId   = request.Id,
                    AuthorId    = request.RequesterId,
                    Subject     = request.Subject,
                    Description = request.Description,
                };

                foreach (var attachment in request.Attachments)
                {
                    reply.Attachments.Add(new ReplyAttachment
                    {
                        PathToFile = attachment.PathToFile,
                        FileName   = attachment.FileName
                    });
                }

                requestToMergeTo.Repiles.Add(reply);
            }

            await this.SaveChangesAsync();
        }
        public void can_get_reply()
        {
            var key        = Environment.TickCount;
            var serverTask = Task.Run(() => Server(1));

            using (var rr = new RequestReply(requestQueueFormatName, replyQueueFormatName, postman))
            {
                var sw = new Stopwatch();
                sw.Start();
                var request = new Message {
                    Label = "my.sq", AppSpecific = key
                };
                var reply = rr.SendRequest(request);
                Assert.AreEqual(request.Label, reply?.Label);
                Assert.AreEqual(request.AppSpecific, reply?.AppSpecific);
                sw.Stop();
                Console.WriteLine($"took {sw.ElapsedMilliseconds:N0}ms");
            }
        }
Esempio n. 10
0
        public async Task AddReply(int requestId, string userId, bool isTechnician, string noteDescription)
        {
            Request request = await this.ById(requestId).FirstAsync();

            User author = await this.userManager.FindByIdAsync(userId);

            if (isTechnician || userId == request.RequesterId)
            {
                RequestReply reply = new RequestReply
                {
                    Subject      = $"Re: [{request.Subject}]",
                    RequestId    = requestId,
                    Description  = noteDescription,
                    CreationTime = DateTime.UtcNow,
                    Author       = author
                };

                request.Repiles.Add(reply);

                await this.SaveChangesAsync();
            }
        }
Esempio n. 11
0
        private void AddGameButton_Click(object sender, RoutedEventArgs e)
        {
            CustomGameEntry game = Games.addCustomGame(AddGameTitle.Value, new System.IO.DirectoryInfo(AddGameLocation.Value), AddGameSaves.Value, AddGameExclusions.Value);

            if (!Core.settings.SuppressSubmitRequests)
            {
                RequestReply reply = TranslatingRequestHandler.Request(RequestType.Question, "PleaseSubmitGame", true);
                if (!reply.Cancelled)
                {
                    createGameSubmission(game);
                }
                else
                {
                    if (reply.Suppressed)
                    {
                        Core.settings.SuppressSubmitRequests = true;
                    }
                }
            }
            closeAddGame(true);
            submitGame.IsEnabled = Games.HasUnsubmittedGames;
        }
Esempio n. 12
0
        public void can_get_multiple_replies()
        {
            var key        = Environment.TickCount;
            var serverTask = Task.Run(() => Server(10));

            using (var rr = new RequestReply(requestQueueFormatName, replyQueueFormatName, postman))
            {
                var sw = new Stopwatch();
                for (int i = 0; i < 10; i++)
                {
                    sw.Restart();
                    var request = new Message {
                        Label = "my.sq", AppSpecific = key + i
                    };
                    var reply = rr.SendRequest(request);
                    Assert.AreEqual(request.Label, reply?.Label);
                    Assert.AreEqual(request.AppSpecific, reply?.AppSpecific);
                    sw.Stop();
                    Console.WriteLine($"took {sw.Elapsed.TotalMilliseconds:N1}ms");
                    key++;
                }
            }
        }
Esempio n. 13
0
        private bool askAboutGame()
        {
            if (!submitPromptSuppress)
            {
                while (submitting_games.Count > 0)
                {
                    CustomGameEntry game  = submitting_games.Peek();
                    RequestReply    reply = TranslatingRequestHandler.Request(RequestType.Question, "AskSubmitGame", true, game.Title);
                    submitPromptSuppress = reply.Suppressed;
                    if (reply.Cancelled)
                    {
                        if (reply.Suppressed)
                        {
                            submitting_games.Clear();
                            return(false);
                        }
                        else
                        {
                            submitting_games.Dequeue();
                        }
                    }
                    else
                    {
                        createGameSubmission(submitting_games.Dequeue());
                        return(true);
                    }
                }
            }

            if (submitting_games.Count > 0)
            {
                createGameSubmission(submitting_games.Dequeue());
                return(true);
            }

            return(false);
        }
Esempio n. 14
0
        public async Task cache_returns_message_stored_for_label()
        {
            using (var inputWriter = new QueueWriter(cacheInputFormatName))
                using (var rr = new RequestReply(cacheInputFormatName, replyFormatName, postman))
                {
                    var cachedMsg = new Message {
                        Label = "some.value", AppSpecific = 234
                    };
                    cachedMsg.BodyASCII("hello world!");
                    await inputWriter.DeliverAsync(cachedMsg, postman, QueueTransaction.None);

                    var request = new Message {
                        Label = "cache.some.value"
                    };
                    var sw = new Stopwatch();
                    sw.Start();
                    var reply = await rr.SendRequestAsync(request);

                    Console.WriteLine($"took {sw.ElapsedMilliseconds:N0}MS");
                    Assert.AreEqual(cachedMsg.Label, reply.Label, "Label");
                    Assert.AreEqual(cachedMsg.AppSpecific, reply.AppSpecific, "AppSpecific");
                    Assert.AreEqual("hello world!", reply.BodyASCII(), "Body");
                }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            // Important: if sending multicast messages is slow you need to set the registry parameter
            // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSQM\Parameters\MulticastRateKbitsPerSec to something bigger than 560, which is the default, say 10000.

            Queues.DeleteOldTempQueues();

            var requestQueueFormatName = "multicast=224.3.9.8:234";
            var requestQueue           = new QueueWriter(requestQueueFormatName);

            var process = Process.GetCurrentProcess();
            var replyQueueFormatName = Queues.TryCreate(Queues.NewTempQueuePath(), QueueTransactional.None, label: process.ProcessName + ":" + process.Id);

            var adminQueueFormatName = Queues.TryCreate(Queues.NewTempQueuePath(), QueueTransactional.None, label: "Admin " + process.ProcessName + ":" + process.Id);

            var postman = new Postman(adminQueueFormatName)
            {
                ReachQueueTimeout = TimeSpan.FromSeconds(30)
            };

            postman.StartAsync();

            var rr = new RequestReply(requestQueueFormatName, replyQueueFormatName, postman);

            var sw = new Stopwatch();

            for (;;)
            {
                var line = Console.ReadLine();
                if (line.Length == 0)
                {
                    break;
                }

                var bits = line.Split(' ');
                switch (bits[0].ToLower())
                {
                case "get":
                {
                    var msg = new Message {
                        Label = "cache." + bits[1], ResponseQueue = replyQueueFormatName, SenderIdType = SenderIdType.None, TimeToBeReceived = TimeSpan.FromSeconds(30)
                    };
                    sw.Restart();
                    var reply = rr.SendRequest(msg);
                    sw.Stop();
                    if (reply == null)
                    {
                        Console.Error.WriteLine("*** no reply");
                    }
                    else
                    {
                        Console.WriteLine($"got {reply.Label} {reply.BodyUTF8()} in {sw.Elapsed.TotalMilliseconds:N1}MS");
                    }
                    break;
                }

                case "put":
                {
                    var msg = new Message {
                        Label = bits[1], TimeToBeReceived = TimeSpan.FromSeconds(30)
                    };
                    if (bits.Length > 2)
                    {
                        msg.BodyUTF8(bits[2]);
                    }
                    requestQueue.Deliver(msg, postman);
                    break;
                }

                case "remove":
                {
                    var msg = new Message {
                        Label = "cache." + bits[1], AppSpecific = (int)MessageCacheAction.Remove, TimeToBeReceived = TimeSpan.FromSeconds(30)
                    };
                    if (bits.Length > 2)
                    {
                        msg.BodyUTF8(bits[2]);
                    }
                    requestQueue.Deliver(msg, postman);
                    break;
                }

                case "clear":
                {
                    var msg = new Message {
                        Label = "cache", AppSpecific = (int)MessageCacheAction.Clear, TimeToBeReceived = TimeSpan.FromSeconds(30)
                    };
                    if (bits.Length > 2)
                    {
                        msg.BodyUTF8(bits[2]);
                    }
                    requestQueue.Deliver(msg, postman);
                    break;
                }

                case "list":
                {
                    var msg = new Message {
                        Label = "cache", AppSpecific = (int)MessageCacheAction.ListKeys, ResponseQueue = replyQueueFormatName, TimeToBeReceived = TimeSpan.FromSeconds(30)
                    };
                    sw.Restart();
                    var reply = rr.SendRequest(msg);
                    sw.Stop();
                    if (reply == null)
                    {
                        Console.Error.WriteLine("*** no reply");
                    }
                    else
                    {
                        Console.WriteLine(reply.BodyUTF8());
                        Console.WriteLine($"listing keys took {sw.Elapsed.TotalMilliseconds:N1}MS");
                    }
                    break;
                }

                case "puts":
                {
                    sw.Restart();
                    int max;
                    if (bits.Length == 1 || !int.TryParse(bits[1], out max))
                    {
                        max = 1000;
                    }

                    var tracking = new List <Tracking>(max);
                    for (int i = 1; i <= max; i++)
                    {
                        var msg = new Message {
                            Label = "price." + i, SenderIdType = SenderIdType.None, TimeToBeReceived = TimeSpan.FromSeconds(30)
                        };
                        msg.BodyUTF8($"bid={i-0.1m:N1},ask={i + 0.1m:N1}");
                        tracking.Add(postman.RequestDelivery(msg, requestQueue));
                    }
                    try
                    {
                        Task.WaitAll(tracking.Select(postman.WaitForDeliveryAsync).ToArray());
                        Console.WriteLine($"Sent {max} messages in {sw.Elapsed.TotalSeconds:N1} seconds");
                    }
                    catch (AggregateException ex)
                    {
                        Console.Error.WriteLine(ex.InnerException.Message);
                    }
                    break;
                }
                }
            }
        }