Пример #1
0
 /// <summary>
 /// 启动Tcp服务端
 /// </summary>
 public override void Start(Func <Request, Response> func)
 {
     if (base.config == null)
     {
         throw new Exception("未设置Tcp服务端服务配置");
     }
     //设置回调函数
     base.Handle_Event = func;
     if (config.Port <= 0)
     {
         return;
     }
     svr                  = new TcpService(config.Port, config.Encoding);
     svr.Suffix           = config.Suffix;
     svr.DefaultMaxClient = config.DefaultMaxClient;
     svr.ServerStart     += new TcpService.Dlgestr(ServerStart);
     svr.ServerError     += new TcpService.Dlgestr(ServerError);
     svr.ServerStop      += new TcpService.Dlgestr(ServerStop);
     svr.ClientRecvData  += new TcpService.NetEvent(ClientRecvData);
     svr.ClientClose     += new TcpService.NetClientEvent(ClientClose);
     svr.ClientConn      += new TcpService.NetClientEvent(ClientConn);
     svr.IsHeartbeat      = config.IsHeartbeat;
     svr.Start();
     Console.WriteLine(DateTime.Now.ToString("MM-dd HH:mm:ss:fff") + " 服务器启动,开放端口:" + config.Port);
     LogHelper.Add("启动TCP通讯服务->StartService", config.Port, LogType.TcpService);
 }
Пример #2
0
        public ADC_Dummy(LogHelper log)
            : base(log)
        {
            settings = new ADC_Dummy_Settings();

            log.Add("Initializing dummy ADC");
        }
Пример #3
0
    public bool SendWhenProcessed(Election e, Person p, OnlineVoter ov, LogHelper logHelper, out string error)
    {
      // only send if they asked for it
      if (ov.EmailCodes == null || !ov.EmailCodes.Contains("p") || p.Phone.HasNoContent())
      {
        error = null;
        return false;
      }

      // proceed to send
      var phone = p.Phone;

      var text = GetSmsTemplate("BallotProcessed").FilledWithObject(new
      {
        voterName = p.C_FullNameFL,
        electionName = e.Name,
        electionType = ElectionTypeEnum.TextFor(e.ElectionType),
      });

      var ok = SendSms(phone, text, p.PersonGuid, out error);

      // error logging done at a higher level

      if (ok)
      {
        logHelper.Add("Sms: ballot was processed", false, phone);
      }

      return ok;
    }
Пример #4
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="func"></param>
        public override void Start(Func <Request, Response> func)
        {
            if (base.config == null)
            {
                throw new Exception("未设置RedisMQ监控服务配置");
            }

            base.Handle_Event = func;
            foreach (Redis item in config.redis)
            {
                RedisClient client = new RedisClient(item.dbNum, item.connectString);
                client.Subscribe(item.redisKey, (channel, value) =>
                {
                    Request req = new Request();
                    req.channel = RequestChannel.RedisMQ;
                    req.code    = item.func;
                    req.id      = Utils.GetReqId();
                    req.para    = value.ToString();
                    LogHelper.Add(req.id + "->Request", req, LogType.RedisMQ);
                    Response resp = func(req);
                    LogHelper.Add(req.id + "->Response", resp, LogType.RedisMQ);
                });
            }
            Console.WriteLine(DateTime.Now.ToString("MM-dd HH:mm:ss:fff") + " RedisMQ监控启动:" + config.redis.Count);
            LogHelper.Add("启动RedisMQ监控->RedisMQ", config.redis.Count, LogType.RedisMQ);
        }
Пример #5
0
        public bool SendVoterTestMessage(string email, out string error)
        {
            var hostSite = SettingsHelper.Get("HostSite", "");

            var html = GetEmailTemplate("TestEmail").FilledWithObject(new
            {
                when  = DateTime.Today.ToShortDateString(),
                month = DateTime.Today.ToString("MMMM"),
                hostSite,
                logo = hostSite + "/Images/LogoSideM.png",
                email
            });

            var message = new MailMessage();

            message.To.Add(email);

            // not in an election... using system From email

            var ok = SendEmail(message, html, out error);

            LogHelper.Add($"Email: Voter test message sent", true);

            return(ok);
        }
Пример #6
0
        public bool SendWhenBallotSubmitted(Person person, Election election, out string error)
        {
            var hostSite = SettingsHelper.Get("HostSite", "");

            var html = GetEmailTemplate("OnSubmit").FilledWithObject(new
            {
                hostSite,
                logo         = hostSite + "/Images/LogoSideM.png",
                name         = person.C_FullNameFL,
                electionName = election.Name,
                electionType = ElectionTypeEnum.TextFor(election.ElectionType)
            });

            var message = new MailMessage();

            message.To.Add(new MailAddress(person.Email, person.C_FullNameFL));

            var htAddress = new MailAddress(election.EmailFromAddressWithDefault, election.EmailFromNameWithDefault);

            message.From   = htAddress;
            message.Sender = htAddress;

            var ok = SendEmail(message, html, out error);

            LogHelper.Add($"Email: Ballot Submitted", false);

            return(ok);
        }
Пример #7
0
        protected virtual void DoBeforeActionExecuted(ActionExecutedContext context)
        {
            try
            {
                CurrentItem.AddItem(WebConst.ENDTIME, DateTime.Now);

                var result = context.Result;
                CurrentItem.AddItem(WebConst.RESPONSE, result);
                var      request   = context.HttpContext.Request;
                DateTime?beginTime = CurrentItem.GetItem <DateTime>(WebConst.BEGINTIME);
                var      ms        = beginTime.HasValue && beginTime.Value == null ? -1 : (long)(DateTime.Now - beginTime.Value).TotalMilliseconds;

                if (ms > ConfigItems.ApiWarningMis)
                {
                    LogHelper.Warn($"请求共耗时:{ms} ms ");
                }
                else if (ConfigItems.LogProcessOpened)
                {
                    LogHelper.Info($"请求共耗时:{ms} ms ");
                }

                LogHelper.Add($"请求耗时{ms} {request.Path}", LogLevels.ApiUrl, url: request.Path, millisecond: ms,
                              appendMessage: true);
            }
            catch
            {
            }
        }
        public Pump_Watson_Marlow_520Du(LogHelper log) : base(log)
        {
            settings = new Pump_Watson_Marlow_520Du_Settings();
            log.Add("Initializing Watson-Marlow 520Du peristalric pump");
            Tubes.Add(new PumpTubing("520R Neoprene 0.5 mm", 0.5, 0.1, 220, 0.004, 9.5));
            Tubes.Add(new PumpTubing("520R Neoprene 0.8 mm", 0.8, 0.1, 220, 0.01, 24));
            Tubes.Add(new PumpTubing("520R Neoprene 1.6 mm", 1.6, 0.1, 220, 0.04, 97));
            Tubes.Add(new PumpTubing("520R Neoprene 3.2 mm", 3.2, 0.1, 220, 0.18, 390));
            Tubes.Add(new PumpTubing("520R Neoprene 4.8 mm", 4.8, 0.1, 220, 0.4, 870));
            Tubes.Add(new PumpTubing("520R Neoprene 6.4 mm", 6.4, 0.1, 220, 0.7, 1500));
            Tubes.Add(new PumpTubing("520R Neoprene 8.0 mm", 8.0, 0.1, 220, 1.1, 2400));
            Tubes.Add(new PumpTubing("520R Neoprene 9.6 mm", 9.6, 0.1, 220, 1.6, 3500));

            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 0.5 mm", 0.5, 0.1, 220, 0.004, 9));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 0.8 mm", 0.8, 0.1, 220, 0.01, 23));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 1.6 mm", 1.6, 0.1, 220, 0.04, 92));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 3.2 mm", 3.2, 0.1, 220, 0.17, 370));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 4.8 mm", 4.8, 0.1, 220, 0.38, 830));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 6.4 mm", 6.4, 0.1, 220, 0.67, 1500));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 8.0 mm", 8.0, 0.1, 220, 1.1, 2300));
            Tubes.Add(new PumpTubing("520R Marpene/Bioprene 64 9.6 mm", 9.6, 0.1, 220, 1.5, 3300));

            Tubes.Add(new PumpTubing("520R Fluorel 1.6 mm", 1.6, 0.1, 220, 0.03, 70));
            Tubes.Add(new PumpTubing("520R Fluorel 3.2 mm", 3.2, 0.1, 220, 0.13, 280));
            Tubes.Add(new PumpTubing("520R Fluorel 4.8 mm", 4.8, 0.1, 220, 0.29, 630));
            Tubes.Add(new PumpTubing("520R Fluorel 6.4 mm", 6.4, 0.1, 220, 0.51, 1100));
            Tubes.Add(new PumpTubing("520R Fluorel 8.0 mm", 8.0, 0.1, 220, 0.8, 1800));

            Settings.ListofTubings = Tubes;
            InitTransducerChannels();
        }
Пример #9
0
        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="resp">响应对象</param>
        public void Send(Response resp)
        {
            if (resp == null)//响应为空
            {
                return;
            }
            Session client = ((TcpServiceRequest)resp.req).client;

            if (client == null)
            {
                return;
            }
            LogHelper.Add(client.Id + "->" + resp.id + "->Send", resp.para, LogType.TcpService);
            //获取IP白名单加密方式
            ClientWhite white = config.ClientWhiteList.Find(f => f.ClientIp.Split(',').Contains(client.ConnIp));

            if (white == null)
            {
                LogHelper.Add("【ERROR】" + client.ConnIp, "未在白名单找到报文", LogType.Error);
                return;
            }
            if (white.encryptType != EncryptType.Normal)
            {
                LogHelper.Add(client.Id + "->" + resp.id + "->加密获取密文", resp.para, LogType.TcpService);
            }
            resp.para = Encryption(resp.para, white);
            //返回响应
            svr.Send(client, resp.para);
        }
Пример #10
0
        public async Task <ActionResult <int> > Login(string UserName, string UserPwd)
        {
            var    list          = db.UserInfo.Where(s => s.UserName.Equals(UserName) && s.UserPwd.Equals(UserPwd)).CountAsync();
            string OperateUser   = UserName;
            string RequestMethod = HttpContext.Request.GetDisplayUrl();
            string IPAddress     = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();

            log.Add(OperateUser, "登录", RequestMethod, IPAddress);
            return(await list);
        }
Пример #11
0
        public PS_PalmSens(LogHelper log)
            : base(log)
        {
            settings = new PS_PalmSens_Settings();

            log.Add("Initializing PalmSens CoreDependencies");
            CoreDependencies.Init();

            refreshDeviceList();
        }
Пример #12
0
 /// <summary>
 /// 客户端连接事件
 /// </summary>
 /// <param name="e"></param>
 void ClientConn(Session e)
 {
     LogHelper.Add(e.Id + "->ClientConn", "IP:" + e.ConnIp + ",Port:" + e.Port, LogType.TcpService);
     //判断IP是否在白名单中
     if (config.ClientWhiteList.Where(f => f.ClientIp.Split(',').Contains(e.ConnIp)).Count() == 0)
     {
         LogHelper.Add(e.Id.ToString(), "客户端不在白名单", LogType.Error);
         svr.Close(e.Client);
         return;
     }
 }
Пример #13
0
        public JsonResult SavePool(string pool)
        {
            var electionGuid = UserSession.CurrentElectionGuid;
            var personGuid   = UserSession.VoterInElectionPersonGuid;
            var logHelper    = new LogHelper();

            var onlineVotingInfo = Db.OnlineVotingInfo
                                   .SingleOrDefault(ovi => ovi.ElectionGuid == electionGuid && ovi.PersonGuid == personGuid);

            if (onlineVotingInfo == null)
            {
                logHelper.Add("OnlineVotingInfo is null when saving pool", true);
                return(new
                {
                    Error = "Invalid request"
                }.AsJsonResult());
            }

            if (pool.HasNoContent())
            {
                // shouldn't be possible, but happened
                pool = "[]";
            }

            var now = DateTime.Now;

            if (UserSession.CurrentElection.OnlineWhenOpen <= now && UserSession.CurrentElection.OnlineWhenClose > now)
            {
                // pool is JSON string
                var newStatus = pool == "[]" ? OnlineBallotStatusEnum.New : OnlineBallotStatusEnum.Draft;
                if (newStatus != onlineVotingInfo.Status)
                {
                    onlineVotingInfo.Status = newStatus;
                }

                new OnlineVoteHelper().SetListPoolEncrypted(onlineVotingInfo, pool);

                onlineVotingInfo.WhenStatus = now;

                Db.SaveChanges();

                // okay
                return(new
                {
                    success = true,
                    newStatus = newStatus.DisplayText
                }.AsJsonResult());
            }

            return(new
            {
                Error = "Closed"
            }.AsJsonResult());
        }
Пример #14
0
        private bool SendEmailSmtp(MailMessage message, string htmlBody, out string errorMessage)
        {
            var host            = SettingsHelper.Get("SmtpHost", "localhost");
            var pickupDirectory = SettingsHelper.Get("SmtpPickupDirectory", "");
            var senderHostName  = message.Sender?.Host ?? "TallyJ";

            message.Headers.Add("Message-Id", "<{0}@{1}>".FilledWith(Guid.NewGuid(), senderHostName));

            try
            {
                var smtpUsername = SettingsHelper.Get("SmtpUsername", "");
                var credentials  = smtpUsername.HasContent()
          ? new NetworkCredential(smtpUsername, SettingsHelper.Get("SmtpPassword", ""))
          : CredentialCache.DefaultNetworkCredentials;

                using (var smtpClient = new SmtpClient
                {
                    Host = host,
                    EnableSsl = !pickupDirectory.HasContent() && SettingsHelper.Get("SmtpSecure", false),
                    Port = SettingsHelper.Get("SmtpPort", 25),
                    PickupDirectoryLocation = pickupDirectory,
                    DeliveryMethod = pickupDirectory.HasContent() ? SmtpDeliveryMethod.SpecifiedPickupDirectory : SmtpDeliveryMethod.Network,
                    Credentials = credentials,
                    Timeout = SettingsHelper.Get("SmtpTimeoutMs", 5 * 1000) // milliseconds
                })
                {
                    smtpClient.Send(message);
                    // .SendAsync does not help? the entire page is held until the operation finishes or times out
                    errorMessage = "";

                    return(true);
                }
            }
            catch (SmtpFailedRecipientsException ex)
            {
                var who = ex.InnerExceptions.Select(e => e.FailedRecipient).JoinedAsString(", ");
                var why = ex.InnerExceptions.Select(e => e.GetAllMsgs("; "));
                errorMessage = $"Email Failed for {who}: {why}";

                LogHelper.Add(errorMessage, true);
            }
            catch (SmtpFailedRecipientException ex)
            {
                errorMessage = $"Email Failed for {ex.FailedRecipient}: {ex.GetAllMsgs("; ")}";
                LogHelper.Add(errorMessage, true);
            }
            catch (Exception ex)
            {
                errorMessage = ex.GetAllMsgs("; ");
                LogHelper.Add(errorMessage, true);
            }

            return(false);
        }
Пример #15
0
        private void LoadBallots(XmlElement locationXml, Location location)
        {
            _hub.StatusUpdate("Loading for '" + location.Name + "'...");

            var locationGuid = location.LocationGuid;

            var ballotsXml = locationXml.SelectNodes("t:ballot", _nsm);

            if (ballotsXml != null)
            {
                var ballots   = new List <Ballot>();
                var votes     = new List <Vote>();
                var numLoaded = 0;
                var numToLoad = ballotsXml.Count;

                foreach (XmlElement ballotXml in ballotsXml)
                {
                    LoadBallotAndVotes(ballotXml, locationGuid, ballots, votes);

                    numLoaded++;
                    if (numLoaded == 1 || numLoaded % 10 == 0)
                    {
                        _hub.StatusUpdate("Processing {0:n0} of {1:n0} ballots ({2:n0} votes)".FilledWith(ballots.Count, numToLoad, votes.Count), true);
                    }
                }

                Db.BulkInsert(ballots);
                Db.BulkInsert(votes);
                _hub.StatusUpdate("Loaded {0:n0} ballots ({1:n0} votes)".FilledWith(ballots.Count, votes.Count));
            }

            var logsXml = locationXml.SelectNodes("t:log", _nsm);

            if (logsXml != null)
            {
                var logs = new List <C_Log>();

                foreach (XmlElement logXml in logsXml)
                {
                    LoadLog(logXml, locationGuid, logs);
                }
                //Db.SaveChanges();
                Db.BulkInsert(logs);
                _hub.StatusUpdate("Loaded {0} log entr{1}".FilledWith(logs.Count, logs.Count.Plural("ies", "y")));
            }

            var logger = new LogHelper(_electionGuid);

            logger.Add("Loaded election from file", true);
            //Db.SaveChanges();
        }
Пример #16
0
 static void Main()
 {
     Program.Log = new LogFile(LogWriterSettings.Default());
     LogHelper.Add(Program.Log);
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.START, "██╗      █████╗ ███████╗██╗   ██╗     ██████╗ ████████╗ █████╗ ██╗  ██╗██╗   ██╗ | Product Lazy Otaku");
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.EMPTY, "██║     ██╔══██╗╚══███╔╝╚██╗ ██╔╝    ██╔═══██╗╚══██╔══╝██╔══██╗██║ ██╔╝██║   ██║ | Version 1.0.0.0");
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.EMPTY, "██║     ███████║  ███╔╝  ╚████╔╝     ██║   ██║   ██║   ███████║█████╔╝ ██║   ██║ | Author  Anderson Breder");
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.EMPTY, "██║     ██╔══██║ ███╔╝    ╚██╔╝      ██║   ██║   ██║   ██╔══██║██╔═██╗ ██║   ██║ | UUID    ff5bae169281478e8de1687fdf319d82");
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.EMPTY, "███████╗██║  ██║███████╗   ██║       ╚██████╔╝   ██║   ██║  ██║██║  ██╗╚██████╔╝ | Repo    github.com/andbreder/LazyOtaku");
     LogHelper.Write(LogWriterLevel.MANDATORY, LogWriterIO.CLOSE, "╚══════╝╚═╝  ╚═╝╚══════╝   ╚═╝        ╚═════╝    ╚═╝   ╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝  | All rights reserved © 2021");
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Views.frmMain());
 }
Пример #17
0
        /// <summary>
        /// 开启定时处理监控
        /// </summary>
        /// <param name="func"></param>
        public override void Start(Func <Request, Response> func)
        {
            base.Handle_Event = func;
            if (base.config == null)
            {
                throw new Exception("未设置定时监控服务配置");
            }
            Thread Timing = new Thread(TimingMessageNotice);

            Timing.IsBackground = true;
            Timing.Start();
            Console.WriteLine(DateTime.Now.ToString("MM-dd HH:mm:ss:fff") + " 定时监控服务启动:" + config.timing.Count);
            LogHelper.Add("定时监控服务启动->TimingService", base.config.timing.Count, LogType.Timing);
        }
Пример #18
0
    public bool SendVoterTestMessage(string phone, out string error)
    {
      var hostSite = SettingsHelper.Get("HostSite", "");

      var text = GetSmsTemplate("TestSms").FilledWithObject(new
      {
        hostSite,
      });

      // this voter is not in a specific election... just testing from the voter page
      var ok = SendSms(phone, text, null, out error);

      LogHelper.Add($"Sms: Voter test message sent", true);

      return ok;
    }
Пример #19
0
        private void RunNextExperiment(int expIndex)
        {
            IExperiment exp = (IExperiment)scanMethod[expIndex];

            log.Add("Configuring " + ((ParametrizableObject)exp).Name + "...");
            enExperimentStatus expStatus = exp.Configure(null, scanMethodResultsPath);

            if ((expStatus != enExperimentStatus.OK) && (expStatus != enExperimentStatus.Idle))
            {
                log.Warning("Experiment Sequence Aborted due to exp.Configure() returning: " + expStatus);
                OnNotifyScanEnded(new ExperimentEndedEventArgs(enExperimentStatus.Error, null));
            }

            exp.NotifyExperimentDataUpdated -= Exp_NotifyExperimentDataUpdated;
            exp.NotifyExperimentDataUpdated += Exp_NotifyExperimentDataUpdated;
            exp.NotifyExperimentEnded       -= Exp_NotifyExperimentEnded;
            exp.NotifyExperimentEnded       += Exp_NotifyExperimentEnded;
            experimentRunning     = expIndex;
            experimentRunningName = (scanMethod[experimentRunning] as ParametrizableObject).Name;

            log.Add("Running " + ((ParametrizableObject)exp).Name + "...");
            expStatus = exp.Run();
            if ((expStatus != enExperimentStatus.OK) && (expStatus != enExperimentStatus.Running))
            {
                exp.NotifyExperimentDataUpdated -= Exp_NotifyExperimentDataUpdated;
                exp.NotifyExperimentEnded       -= Exp_NotifyExperimentEnded;
                try
                {
                    // just in case Experiment was started
                    exp.Abort();
                }
                catch (Exception e)
                {
                }
                log.Warning("Experiment Sequence Aborted due to exp.Run() returning: " + expStatus);
                OnNotifyScanEnded(new ExperimentEndedEventArgs(enExperimentStatus.Error, null));
            }
        }
Пример #20
0
        //    public bool SendWhenOpen(Election e, Person p, OnlineVotingInfo ovi, OnlineVoter ov, out string error)

        //    {

        //      // only send if they asked for it

        //      if (!ov.EmailCodes.Contains("o"))

        //      {

        //        error = null;

        //        return true;

        //      }

        //

        //      // proceed to send

        //      var email = ov.Email;

        //      var hostSite = SettingsHelper.Get("HostSite", "");

        //

        //      var whenClose = e.OnlineWhenClose.GetValueOrDefault();

        //      var openLength = whenClose - e.OnlineWhenOpen.GetValueOrDefault();

        //      var howLong = "";

        //      if (openLength.Days > 1)

        //      {

        //        howLong = openLength.Days + " days";

        //      }

        //      else

        //      {

        //        howLong = openLength.Hours + " hours";

        //      }

        //

        //      var html = GetEmailTemplate("BallotProcessed").FilledWithObject(new

        //      {

        //        email,

        //        voterName = p.C_FullNameFL,

        //        electionName = e.Name,

        //        electionType = ElectionTypeEnum.TextFor(e.ElectionType),

        //        hostSite,

        //        logo = hostSite + "/Images/LogoSideM.png",

        //        howLong,

        //        whenClose

        //      });

        //

        //      var message = new MailMessage();

        //      message.To.Add(new MailAddress(email, p.C_FullNameFL));

        //

        //      var memberEmail = UserSession.MemberEmail;

        //      if (memberEmail.HasContent())

        //      {

        //        message.ReplyToList.Add(new MailAddress(memberEmail, UserSession.MemberName + " (Teller)"));

        //      }

        //

        //      return SendEmail(message, html, out error);

        //    }


        public bool SendWhenProcessed(Election election, Person p, OnlineVoter ov, LogHelper logHelper, out string error)
        {
            // only send if they asked for it
            if (ov.EmailCodes == null || !ov.EmailCodes.Contains("p") || p.Email.HasNoContent())
            {
                error = null;
                return(false);
            }


            // proceed to send
            var email = p.Email;

            var hostSite = SettingsHelper.Get("HostSite", "");

            var html = GetEmailTemplate("BallotProcessed").FilledWithObject(new
            {
                email,
                voterName    = p.C_FullNameFL,
                electionName = election.Name,
                electionType = ElectionTypeEnum.TextFor(election.ElectionType),
                hostSite,
                logo = hostSite + "/Images/LogoSideM.png",
            });

            var message = new MailMessage();

            message.To.Add(new MailAddress(email, p.C_FullNameFL));

            var htAddress = new MailAddress(election.EmailFromAddressWithDefault, election.EmailFromNameWithDefault);

            message.From   = htAddress;
            message.Sender = htAddress;

            var ok = SendEmail(message, html, out error);

            if (ok)
            {
                logHelper.Add("Email: ballot was processed", false, email);
            }

            return(ok);
        }
Пример #21
0
    public bool SendWhenBallotSubmitted(Person person, Election election, out string error)
    {
      var hostSite = SettingsHelper.Get("HostSite", "");

      var text = GetSmsTemplate("OnSubmit").FilledWithObject(new
      {
        hostSite,
        logo = hostSite + "/Images/LogoSideM.png",
        name = person.C_FullNameFL,
        electionName = election.Name,
        electionType = ElectionTypeEnum.TextFor(election.ElectionType)
      });

      var ok = SendSms(person.Phone, text, person.PersonGuid, out error);

      LogHelper.Add($"Sms: Ballot Submitted", false);

      return ok;
    }
Пример #22
0
        private bool SendEmailApi(string sendGridApiKey, MailMessage message, string htmlBody, out string errorMessage)
        {
            var msg = new SendGridMessage
            {
                From        = message.From.AsSendGridEmailAddress(),
                Subject     = message.Subject,
                HtmlContent = htmlBody
            };

            msg.AddTos(message.To.Select(a => a.AsSendGridEmailAddress()).ToList());

            var sendGridClient = new SendGridClient(sendGridApiKey);
            var response       = sendGridClient.SendEmailAsync(msg).Result;

            if (response.IsSuccessStatusCode)
            {
                errorMessage = "";
                return(true);
            }

            errorMessage = $"{response.StatusCode} {response.Body.ReadAsStringAsync()}";
            LogHelper.Add(errorMessage, true);
            return(false);
        }
Пример #23
0
 public PC_Dummy(LogHelper log) : base(log)
 {
     log.Add("Instantiating dummy positioner");
     settings = new PC_Dummy_Settings();
 }
Пример #24
0
        /// <summary>
        /// Mark online ballot as "submitted" or locked.
        /// </summary>
        /// <param name="locked"></param>
        /// <returns></returns>
        public JsonResult LockPool(bool locked)
        {
            var currentElection = UserSession.CurrentElection;
            var personGuid      = UserSession.VoterInElectionPersonGuid;

            var onlineVotingInfo = Db.OnlineVotingInfo
                                   .SingleOrDefault(ovi => ovi.ElectionGuid == currentElection.ElectionGuid && ovi.PersonGuid == personGuid);

            if (onlineVotingInfo == null)
            {
                return(new
                {
                    Error = "Invalid request"
                }.AsJsonResult());
            }

            if (onlineVotingInfo.Status == OnlineBallotStatusEnum.Processed)
            {
                // already processed... don't do anything
                return(new
                {
                    Error = "Ballot already processed"
                }.AsJsonResult());
            }

            var now = DateTime.Now;

            if (currentElection.OnlineWhenOpen <= now && currentElection.OnlineWhenClose > now)
            {
                var onlineVoteHelper = new OnlineVoteHelper();
                var logHelper        = new LogHelper();

                if (!EncryptionHelper.IsEncrypted(onlineVotingInfo.ListPool))
                {
                    // upgrade previous record
                    onlineVoteHelper.SetListPoolEncrypted(onlineVotingInfo);
                }

                if (locked)
                {
                    // ensure we have enough votes
                    var rawPool = onlineVoteHelper.GetDecryptedListPool(onlineVotingInfo, out var errorMessage);
                    if (rawPool == null)
                    {
                        logHelper.Add("LockPool but pool is empty. " + errorMessage, true);
                        return(new
                        {
                            Error = "Pool is empty"
                        }.AsJsonResult());
                    }

                    if (errorMessage.HasContent())
                    {
                        logHelper.Add(errorMessage, true);
                        return(new
                        {
                            Error = errorMessage
                        }.AsJsonResult());
                    }

                    List <OnlineRawVote> completePool;
                    try
                    {
                        completePool = JsonConvert.DeserializeObject <List <OnlineRawVote> >(rawPool);
                    }
                    catch (Exception e)
                    {
                        logHelper.Add("LockPool but pool has invalid JSON. " + e.GetBaseException().Message + "...  Start of pool: " + rawPool.Left(30), true);
                        return(new
                        {
                            Error = "Technical error in pool. Please edit and try again."
                        }.AsJsonResult());
                    }

                    var numVotes = completePool.Count;
                    if (numVotes < currentElection.NumberToElect)
                    {
                        var msg = $"Too few votes ({numVotes})";
                        logHelper.Add(msg + $" Required ({currentElection.NumberToElect})", true);
                        return(new
                        {
                            Error = msg
                        }.AsJsonResult());
                    }
                }

                onlineVotingInfo.PoolLocked = locked;

                onlineVotingInfo.Status         = locked ? OnlineBallotStatusEnum.Submitted : OnlineBallotStatusEnum.Draft;
                onlineVotingInfo.HistoryStatus += $";{onlineVotingInfo.Status} ({UserSession.VoterLoginSource})|{now.ToJSON()}".FilledWith(onlineVotingInfo.Status, now.ToJSON());
                onlineVotingInfo.WhenStatus     = now;

                var personCacher = new PersonCacher(Db);
                var person       = personCacher.AllForThisElection.SingleOrDefault(p => p.PersonGuid == onlineVotingInfo.PersonGuid);
                if (person == null)
                {
                    return(new
                    {
                        Error = "Invalid request (2)"
                    }.AsJsonResult());
                }

                if (!person.CanVote.AsBoolean())
                {
                    return(new
                    {
                        Error = "Cannot vote"
                    }.AsJsonResult());
                }

                Db.Person.Attach(person);
                var    peopleModel         = new PeopleModel();
                var    votingMethodRemoved = false;
                string notificationType    = null;

                person.HasOnlineBallot = locked;

                if (person.VotingMethod.HasContent() && person.VotingMethod != VotingMethodEnum.Online)
                {
                    // teller has set. Voter can't change it...
                }
                else
                {
                    if (locked)
                    {
                        person.VotingMethod       = VotingMethodEnum.Online;
                        person.RegistrationTime   = now;
                        person.VotingLocationGuid = new LocationModel().GetOnlineLocation().LocationGuid;
                        person.EnvNum             = null;

                        var log = person.RegistrationLog;
                        log.Add(new[]
                        {
                            peopleModel.ShowRegistrationTime(person, true),
                            UserSession.VoterLoginSource,
                            VotingMethodEnum.TextFor(person.VotingMethod),
                        }.JoinedAsString("; ", true));
                        person.RegistrationLog = log;

                        // logHelper.Add("Locked ballot");
                        logHelper.Add("Submitted Ballot", false, UserSession.VoterId);


                        var notificationHelper = new NotificationHelper();
                        var notificationSent   = notificationHelper.SendWhenBallotSubmitted(person, currentElection, out notificationType, out var error);
                        if (!notificationSent)
                        {
                            notificationType = null;
                        }
                    }
                    else
                    {
                        // not online or anywhere
                        person.VotingMethod       = null;
                        person.VotingLocationGuid = null;
                        person.EnvNum             = null;

                        votingMethodRemoved = true;

                        var log = person.RegistrationLog;
                        person.RegistrationTime = now; // set time so that the log will have it
                        log.Add(new[]
                        {
                            peopleModel.ShowRegistrationTime(person, true),
                            "Cancel Online",
                        }.JoinedAsString("; ", true));
                        person.RegistrationTime = null; // don't keep it visible
                        person.RegistrationLog  = log;

                        // logHelper.Add("Unlocked ballot");
                        logHelper.Add("Recalled Ballot", false, UserSession.VoterId);
                    }
                }

                Db.SaveChanges();

                personCacher.UpdateItemAndSaveCache(person);
                peopleModel.UpdateFrontDeskListing(person, votingMethodRemoved);


                // okay
                return(new
                {
                    success = true,
                    notificationType,
                    person.VotingMethod,
                    ElectionGuid = UserSession.CurrentElectionGuid,
                    person.RegistrationTime,
                    onlineVotingInfo.WhenStatus,
                    onlineVotingInfo.PoolLocked
                }.AsJsonResult());
            }

            return(new
            {
                Error = "Closed"
            }.AsJsonResult());
        }
Пример #25
0
 /// <summary>
 /// 客户端断开事件
 /// </summary>
 /// <param name="e"></param>
 void ClientClose(Session e)
 {
     LogHelper.Add(e.Id + "->ClientClose", "IP:" + e.ConnIp + ",Port:" + e.Port, LogType.TcpService);
 }
Пример #26
0
        public Exporter Export()
        {
            // collect all the info
            _election = Db.Election.SingleOrDefault(e => e.ElectionGuid == _electionGuid);

            var logger = new LogHelper(_electionGuid);

            logger.Add("Save to file started");

            if (_election == null)
            {
                return(null);
            }

            // don't use Cached versions - this may not be for the current election

            var locations = Db.Location.Where(l => l.ElectionGuid == _electionGuid);
            //var computers = Db.Computer.Where(c => c.ElectionGuid == _electionGuid);

            var people          = Db.Person.Where(p => p.ElectionGuid == _electionGuid);
            var tellers         = Db.Teller.Where(t => t.ElectionGuid == _electionGuid);
            var results         = Db.Result.Where(r => r.ElectionGuid == _electionGuid);
            var resultSummaries = Db.ResultSummary.Where(r => r.ElectionGuid == _electionGuid);
            var resultTies      = Db.ResultTie.Where(r => r.ElectionGuid == _electionGuid);
            var logs            = Db.C_Log.Where(log => log.ElectionGuid == _electionGuid);
            var onlineVoterInfo = Db.OnlineVotingInfo.Where(ovi => ovi.ElectionGuid == _electionGuid);

            var joinElectionUsers = Db.JoinElectionUser.Where(j => j.ElectionGuid == _electionGuid);
            var users             = Db.Users.Where(u => joinElectionUsers.Select(j => j.UserId).Contains(u.UserId));

            var ballots = Db.Ballot.Where(b => locations.Select(l => l.LocationGuid).Contains(b.LocationGuid));
            var votes   = Db.Vote.Where(v => ballots.Select(b => b.BallotGuid).Contains(v.BallotGuid));

            var site = new SiteInfo();


            var blob = new
            {
                Exported    = DateTime.Now.ToString("o"),
                ByUser      = UserSession.MemberName,
                UserEmail   = UserSession.MemberEmail,
                Server      = site.ServerName,
                Version     = UserSession.SiteVersion,
                Environment = site.CurrentEnvironment,
                // elements
                election        = ExportElection(_election),
                resultSummary   = ExportResultSummaries(resultSummaries),
                result          = ExportResults(results),
                resultTie       = ExportResultTies(resultTies),
                teller          = ExportTellers(tellers),
                user            = ExportUsers(users),
                onlineVoterInfo = ExportOnlineVoterInfos(onlineVoterInfo),
                location        = ExportLocationBallotVote(locations, ballots, votes, logs),
                person          = ExportPeople(people),
                reason          = ExportReasons(),
                //log = ExportLogs(logs)
            };

            var exportName = $"{_election.DateOfElection.GetValueOrDefault(DateTime.Today):yyyy-MM-dd} {_election.Name}.TallyJ";

            return(new Exporter(blob, "TallyJ2", exportName));
        }
Пример #27
0
 /// <summary>
 /// 服务处理失败事件
 /// </summary>
 /// <param name="msg"></param>
 void ServerError(string msg)
 {
     LogHelper.Add("->ServerError", msg, LogType.TcpService);
 }
Пример #28
0
    /// <summary>
    ///   requested by the head teller
    /// </summary>
    /// <param name="messageCode">
    ///   Expected: test, announce
    /// </param>
    /// <param name="testPhoneNumber">Used when Testing </param>
    /// <param name="text"></param>
    /// <param name="idList"></param>
    /// <returns></returns>
    public JsonResult SendHeadTellerMessage(string idList)
    {
      // var htMessageCode = messageCode.AsEnum(HtEmailCodes._unknown_);
      //
      // if (htMessageCode == HtEmailCodes._unknown_)
      // {
      //   return new
      //   {
      //     Success = false,
      //     Status = "Invalid request"
      //   }.AsJsonResult();
      // }
      //

      var db = UserSession.GetNewDbContext;
      var now = DateTime.Now;
      var hostSite = SettingsHelper.Get("HostSite", "");

      var election = UserSession.CurrentElection;
      var text = election.SmsText;

      if (text.HasNoContent())
      {
        return new
        {
          Success = false,
          Status = "SMS text not set"
        }.AsJsonResult();
      }

      var phoneNumbersToSendTo = new List<NamePhone>();

      // switch (htMessageCode)
      // {
      //   case HtEmailCodes.Test:
      //     phoneNumbersToSendTo.Add(new NamePhone
      //     {
      //       Phone = testPhoneNumber, 
      //       PersonName = election.EmailFromNameWithDefault,
      //       FirstName = "(voter's first name)",
      //       VoterContact = testPhoneNumber
      //     });
      //     break;
      //
      //   case HtEmailCodes.Intro:
      var personIds = idList.Replace("[", "").Replace("]", "").Split(',').Select(s => s.AsInt()).ToList();

      phoneNumbersToSendTo.AddRange(db.Person
        .Where(p => p.ElectionGuid == election.ElectionGuid && p.Phone != null && p.Phone.Trim().Length > 0)
        .Where(p => p.CanVote.Value)
        .Where(p => personIds.Contains(p.C_RowId))
        .Select(p => new NamePhone
        {
          Phone = p.Phone,
          PersonName = p.C_FullNameFL,
          FirstName = p.FirstName,
          VoterContact = p.Phone,
          PersonGuid = p.PersonGuid
        })
      );
      //     break;
      //
      //   default:
      //     // not possible
      //     return null;
      // }

      // var whenOpen = election.OnlineWhenOpen.GetValueOrDefault();
      // var whenOpenUtc = whenOpen.ToUniversalTime();
      // var openIsFuture = whenOpen - now > 0.minutes();
      //
      // var whenClosed = election.OnlineWhenClose.GetValueOrDefault();
      // var whenClosedUtc = whenClosed.ToUniversalTime();
      // var remainingTime = whenClosed - now;
      // var howLong = "";
      // if (remainingTime.Days > 1)
      // {
      //   howLong = remainingTime.Days + " days";
      // }
      // else
      // {
      //   howLong = remainingTime.Hours + " hours";
      // }

      // var numSmsSegments = text.Length / 160;

      var numSent = 0;
      var errors = new List<string>();
      var numToSend = phoneNumbersToSendTo.Count;

      LogHelper.Add($"Sms: Sending to {numToSend} {numToSend.Plural("people", "person")} (see above)", true);
      var startTime = DateTime.Now;
      
      phoneNumbersToSendTo.ForEach(p =>
      {
        var phoneNumber = p.Phone;

        if (!PhoneNumberChecker.IsMatch(phoneNumber))
        {
          errors.Add("Invalid phone number: " + phoneNumber);
          return;
        }

        var messageText = text.FilledWithObject(new
        {
          hostSite,
          p.PersonName,
          p.FirstName,
          p.VoterContact,
        });

        var ok = SendSms(phoneNumber, messageText, p.PersonGuid, out var errorMessage);

        if (ok)
          numSent++;
        else
          errors.Add(errorMessage);
      });

      var seconds = (DateTime.Now - startTime).TotalSeconds.AsInt();

      var msg2 = $"Sms: Sent to {numSent} {numSent.Plural("people", "person")} in {seconds} second{seconds.Plural()}";
      if (errors.Count > 0) msg2 = $" - {errors.Count} failed to send. First error: {errors[0]}";
      LogHelper.Add(msg2, true);

      return new
      {
        Success = numSent > 0,
        Status = msg2
      }.AsJsonResult();
    }
Пример #29
0
 public Pump_Jasco_PU_4180(LogHelper log) : base(log)
 {
     settings = new Pump_Jasco_PU_4180_Setting();
     log.Add("Initializing Jasco PU-4180 HPLC pump");
 }
Пример #30
0
 /// <summary>
 /// 服务停止事件
 /// </summary>
 /// <param name="msg"></param>
 void ServerStop(string msg)
 {
     LogHelper.Add("->ServerStop", msg, LogType.TcpService);
 }