Example #1
0
        private void MapOptions(CliOptions opts)
        {
            ApplicationHelpers.SetConfigPath(opts.ConfigPath);
            // Actor
            if (opts.ActorIsCluster.HasValue)
            {
                ActorConfig.Instance.IsCluster = opts.ActorIsCluster.Value;
            }
            if (!string.IsNullOrWhiteSpace(opts.ActorHostName))
            {
                ActorConfig.Instance.HostName = opts.ActorHostName;
            }
            if (opts.ActorPort.HasValue)
            {
                ActorConfig.Instance.Port = opts.ActorPort.Value;
            }
            if (opts.ActorConcurrencyLevel.HasValue)
            {
                ActorConfig.Instance.ConcurrencyLevel = opts.ActorConcurrencyLevel.Value;
            }

            if (opts.IsParallelEnable.HasValue)
            {
                ParallelConfig.Instance.IsParallelEnable = opts.IsParallelEnable.Value;
            }
        }
        public void ImportApplication_InstallFails_ThrowsException()
        {
            //ARRANGE
            var clientMock = new Mock <IRSAPIClient>();

            clientMock.Setup(x => x.APIOptions).Returns(new APIOptions());
            clientMock
            .Setup(x => x.InstallApplication(It.IsAny <APIOptions>(), It.IsAny <AppInstallRequest>()))
            .Returns(new ProcessOperationResult {
                Success = false, ProcessID = Guid.NewGuid()
            });

            clientMock
            .SetupSequence(x => x.GetProcessState(It.IsAny <APIOptions>(), It.IsAny <Guid>()))
            .Returns(new ProcessInformation {
                State = ProcessStateValue.Running
            })
            .Returns(new ProcessInformation {
                State = ProcessStateValue.Completed
            });


            //ACT
            Assert.Throws <ApplicationInstallException>(() => ApplicationHelpers.ImportApplication(clientMock.Object, It.IsAny <int>(), It.IsAny <bool>(), It.IsAny <string>()));

            //ASSERT
        }
Example #3
0
        public bool SaveServiceRequestActivity()
        {
            _hpDataAccess = new HpDataAccess(_context);
            var lstSrActivity = _hpDataAccess.GetSrWithHpActivity();

            if (lstSrActivity != null && lstSrActivity.Count > 0)
            {
                var auditLog = new AuditLogEntity();
                auditLog.Module    = Constants.Module.Batch;
                auditLog.Action    = Constants.AuditAction.SubmitActivityToCARSystem;
                auditLog.IpAddress = ApplicationHelpers.GetClientIP();

                _srFacade = new ServiceRequestFacade();
                foreach (var sr in lstSrActivity)
                {
                    // TODO :: Add new parameter: AuditLogEntity for Call CAR Web Service
                    _srFacade.CreateServiceRequestActivity(auditLog, sr, true);
                    //if (result.IsSuccess == false)
                    //{
                    //    Logger.Debug(string.Format("CreateServiceRequestActivity SrId:{0} ErrorMessage:{1} WarningMessages:{2} "
                    //        , sr.SrId.Value.ToString(), result.ErrorMessage, result.WarningMessages));
                    //}
                }
            }

            return(true);
        }
Example #4
0
        public async Task <IEnumerable <TLMessage> > GetMessages(int id, long accessHash, int count, int numberOfTry = 0)
        {
            try
            {
                var inputPer = new TLInputPeerChannel()
                {
                    ChannelId  = id,
                    AccessHash = accessHash
                };
                var history = (await telegramClient.GetHistoryAsync(inputPer, limit: count));

                if (history is TLChannelMessages messages)
                {
                    return(messages.Messages.OfType <TLMessage>());
                }

                return(null);
            }
            catch (Exception ex)
            {
                ApplicationHelpers.LogException(ex);

                if (numberOfTry > 2)
                {
                    throw;
                }

                await Task.Delay(telegramSetting.DelayPerMessage);

                return(await GetMessages(id, accessHash, count, ++numberOfTry));
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="next"></param>
 public HttpHeaderMiddleware(RequestDelegate next)
 {
     this._next      = next;
     _machineName    = Environment.MachineName;
     _hostName       = Dns.GetHostName();
     _ip4AddressList = ApplicationHelpers.GetIpAddressList();
 }
Example #6
0
        /// <summary>
        /// Keeps the game alive.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param>
        private async void KeepGameAlive(object sender, ElapsedEventArgs e)
        {
            if (!this.currentGameId.Equals(Guid.Empty))
            {
                bool isGameRunning;
                try
                {
                    isGameRunning = await this.gameConsoleServiceClient.IsGameRunningAsync(this.currentGameId);
                }
                catch (ServerUnavailableException ex)
                {
                    ApplicationHelpers.HandleServerException(ex);
                    return;
                }
                catch (Exception ex)
                {
                    this.LogError(ex.Message, ex);
                    ThreadContext.InvokeOnUiThread(() => this.RunningGameDisappeared(this, null));
                    this.keepAliveTimer.Stop();
                    return;
                }

                if (isGameRunning)
                {
                    await Tracer.Debug(string.Format("Sent keepalive for the game with the id {0}. Game is still running.", this.currentGameId));
                }
                else
                {
                    await Tracer.Debug(string.Format("Sent keepalive for the game with the id {0}. Game is no longer running.", this.currentGameId));

                    ThreadContext.InvokeOnUiThread(() => this.RunningGameDisappeared(this, null));
                    this.keepAliveTimer.Stop();
                }
            }
        }
Example #7
0
        public async Task <TLChannel> GetChannelByUserName(string channelUserName, int numberOfTry = 0)
        {
            try
            {
                var channelInfos = (await telegramClient.SendRequestAsync <TLResolvedPeer>(
                                        new TLRequestResolveUsername
                {
                    Username = channelUserName
                }).ConfigureAwait(false));

                if (channelInfos.Chats.Count == 0)
                {
                    return(null);
                }

                return(channelInfos.Chats.First() as TLChannel);
            }
            catch (Exception ex)
            {
                ApplicationHelpers.LogException(ex);

                if (numberOfTry > 2)
                {
                    throw;
                }

                await Task.Delay(telegramSetting.DelayPerMessage);

                return(await GetChannelByUserName(channelUserName, ++numberOfTry));
            }
            //TLBoolTrue
        }
Example #8
0
        private static void Main(string[] args)
        {
            logger = new Logger();

            logger.LogInfo("Program started");

            NetworkChecks networkChecks = new NetworkChecks();

            serviceCheck = new ServiceCheck();

            applicationHelpers = new ApplicationHelpers();

            networkChecks.WaitForNetwork();

            CheckIfServiceAndProcessIsRunning();

            if (serviceCheck.ServiceIsRunning(ServiceCheck.MeatMasterServiceName))
            {
                logger.LogInfo("Services are running.");
            }

            CancelStartupAndCloseDown();

            Process.Start("shutdown.exe", "-r -t 0");
        }
Example #9
0
        static void Main(string[] args)
        {
            string novaPath = @"C:\Program Files (x86)\FOSS\MeatMaster II\FOSS.Nova.UI.Antonius.Core.exe";
            MeatMaster2Functions helper;

            applicationHelpers = new ApplicationHelpers();

            while (true)
            {
                applicationHelpers.StartApplication(novaPath);
                WaitForNovaWindow();
                helper = new MeatMaster2Functions();

                //helper.HandleInstrumentDiagnostic();

                helper.CancelStartup(TimeSpan.FromSeconds(60));
                helper.SelectProduct("Reference");
                helper.ClickStartStopButton();
                helper.WaitForReference();

                helper.ClickApplicationswitchButton();

                applicationHelpers.KillProcess(UiItems.MantaProcessname);
                applicationHelpers.KillProcess(MeatMaster2UiItems.Mm2ProcessName);

                Thread.Sleep(TimeSpan.FromMinutes(5));
            }
        }
Example #10
0
        public async Task <TLUser> GetByUserName(string userName, int numberOfTry = 0)
        {
            try
            {
                TLFound found = await this.telegramClient.SearchUserAsync(userName);

                var users = found.Users.OfType <TLUser>();
                if (!users.Any())
                {
                    return(null);
                }

                return(users.First());
            }
            catch (Exception ex)
            {
                ApplicationHelpers.LogException(ex);

                if (numberOfTry > 2)
                {
                    throw;
                }

                await Task.Delay(telegramSetting.DelayPerMessage);

                return(await GetByUserName(userName, ++numberOfTry));
            }

            //long hash = ((TLUser)found.Users.ToList()[0]).access_hash.Value;
            //int id = ((TeleSharp.TL.TLUser)found.users.lists[0]).id;
            //TeleSharp.TL.TLInputPeerUser peer = new TeleSharp.TL.TLInputPeerUser() { user_id = id, access_hash = hash };

            //TeleSharp.TL.TLAbsUpdates up = await this.client.SendMessageAsync(peer, "/start");
        }
Example #11
0
        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var processUIDs = _allUIds.GetRange(_batchStartIndex, _batchLength);

            Console.WriteLine("Timer Processing", processUIDs);



            Parallel.ForEach(processUIDs, async uid => {
                CustomClient client = null;
                if (MailConnectionManager.TryGetClient(out client))
                {
                    Console.WriteLine(client.Id);
                    var proxy = new MailProxy("imap.gmail.com", EncryptionType.UNENCRYPTED, ref client);
                    if (!client.Connected)
                    {
                        proxy.Login("ramankingdom", "letusc");
                    }
                    proxy.SetWorkingEmailFolder("Inbox");
                    var header = await proxy.GetEmailHeaderAsync(uid);
                    Console.WriteLine(ApplicationHelpers.ConvertBytesToString(header));
                    client.FreeClient();
                }
            }
                             );
        }
Example #12
0
        private string GetReturnUri(ActionExecutingContext filterContext)
        {
            string returnUrl;

            if (filterContext.HttpContext.Request.UrlReferrer != null)
            {
                returnUrl = filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;
            }
            else
            {
                returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery;
            }

            string decodeUrl = HttpUtility.UrlDecode(returnUrl);
            var    dic       = ApplicationHelpers.GetParams(decodeUrl);
            string callId    = filterContext.RouteData.Values["callId"].ConvertToString();

            if (_ignoreUri.Contains(decodeUrl) || decodeUrl.IsQueryStringExists("returnUrl") || !string.IsNullOrWhiteSpace(callId))
            {
                // Reset routedata
                filterContext.RouteData.Values.Remove("callId");
                filterContext.RouteData.Values.Remove("phoneNo");
                returnUrl = string.Empty;
            }
            if (dic != null && dic.ContainsKey("encryptedstring"))
            {
                returnUrl = UrlHelper.GenerateContentUrl("~/Customer/Search", filterContext.HttpContext);
            }

            return(returnUrl);
        }
        /// <summary>
        /// Ends the round.
        /// </summary>
        /// <param name="firstPlayer">if set to <c>true</c> the current round was played by the first player.</param>
        /// <param name="score">The score.</param>
        public async void EndRound(bool firstPlayer, int score)
        {
            this.currentRoundEnded = true;

            // We only want to send the end round command to the server if this was the current players turn
            if (GameManager.Current.CurrentGame.CurrentPlayer.IsLocalPlayer)
            {
                try
                {
                    GameManager.Current.LogMessage(
                        string.Format("Finished round with a score of {0}", score),
                        Tracer.Debug);

                    await GameConsoleContext.Current.GameConsoleServiceClient.EndRoundAsync(
                        GameManager.Current.CurrentGame.GameId,
                        firstPlayer,
                        score);
                }
                catch (ServerUnavailableException ex)
                {
                    ApplicationHelpers.HandleServerException(ex);
                }
                catch (Exception ex)
                {
                    this.LogError(ex);
                    this.ErrorOccurred(this, null);
                }
            }
            else if (this.currentRoundEndedEventRecieved && this.currentRoundEndedArguments != null)
            {
                // Fire the RoundEnded event if the server already sent the appropriate event
                this.OnRoundEnded(this.currentRoundEndedArguments);
            }
        }
Example #14
0
 static int Main(string[] args)
 {
     return(ApplicationHelpers
            .GenerateApplication("raffleWinner",
                                 "Prompts for the maximum number of entrants, then picks a random winner")
            .SafeExecuteApp(args));
 }
Example #15
0
        public async Task <TLSchema.Messages.TLChatFull> GetFullChatOfChannel(int id, long accessHash, int numberOfTry = 0)
        {
            try
            {
                return(await telegramClient.SendRequestAsync <TLSchema.Messages.TLChatFull>(new TLRequestGetFullChannel()
                {
                    Channel = new TLInputChannel
                    {
                        ChannelId = id,
                        AccessHash = accessHash
                    }
                }));
            }
            catch (Exception ex)
            {
                ApplicationHelpers.LogException(ex);

                if (numberOfTry > 2)
                {
                    throw;
                }

                await Task.Delay(telegramSetting.DelayPerMessage);

                return(await GetFullChatOfChannel(id, accessHash, ++numberOfTry));
            }
        }
Example #16
0
        public List <UserEntity> GetActionByName(string searchTerm, int pageSize, int pageNum, int?branchId)
        {
            var ci    = ApplicationHelpers.GetCultureInfo(Constants.KnownCulture.Thai);
            var query = GetActionQueryByName(searchTerm, branchId).OrderBy(x => x.UserId).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();

            return(query.OrderBy(x => x.FullName, StringComparer.Create(ci, true)).ToList());
        }
Example #17
0
        public dynamic GetHeaderByServiceName <T>(string serviceName)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Request Header").Add("ServiceName", serviceName).ToInputLogString());

            var       today       = DateTime.Now;
            var       appDataPath = GetProfileXml();
            XDocument doc         = XDocument.Load(appDataPath);

            dynamic result = null;
            var     query  = doc.Descendants("service").Where(x => x.Attribute("name").Value.ToUpper(CultureInfo.InvariantCulture) == serviceName.ToUpper(CultureInfo.InvariantCulture));

            if (typeof(T) == typeof(Header))
            {
                result = query.Select(x => new Header
                {
                    user_name        = x.Element("username").Value,
                    password         = x.Element("password").Value,
                    reference_no     = ApplicationHelpers.GenerateRefNo(),
                    system_code      = x.Element("system_code").Value,
                    service_name     = x.Element("service_name").Value,
                    transaction_date = today.FormatDateTime("yyyy-MM-dd"),
                    channel_id       = x.Element("channel_id").Value,
                    command          = x.Element("command").Value
                }).FirstOrDefault();
            }

            return(result);
        }
        /// <summary>
        /// Places the ball on game field.
        /// </summary>
        /// <param name="windowId">The window identifier.</param>
        /// <param name="position">The position.</param>
        public async void PlaceBallOnGameField(long windowId, Point position)
        {
            try
            {
                GameManager.Current.LogMessage(
                    string.Format(
                        "Placed ball in window with id {0} on position {1}",
                        windowId,
                        position),
                    Tracer.Debug);

                await GameConsoleContext.Current.GameConsoleServiceClient.SetStartPointAsync(
                    GameManager.Current.CurrentGame.GameId,
                    windowId,
                    position.X,
                    position.Y);
            }
            catch (ServerUnavailableException ex)
            {
                ApplicationHelpers.HandleServerException(ex);
            }
            catch (Exception ex)
            {
                this.HandleException(ex);
            }
        }
Example #19
0
        public async Task SetAsRead(int id, long accessHash, int messageId, int count, int numberOfTry = 0)
        {
            try
            {
                var ch = new TLInputChannel()
                {
                    ChannelId = id, AccessHash = accessHash
                };
                var markAsRead = new TLSchema.Channels.TLRequestReadHistory()
                {
                    Channel         = ch,
                    MaxId           = -1,
                    Dirty           = true,
                    MessageId       = messageId,
                    ConfirmReceived = true,
                    //Sequence = count
                };
                var readed = await telegramClient.SendRequestAsync <bool>(markAsRead);
            }
            catch (Exception ex)
            {
                ApplicationHelpers.LogException(ex);

                if (numberOfTry > 2)
                {
                    throw;
                }

                await Task.Delay(telegramSetting.DelayPerMessage);
                await SetAsRead(id, accessHash, messageId, ++numberOfTry);
            }
        }
Example #20
0
        public void Action(DeployArg arg)
        {
            // Todo temp solution
            ApiKeyConfig.Instance.ChainKeys.Add(arg.SideChainId, arg.ApiKey);
            var configJson = JsonSerializer.Instance.Serialize(ApiKeyConfig.Instance);

            File.WriteAllText(Path.Combine(ApplicationHelpers.GetDefaultConfigPath(), "config", "api-key.json"), configJson);
        }
Example #21
0
        public GetSRResponse GetSR(string srNo)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();

            _srFacade = new ServiceRequestFacade();
            return(_srFacade.GetSRWebService(srNo));
        }
        internal bool IsValidCardFormat()
        {
            bool isPersonCardType    = SubscriptTypeCode == Constants.SubscriptTypeCode.Personal;
            bool isValidPersonCardNo = string.IsNullOrWhiteSpace(CardNo) || ApplicationHelpers.ValidateCardNo(CardNo);
            bool valid = !isPersonCardType || isValidPersonCardNo;

            return(valid);
        }
        /// <summary> Creates a new window. </summary>
        /// <param name="logCategory"> The category of logs generated by this instance. </param>
        /// <param name="parentWindow"> The window that owns this one. </param>
        /// <param name="presenter"> The presenter to attach. </param>
        public BaseWindow(string logCategory, IBaseWindow parentWindow, IPresenter presenter)
        {
            Log   = ApplicationHelpers.CreateActiveLogger(logCategory);
            Owner = parentWindow as Window;

            Presenter = presenter;
            Presenter.SetParentWindow(this);
        }
Example #24
0
        public SearchSRResponse SearchSR(SearchSRRequest request)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();

            _srFacade = new ServiceRequestFacade();
            return(_srFacade.SearchSRWebService(request));
        }
Example #25
0
        public UpdateCalendarResponse UpdateBranchCalendar(UpdateBranchCalendarRequest request)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();

            _branchFacade = new BranchFacade();
            return(_branchFacade.UpdateBranchCalendar(request));
        }
Example #26
0
        static void Main(string[] args)
        {
            Uis myUi = new Uis();
            ApplicationHelpers applicationHelpers = new ApplicationHelpers();

            if (Uis.TryParse(args[0], out myUi))
            {
                Functions helper = new Functions(myUi);
                applicationHelpers.StartCaffeine();

                int sampleNo = 1;

                ProductList productList = helper.GetSamplesList(args);

                bool handleSampleReg = false;
                if (args.Count() > 2)
                {
                    if (!bool.TryParse(args[2], out handleSampleReg))
                    {
                        handleSampleReg = false;
                    }
                }

                while (sampleNo < productList.TotalSamples || productList.TotalSamples == 0)
                {
                    foreach (Product product in productList.Products)
                    {
                        if (!string.IsNullOrEmpty(product.Name))
                        {
                            helper.SelectProduct(product.Name);
                        }

                        for (int i = 0; i < productList.SamplesPrProduct; i++)
                        {
                            helper.ClickStartStopButton();

                            if (handleSampleReg)
                            {
                                helper.HandleSampleRegistration();
                            }


                            Console.Clear();
                            Console.WriteLine("Running Sample number {0}", sampleNo);

                            helper.WaitForSample(productList.TimeBetweenSamples);

                            sampleNo++;
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("{0} is not a valid UI, check command parameters", args[0]);
            }
        }
Example #27
0
        public CliHelper(string rpcUrl)
        {
            _keyStore           = new AElfKeyStore(ApplicationHelpers.GetDefaultDataDir());
            _accountManager     = new AccountManager(_keyStore);
            _transactionManager = new TransactionManager(_keyStore);
            _requestManager     = new RpcRequestManager(rpcUrl);
            _loadedModules      = new Dictionary <string, Module>();

            CommandList = new List <CommandInfo>();
        }
Example #28
0
        private static string PrepareDescription(string description)
        {
            if (!string.IsNullOrWhiteSpace(description))
            {
                description = description.Replace(Environment.NewLine, "");
                description = ApplicationHelpers.RemoveAllHtmlTags(description);
            }

            return(description);
        }
Example #29
0
        public CreateBranchResponse InsertOrUpdateBranch(InsertOrUpdateBranchRequest request)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();

            _branchFacade = new BranchFacade();
            var response = _branchFacade.InsertOrUpdateBranch(request);

            return(response);
        }
Example #30
0
 protected void Application_PostAcquireRequestState(object sender, EventArgs e)
 {
     if (Context.Handler is IRequiresSessionState)
     {
         log4net.ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();
         if (HttpContext.Current.User.Identity.IsAuthenticated)
         {
             log4net.ThreadContext.Properties["UserID"] = HttpContext.Current.User.Identity.Name;
         }
     }
 }