Exemplo n.º 1
0
 public void SetHost(HomeGenieService hg, int programId)
 {
     homegenie = hg;
     netHelper = new NetHelper(homegenie);
     programHelper = new ProgramHelper(homegenie, programId);
     eventsHelper = new EventsHelper(homegenie, programId);
     serialPortHelper = new SerialPortHelper();
     tcpClientHelper = new TcpClientHelper();
     schedulerHelper = new SchedulerHelper(homegenie);
 }
Exemplo n.º 2
0
        public void Handle(CheckParams checkParams, NetHelper nHelper, CancellationToken token)
        {
            CheckParams = checkParams;
            SetRestartState();
            while (_currentState != null)
            {
                if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();

                _currentState.Handle(nHelper);
            }
        }
Exemplo n.º 3
0
 public void TestReadTimeout()
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.Connect("localhost", port);
     NetHelper helper = new NetHelper();
     helper.Set(socket, 100);
     NetHeader header = new NetHeader();
     byte[] bytes;
     bool ok = helper.ReadTimeout(200, ref header, out bytes);
     Assert.AreEqual(ok, false);
     helper.Close();
 }
Exemplo n.º 4
0
 public void TestWriteRead()
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket.Connect("localhost", port);
     NetHelper helper = new NetHelper();
     helper.Set(socket, 100);
     helper.WriteWithHeader(1, NetHelper.ToUTF8("status"));
     NetHeader header = new NetHeader();
     byte[] bytes;
     helper.Read(ref header, out bytes);
     string beginExpected = "\n{\"status\":\"ok\"";
     string beginRead = NetHelper.FromUTF8(bytes).Substring(0, beginExpected.Length);
     Assert.AreEqual(beginExpected, beginRead);
     helper.Close();
 }
Exemplo n.º 5
0
        public override void Handle(NetHelper nHelper)
        {
            var metadataFinder = new MetadataFinder(Context.CheckParams.Account);
            string metadata = metadataFinder.Find(_getMetadataTimeout);

            if (Properties.Settings.Default.Mode == 0 || Properties.Settings.Default.Mode == 2)
            {
                var proxy = Context.ProxyManager.GetProxy();

                if (proxy == null)
                {
                    //Context.State = null;
                    //throw new ApplicationException("proxy not found");
                }
                else
                {
                    nHelper.Proxy = proxy;
                }
            }

            var output = nHelper.GET(Globals.LOG_URL);

            if (StateContext.IsError(output))
            {
                Context.ProxyManager.RemoveProxy(nHelper.Proxy);
                return;
            }

            var attributes = StateContext.ParseAccountAttributes(Context.CheckParams.Account, metadata);

            foreach (Match match in _attributesRegex.Matches(output))
            {
                attributes.Add(match.Groups[1].ToString(), match.Groups[2].ToString());
            }

            string response = nHelper.POST(Globals.POST_URL, attributes);

            Context.SetValidationState(response);
        }
Exemplo n.º 6
0
 private void GetResult(string url)
 {
     result = NetHelper.RequestGetUrl(url);
 }
Exemplo n.º 7
0
        /// <summary>
        ///     获取开奖详情
        /// </summary>
        /// <param name="qishu"></param>
        /// <returns></returns>
        private string GetKaijiangDetails(string qishu)
        {
            var url          = $"https://fx.cp2y.com/draw/draw.jsp?lid=10029&iid={qishu}";
            var htmlResource = NetHelper.GetUrlResponse(url, Encoding.GetEncoding("gb2312"));

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

            var doc = new HtmlDocument();

            doc.LoadHtml(htmlResource);

            var div = doc.DocumentNode.SelectSingleNode("//div[@class='fl lh24 f14']");

            if (div == null)
            {
                return(null);
            }
            var div2 = div.ChildNodes.Where(node => node.Name == "div").ToList();
            //爬去奖金
            var trjeg = div2[1].ChildNodes.Where(node => node.Name == "span").ToList();
            var gdjeg = div2[2].ChildNodes.Where(node => node.Name == "span").ToList();

            //爬去奖项
            //var tbody = div.ChildNodes.Where(node => node.Name == "tbody").ToList();
            var table = doc.DocumentNode.SelectSingleNode("//table");
            var trs   = table.ChildNodes.Where(node => node.Name == "tr").ToList();

            var gdje = gdjeg[1].InnerText.Replace("奖池资金累计金额:", "").Replace("元", "").Replace("--", "0").Replace(",", "")
                       .Trim();
            var trje = trjeg[1].InnerText.Replace("本期投注总额:", "").Replace("元", "").Replace("--", "0").Replace(",", "")
                       .Trim();

            var entity = new KaijiangDetailsEntity
            {
                Gdje = gdje == "0" ? "0" : (double.Parse(gdje) * 1).ToString(),
                Trje = trje == "0" ? "0" : (double.Parse(trje) * 1).ToString()
            };
            //TODO

            //组装详情
            var list = new List <Kaijiangitem>();

            for (var i = 1; i < trs.Count; i++)
            {
                var tds = trs[i].ChildNodes.Where(node => node.Name == "td").ToList();


                var kaijiangitem = new Kaijiangitem();

                var TotalMoney = tds[3].InnerText.Replace("元", "").Replace("--", "0").Replace(",", "").Trim();
                kaijiangitem.Name       = tds[1].InnerText.Trim();
                kaijiangitem.TotalMoney = TotalMoney == "0" ? "0" : double.Parse(TotalMoney).ToString();
                kaijiangitem.Total      = tds[2].InnerText.Replace(" 注", "").Replace("--", "0").Trim();
                list.Add(kaijiangitem);
            }

            entity.KaiJiangItems = list;

            return(entity.TryToJson());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="addressOrSubnet">
        /// Specifies the IP address or subnet or you may also specify <b>"any"</b>
        /// to specify all possible IP addresses.
        /// </param>
        /// <param name="action">Specifies whether network traffic is to be allowed or denied.</param>
        public AddressRule(string addressOrSubnet, AddressRuleAction action)
        {
            Covenant.Requires <ArgumentException>(!string.IsNullOrEmpty(addressOrSubnet), nameof(addressOrSubnet));
            Covenant.Requires <ArgumentException>(addressOrSubnet.Equals("any", StringComparison.InvariantCultureIgnoreCase) || NetHelper.TryParseIPv4Address(addressOrSubnet, out var v1) || NetworkCidr.TryParse(addressOrSubnet, out var v2), nameof(addressOrSubnet));

            if (addressOrSubnet.Equals("any", StringComparison.InvariantCultureIgnoreCase))
            {
                this.AddressOrSubnet = null;
            }
            else
            {
                this.AddressOrSubnet = addressOrSubnet;
            }

            this.Action = action;
        }
 public bool IsValidEmail()
 {
     return(NetHelper.IsValidEmail(UserNameOrEmail));
 }
Exemplo n.º 10
0
        public static void Update(TcpClient server)
        {
            if (Focused)
            {
                string buffer = "";

                foreach (ConsoleKeyInfo keyInfo in InputManager.PressedKeys)
                {
                    switch (keyInfo.Key)
                    {
                    case ConsoleKey.Escape:
                    {
                        Focused = false;
                        Text    = string.Empty;
                        break;
                    }

                    case ConsoleKey.Enter:
                    {
                        Focused = false;
                        AddMessage(new ChatLine(Text, LocalClient.Player.Drawable.Color));
                        Text = string.Empty;
                        break;
                    }

                    case ConsoleKey.Backspace:
                    {
                        if (Text.Length - 1 > 0)
                        {
                            Text = Text.Substring(0, Text.Length - 1);
                        }
                        else
                        {
                            Text = string.Empty;
                        }
                        break;
                    }

                    default:
                    {
                        buffer += keyInfo.KeyChar;
                        break;
                    }
                    }
                }

                Text += buffer;
            }
            else
            {
                foreach (ConsoleKeyInfo keyInfo in InputManager.PressedKeys)
                {
                    switch (keyInfo.Key)
                    {
                    case ConsoleKey.Y:
                    {
                        Focused = true;
                        break;
                    }
                    }
                }
            }

            SendBuffer(server);

            // An incoming message spotted.
            if (server.Available > 0)
            {
                string message;
                while (true)
                {
                    message = NetHelper.ReceiveMessageFrom(server);

                    if (message != string.Empty)
                    {
                        break;
                    }
                }

                string[] messages = message.Split(Headers.SplitChar);

                int          id          = int.Parse(messages[1]);
                string       chatMessage = messages[2];
                ConsoleColor chatColor   = (ConsoleColor)int.Parse(messages[3]);

                PrintChatLine(new ChatLine(chatMessage, chatColor));
            }
        }
Exemplo n.º 11
0
        private bool TryUpgrade(int i, int j)
        {
            Player player  = Main.player[Main.myPlayer];
            Item   item    = player.inventory[player.selectedItem];
            int    style   = Main.tile[i, j].frameY / 36;
            bool   success = false;

            if (style == 0 && item.type == mod.ItemType("UpgradeDemonite"))
            {
                SetStyle(i, j, 1);
                success = true;
            }
            else if (style == 0 && item.type == mod.ItemType("UpgradeCrimtane"))
            {
                SetStyle(i, j, 2);
                success = true;
            }
            else if ((style == 1 || style == 2) && item.type == mod.ItemType("UpgradeHellstone"))
            {
                SetStyle(i, j, 3);
                success = true;
            }
            else if (style == 3 && item.type == mod.ItemType("UpgradeHallowed"))
            {
                SetStyle(i, j, 4);
                success = true;
            }
            else if (style == 4 && item.type == mod.ItemType("UpgradeBlueChlorophyte"))
            {
                SetStyle(i, j, 5);
                success = true;
            }
            else if (style == 5 && item.type == mod.ItemType("UpgradeLuminite"))
            {
                SetStyle(i, j, 6);
                success = true;
            }
            else if (style == 6 && item.type == mod.ItemType("UpgradeTerra"))
            {
                SetStyle(i, j, 7);
                success = true;
            }
            if (success)
            {
                TEStorageUnit storageUnit = (TEStorageUnit)TileEntity.ByPosition[new Point16(i, j)];
                storageUnit.UpdateTileFrame();
                NetMessage.SendTileRange(Main.myPlayer, i, j, 2, 2);
                TEStorageHeart heart = storageUnit.GetHeart();
                if (heart != null)
                {
                    if (Main.netMode == 0)
                    {
                        heart.ResetCompactStage();
                    }
                    else if (Main.netMode == 1)
                    {
                        NetHelper.SendResetCompactStage(heart.ID);
                    }
                }
                item.stack--;
                if (item.stack <= 0)
                {
                    item.SetDefaults(0);
                }
                if (player.selectedItem == 58)
                {
                    Main.mouseItem = item.Clone();
                }
            }
            return(success);
        }
Exemplo n.º 12
0
        private async Task GatherGiftCardBalanceAsync(NetHelper nHelper, Account account)
        {
            var task = Task.Factory.StartNew(() =>
            {
                try
                {
                    account.GiftCardBalance = Regex.Match(nHelper.GET(Globals.GC_URL), Globals.GC_REGEX).Groups[1].Value;
                }
                catch (Exception exception)
                {
                    _logger.Debug("error while gather GiftCardBalance");
                    _logger.Error(exception);

                    account.GiftCardBalance = "N/A";
                }
            });
            await task;
        }
Exemplo n.º 13
0
        public async Task GatherAddyInfosAsync(NetHelper nHelper, Account account)
        {
            var task = Task.Factory.StartNew(() =>
            {
                try
                {
                    string pageCode = nHelper.GET(Globals.ADDY_URL);
                    string addyId = Regex.Match(pageCode, Globals.REGEX.Replace(" />", ">")).Groups[2].Value;
                    string addyInfos = nHelper.GET(string.Format(Globals.FULLADDY_URL, addyId));
                    
                    //account.ZipCode = HtmlParser.GetElementValueById(addyInfos, "enterAddressPostalCode");
                    //account.Phone = HtmlParser.GetElementValueById(addyInfos, "enterAddressPhoneNumber");

                    Regex attributesRegex = new Regex(Globals.REGEX, RegexOptions.Multiline | RegexOptions.IgnoreCase);

                    foreach (Match m in attributesRegex.Matches(addyInfos))
                    {
                        var addy = m.Groups[1].Value;
                        if (addy == "oldPostalCode")
                            account.ZipCode = m.Groups[2].Value;
                        else if (addy == "oldPhoneNumber")
                            account.Phone = m.Groups[2].Value;
                        else
                            _logger.Info(string.Format("unknown ADDY info:'{0}'", addy));
                    }
                }
                catch (Exception exception)
                {
                    _logger.Debug("error while gather addy info");
                    _logger.Error(exception);

                    account.ZipCode = "N/A";
                    account.Phone = "N/A";
                }
            });
            await task;
        }
Exemplo n.º 14
0
        public void GatherInformation(NetHelper nHelper, Account account)
        {
            var tasks =
                new List<Task>(new[]
                {
                    GatherGiftCardBalanceAsync(nHelper, account),
                    GatherOrdersAsync(nHelper, account),
                    GatherAddyInfosAsync(nHelper, account)
                });

            Task.WhenAll(tasks).Wait();
        }
Exemplo n.º 15
0
        /// <summary>
        ///     获取备用站点开奖列表数据
        /// </summary>
        /// <returns></returns>
        private List <OpenCode5DTModel> GetOpenListFromBackUrl()
        {
            var result = new List <OpenCode5DTModel>();

            try
            {
                var url          = new Uri(Config.BackUrl);
                var htmlResource = NetHelper.GetUrlResponse(Config.BackUrl, Encoding.GetEncoding("gb2312"));
                if (htmlResource == null)
                {
                    return(result);
                }


                var doc = new HtmlDocument();
                doc.LoadHtml(htmlResource);
                var table = doc.DocumentNode.SelectSingleNode("//table");
                if (table == null)
                {
                    return(result);
                }
                var trs = table.ChildNodes.Where(node => node.Name == "tr").ToList();
                OpenCode5DTModel model = null;
                HtmlNode         nodeA = null;
                var optimizeUrl        = string.Empty;
                for (var i = 2; i < trs.Count; i++) //第一二行为表头
                {
                    var trstyle = trs[i].Attributes["style"];
                    if (trstyle != null && trstyle.Value == "display:none")
                    {
                        continue;
                    }
                    var tds = trs[i].ChildNodes.Where(node => node.Name == "td").ToList();
                    if (tds.Count < 10)
                    {
                        continue;
                    }
                    model = new OpenCode5DTModel();
                    nodeA = tds[0].ChildNodes.FirstOrDefault(n => n.Name == "a");
                    if (nodeA == null)
                    {
                        continue;
                    }
                    model.Term      = Convert.ToInt64(nodeA.InnerText.Trim());
                    optimizeUrl     = nodeA.Attributes["href"].Value;
                    model.DetailUrl = new Uri(url, optimizeUrl).AbsoluteUri;
                    model.OpenTime  = Convert.ToDateTime(tds[9].InnerText);
                    if (tds[1].ChildNodes.Count == 0)
                    {
                        continue;
                    }
                    var opencodeNode = tds[1].ChildNodes.Where(n => n.Name.ToLower() == "i").ToList();
                    if (opencodeNode.Count < 5)
                    {
                        continue;
                    }
                    model.OpenCode1 = Convert.ToInt32(opencodeNode[0].InnerText.Trim());
                    model.OpenCode2 = Convert.ToInt32(opencodeNode[1].InnerText.Trim());
                    model.OpenCode3 = Convert.ToInt32(opencodeNode[2].InnerText.Trim());
                    model.OpenCode4 = Convert.ToInt32(opencodeNode[3].InnerText.Trim());
                    model.OpenCode5 = Convert.ToInt32(opencodeNode[4].InnerText.Trim());
                    result.Add(model);
                }

                var checkDataHelper = new CheckDataHelper();
                var dbdata          = services.GetListS <OpenCode5DTModel>(currentLottery)
                                      .ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr());
                checkDataHelper.CheckData(dbdata, result.ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr()),
                                          Config.Area, currentLottery);
                result = result.OrderByDescending(S => S.Term).ToList();
            }
            catch (Exception ex)
            {
                log.Error(GetType(),
                          string.Format("【{0}】通过备用站点抓取开奖列表时发生错误,错误信息【{1}】", Config.Area + currentLottery, ex.Message));
            }

            return(result);
        }
Exemplo n.º 16
0
        public void run()
        {
            running = true;
            while (running)
            {
                NetCommand input = NetHelper.ReadNetCommand(client);

                switch (input.Type)
                {
                case NetCommand.CommandType.LOGOUT:
                    running = false;
                    client.Close();
                    server.backlog.Clear();
                    Console.WriteLine("Doctor logged out");
                    break;

                case NetCommand.CommandType.CHAT:
                    server.SendToClient(input);
                    break;

                case NetCommand.CommandType.BROADCAST:
                    server.BroadcastToClients(input.ChatMessage);
                    break;

                case NetCommand.CommandType.VALUESET:
                    server.SendToClient(input);
                    break;

                case NetCommand.CommandType.USER:
                    server.AddUser(input.DisplayName, input.Password);
                    break;

                case NetCommand.CommandType.REQUEST:
                    switch (input.Request)
                    {
                    case NetCommand.RequestType.USERS:
                        sendToDoctor(new NetCommand(NetCommand.LengthType.USERS, server.users.Count - 1, input.Session));
                        foreach (KeyValuePair <string, string> user in server.users)
                        {
                            Thread.Sleep(10);
                            if (user.Key != "Doctor0tVfW")
                            {
                                sendToDoctor(new NetCommand(user.Key, user.Value, input.Session));
                            }
                        }
                        break;

                    case NetCommand.RequestType.CHAT:
                        List <ChatMessage> chat = FileHandler.ReadChat(input.Session);
                        foreach (ChatMessage msg in chat)
                        {
                            Thread.Sleep(10);
                            sendToDoctor(new NetCommand(msg.Message, msg.IsDoctor, input.Session));
                        }
                        break;

                    case NetCommand.RequestType.OLDDATA:
                        List <Meting> metingen = FileHandler.ReadMetingen(input.Session);
                        foreach (Meting meting in metingen)
                        {
                            Thread.Sleep(10);
                            sendToDoctor(new NetCommand(meting, input.Session));
                        }
                        break;

                    case NetCommand.RequestType.ALLSESSIONS:
                        List <Tuple <int, string, double> > sessions = FileHandler.GetAllSessions();
                        sendToDoctor(new NetCommand(NetCommand.LengthType.SESSIONS, sessions.Count, input.Session));
                        foreach (Tuple <int, string, double> session in sessions)
                        {
                            sendToDoctor(new NetCommand(session.Item2, session.Item3, session.Item1, true));
                            Thread.Sleep(10);
                        }
                        break;

                    case NetCommand.RequestType.SESSIONDATA:
                        List <Tuple <int, string> > currentsessionsdata = server.GetRunningSessionsData();
                        sendToDoctor(new NetCommand(NetCommand.LengthType.SESSIONDATA, currentsessionsdata.Count, input.Session));
                        foreach (Tuple <int, string> ses in currentsessionsdata)
                        {
                            sendToDoctor(new NetCommand(ses.Item2, Helper.Now, ses.Item1));
                            Thread.Sleep(10);
                        }
                        break;

                    case NetCommand.RequestType.PERSONALDATA:
                        NetCommand response = FileHandler.ReadPersonalData(input.Session);
                        sendToDoctor(response);
                        break;

                    case NetCommand.RequestType.TESTRESULT:
                        NetCommand resp = FileHandler.ReadTestResult(input.Session);
                        sendToDoctor(resp);
                        break;

                    default:
                        throw new FormatException("Unknown Command");
                    }

                    break;

                case NetCommand.CommandType.ERROR:
                    Console.WriteLine("An error occured, assuming docter disconnected");
                    running = false;
                    Console.WriteLine("Doctor logged out due to an error");
                    client.Close();
                    break;

                default:
                    throw new FormatException("Unknown Command");
                }
            }
        }
Exemplo n.º 17
0
        private void Check(CheckParams checkParams, CancellationToken token)
        {
            if (checkParams == null)
                throw new ArgumentNullException(nameof(checkParams));

            try
            {
                NetHelper nHelper = new NetHelper { UserAgent = UserAgentsManager.GetRandomUserAgent() };

                var context = new StateContext(_logger, _proxyManager, _captchaService);
                context.OnCheckCompleted += _context_OnCheckCompleted;
                context.Handle(checkParams, nHelper, token);
                context.OnCheckCompleted -= _context_OnCheckCompleted;
            }
            catch (Exception exception)
            {
                _logger.Debug("error while check");
                _logger.Error(exception);

                _accChecked++;
                _badAccounts++;

                FireOnCheckCompleted(CheckResults.Bad, checkParams);

                _eventAggregator.SendMessage(new InformUserMessage(new InformUserMessage.Message(exception.Message, InformUserMessage.MessageType.Error)));
            }
        }
Exemplo n.º 18
0
        public static bool Connect(string comport, string name, string password, out string error)
        {
            error = "Succes";

            if (!ComPort.IsOpen())
            {
                if (ComPort.Connect(comport))
                {
                    ComPort.Write("RS");
                    string temp = ComPort.Read();
                    if (temp.ToLower() != "ack")
                    {
                        ComPort.Disconnect();
                        error = "De Ergometer is niet verbonden";
                        return(false);
                    }
                    Thread.Sleep(200);

                    ComPort.Write("ST");
                    string response = ComPort.Read();

                    SaveMeting(response);
                }
                else
                {
                    error = "De ergometer is niet verbonden";
                    return(false);
                }
            }

            if (Doctor == null || !Doctor.Connected)
            {
                if (Doctor == null)
                {
                    Doctor = new TcpClient();
                }

                try
                {
                    Doctor.Connect(HOST, PORT);
                }
                catch (Exception e)
                {
                    error = "Server is niet online.";
                    return(false);
                }

                Name = name;

                NetCommand net = NetHelper.ReadNetCommand(Doctor);
                if (net.Type == NetCommand.CommandType.SESSION)
                {
                    Session = net.Session;
                }
                else
                {
                    throw new Exception("Session not assigned");
                }

                running = true;

                t = new Thread(run);
                t.IsBackground = true;
                t.Start();
            }

            if (!Loggedin)
            {
                NetCommand command = new NetCommand(name, false, password, Session);
                NetHelper.SendNetCommand(Doctor, command);

                NetCommand response = NetHelper.ReadNetCommand(Doctor);
                if (response.Type == NetCommand.CommandType.RESPONSE && response.Response == NetCommand.ResponseType.LOGINWRONG)
                {
                    Loggedin = false;
                    error    = "De inloggegevens zijn onjuist.";
                    return(false);
                }

                Loggedin = true;
            }

            return(true);
        }
Exemplo n.º 19
0
        public override void Handle(NetHelper nHelper)
        {
            var account = Context.CheckParams.Account;
            var proxyManager = Context.ProxyManager;

            if (StateContext.IsBadLog(_response))
            {
                Context.FireOnCheckCompleted(Context, CheckResults.Bad, Context.CheckParams);
            }
            else if (StateContext.IsSecurityQuestion(_response))
            {
                nHelper.GET("http://amazon.com/homepage=true");
                Context.GatherInformation(nHelper, account);

                Context.FireOnCheckCompleted(Context, CheckResults.Good, Context.CheckParams);
            }
            else if (StateContext.IsCookiesDisabled(_response))
            {
                Context.SetRestartState();
                return;
            }
            else if (StateContext.IsCaptchaMsg(_response))
            {
                if (Properties.Settings.Default.Mode == 0 || Properties.Settings.Default.Mode == 1)
                {
                    string captchaUrl = "https://opfcaptcha-prod.s3.amazonaws.com" +
                                        _response.Split(new[] { "opfcaptcha-prod.s3.amazonaws.com" },
                                            StringSplitOptions.None)[1].Split('"')[0];
                    byte[] captchaBytes;

                    using (WebClient wc = new WebClient())
                        captchaBytes = wc.DownloadData(captchaUrl);

                    var captchaResult = Context.CaptchaService.DecodeCaptchaAsync(captchaBytes).Result;

                    if (captchaResult != null)
                    {
                        var metadataFinder = new MetadataFinder(account);
                        var metadata = metadataFinder.Find(_getMetadataTimeout);

                        var attributes = StateContext.ParseAccountAttributes(account, metadata);

                        foreach (Match m in _attributesRegex.Matches(_response))
                        {
                            attributes.Add(m.Groups[1].ToString(), m.Groups[2].ToString());
                        }

                        attributes.Add("guess", captchaResult.Text);

                        var response = nHelper.POST(Globals.POST_URL, attributes);
                        Init(response);

                        // limit captcha attemts
                        if (_captchaCounter >= 5)
                        {
                            Context.SetFinishState();
                            return;
                        }

                        _captchaCounter++;

                        return;
                    }
                    //todo: captcha not recognized, so need to request new one
                }
                else
                {
                    proxyManager.RemoveProxy(nHelper.Proxy);
                    Context.SetRestartState();
                    return;
                }
            }
            else if (StateContext.IsAskCredentials(_response))
            {
                Context.SetRestartState();
            }
            else if (StateContext.IsAnotherDevice(_response))
            {
                Context.FireOnCheckCompleted(Context, CheckResults.Good, Context.CheckParams);
            }
            else if (StateContext.IsError(_response))
            {
                proxyManager.RemoveProxy(nHelper.Proxy);
                Context.SetRestartState();
                return;
            }
            else
            {
                Context.GatherInformation(nHelper, account);

                Context.FireOnCheckCompleted(Context, CheckResults.Good, Context.CheckParams);
            }

            Context.SetFinishState();
        }
Exemplo n.º 20
0
 public abstract void Handle(NetHelper nHelper);
Exemplo n.º 21
0
        private void checkLatestVersion()
        {
            NetHelper.Request($"https://api.github.com/repos/{Program.Repository}/releases?per_page=10&page=1", "cache/net/releases", 15 * 60,
                              (response, exception) =>
            {
                if (IsDisposed)
                {
                    return;
                }
                if (exception != null)
                {
                    handleLastestVersionException(exception);
                    return;
                }
                try
                {
                    var hasLatest     = false;
                    var latestVersion = Program.Version;
                    var description   = "";
                    var downloadUrl   = (string)null;

                    var releases = TinyToken.ReadString <JsonFormat>(response);
                    foreach (var release in releases.Values <TinyObject>())
                    {
                        var isDraft      = release.Value <bool>("draft");
                        var isPrerelease = release.Value <bool>("prerelease");
                        if (isDraft || isPrerelease)
                        {
                            continue;
                        }

                        var name    = release.Value <string>("name");
                        var version = new Version(name);

                        if (!hasLatest)
                        {
                            hasLatest     = true;
                            latestVersion = version;

                            foreach (var asset in release.Values <TinyObject>("assets"))
                            {
                                var downloadName = asset.Value <string>("name");
                                if (downloadName.EndsWith(".zip"))
                                {
                                    downloadUrl = asset.Value <string>("browser_download_url");
                                    break;
                                }
                            }
                        }

                        if (Program.Version < version || Program.Version >= latestVersion)
                        {
                            var publishedAt = release.Value <string>("published_at");
                            var publishDate = DateTime.ParseExact(publishedAt, @"yyyy-MM-dd\THH:mm:ss\Z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
                            var authorName  = release.Value <string>("author", "login");

                            var body = release.Value <string>("body");
                            if (body.Contains("---"))
                            {
                                body = body.Substring(0, body.IndexOf("---"));
                            }
                            body = body.Replace("\r\n", "\n").Trim(' ', '\n');
                            body = $"v{version} - {authorName}, {publishDate.ToTimeAgo()}\n{body}\n\n";

                            var newDescription = description + body;
                            if (description.Length > 0 && newDescription.Count(c => c == '\n') > 35)
                            {
                                break;
                            }

                            description = newDescription;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (Program.Version < latestVersion)
                    {
                        updateButton.Text     = $"Version {latestVersion} available!";
                        updateButton.Tooltip  = $"What's new:\n\n{description.TrimEnd('\n')}";
                        updateButton.OnClick += (sender, e) =>
                        {
                            if (downloadUrl != null && latestVersion >= new Version(1, 4))
                            {
                                Manager.Add(new UpdateMenu(downloadUrl));
                            }
                            else
                            {
                                Updater.OpenLastestReleasePage();
                            }
                        };
                        updateButton.StyleName = "";
                        updateButton.Disabled  = false;
                    }
                    else
                    {
                        versionLabel.Tooltip   = $"Recent changes:\n\n{description.TrimEnd('\n')}";
                        updateButton.Displayed = false;
                    }
                    bottomLayout.Pack(600);
                }
                catch (Exception e)
                {
                    handleLastestVersionException(e);
                }
            });
        }
Exemplo n.º 22
0
        public static bool login(string UserName, string Password)
        {
            if (ISLOGIN)
            {
                return(true);
            }

            string Errmsg  = null;
            string SessID1 = null;
            string SessID2 = null;
            string Ccode   = null;
            string sRet    = null;

            for (int i = 0; i < 2; i++)
            {
                //HttpHelper.GetOrPost get err when the username=="*****@*****.**"
                if (UserName.IndexOf("@gmail") >= 0 && UserName.IndexOf("+") >= 0)
                {
                    sRet = NetHelper.UploadCollection(URL + "login/username", out Errmsg, new NameValueCollection {
                        { "username", UserName },
                        { "password", Password },
                        { "token", i == 0 ? TOKEN_PHONE : TOKEN },
                        { "clientVersion", VERSION },
                        { "clientUniqueKey", getUID() }
                    }, 20 * 1000, IsErrResponse: true).ToString();
                }
                else
                {
                    sRet = (string)HttpHelper.GetOrPost(URL + "login/username", out Errmsg, new Dictionary <string, string>()
                    {
                        { "username", UserName },
                        { "password", Password },
                        { "token", i == 0 ? TOKEN_PHONE : TOKEN },
                        { "clientVersion", VERSION },
                        { "clientUniqueKey", getUID() }
                    },
                                                        ContentType: "application/x-www-form-urlencoded",
                                                        IsErrResponse: true, Timeout: 30 * 1000, Proxy: PROXY);
                }

                if (ISLOGIN)
                {
                    return(true);
                }
                if (Errmsg.IsNotBlank())
                {
                    loginErrlabel = AIGS.Helper.JsonHelper.GetValue(Errmsg, "userMessage");
                    if (loginErrlabel == null)
                    {
                        loginErrlabel = Errmsg;
                    }
                    return(false);
                }
                if (i == 0)
                {
                    SessID1 = JsonHelper.GetValue(sRet, "sessionId");
                }
                else
                {
                    SessID2 = JsonHelper.GetValue(sRet, "sessionId");
                    Ccode   = JsonHelper.GetValue(sRet, "countryCode");
                }
            }
            if (ISLOGIN)
            {
                return(true);
            }

            SESSIONID_PHONE = SessID1;
            SESSIONID       = SessID2;
            COUNTRY_CODE    = Ccode;
            USERNAME        = UserName;
            PASSWORD        = Password;
            ISLOGIN         = true;
            return(true);
        }
Exemplo n.º 23
0
        public async static Task <string> LoadFromHtml(HTMLNode imgNode, string baseUrl)
        {
            Param  param = imgNode.Param.ByName("src");
            string str   = "";

            if (param == null)
            {
                return(str);
            }
            string url = param.Value.Trim().ToLower();

            if ((url == "#") || url.Equals(string.Empty))
            {
                return("");
            }
            if ((url.StartsWith("http://") || url.StartsWith("ftp://")) || url.StartsWith("file://"))
            {
                url = param.Value.Trim();
            }
            else
            {
                url = baseUrl + param.Value.Trim();
            }
            ImageStyle style = new ImageStyle(url);

            using (Stream stream = await NetHelper.Get(url))
            {
                int          width  = 0;
                int          height = 0;
                RandomStream rs     = new RandomStream(stream);
                BitmapImage  image  = new BitmapImage();
                {
                    image.SetSource(rs);
                    width  = image.PixelWidth;
                    height = image.PixelHeight;
                    Param param2 = imgNode.Param.ByName("width");
                    if (param2 != null)
                    {
                        style.Width = HTMLTree.FontSizeFromHTML(param2.Value.Trim());
                    }
                    Param param3 = imgNode.Param.ByName("height");
                    if (param3 != null)
                    {
                        style.Height = HTMLTree.FontSizeFromHTML(param3.Value.Trim());
                    }
                    if ((style.Width != -1) && (style.Height != -1))
                    {
                        width  = style.Width;
                        height = style.Height;
                    }
                    else if (style.Width != -1)
                    {
                        height = (width * style.Height) / style.Width;
                        width  = style.Width;
                    }
                    else if (style.Height != -1)
                    {
                        width  = (height * style.Width) / style.Height;
                        height = style.Height;
                    }
                }
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("{{\\pict\\wmetafile8\\picwgoal{0}\\pichgoal{1}\n", width * 20, height * 20);
                byte[] buffer = new byte[40];
                stream.Position = 0L;
                int num3 = 0;
                while ((num3 = stream.Read(buffer, 0, 40)) > 0)
                {
                    for (int i = 0; i < num3; i++)
                    {
                        builder.Append(buffer[i].ToString("x").PadLeft(2, '0'));
                    }
                    builder.Append("\n");
                }
                builder.Append("}");
                return(builder.ToString());
            }
        }
Exemplo n.º 24
0
        /// <summary>确保建立服务器</summary>
        public override void EnsureCreateServer()
        {
            if (Servers.Count <= 0)
            {
                // 同时两个端口
                AddServer(IPAddress.Any, Port, ProtocolType.Unknown, AddressFamily.InterNetwork);
                AddServer(IPAddress.Any, Port2, ProtocolType.Unknown, AddressFamily.InterNetwork);

                var        dic = new Dictionary <Int32, IPEndPoint>();
                IPEndPoint ep  = null;
                var        pub = NetHelper.MyIP();
                StunResult rs  = null;
                WriteLog("获取公网地址……");

                foreach (var item in Servers)
                {
                    if (item.Local.ProtocolType == ProtocolType.Tcp)
                    {
                        continue;
                    }

                    // 查询公网地址和网络类型,如果是受限网络,或者对称网络,则采用本地端口,因此此时只能依赖端口映射,将来这里可以考虑操作UPnP
                    if (rs == null)
                    {
                        item.Start();
                        rs = new StunClient(item).Query();
                        if (rs != null)
                        {
                            if (rs != null && rs.Type == StunNetType.Blocked && rs.Public != null)
                            {
                                rs.Type = StunNetType.Symmetric;
                            }
                            WriteLog("网络类型:{0} {1}", rs.Type, rs.Type.GetDescription());
                            ep = rs.Public;
                            if (ep != null)
                            {
                                pub = ep.Address;
                            }
                        }
                    }
                    else
                    {
                        ep = new StunClient(item).GetPublic();
                    }
                    if (rs != null && rs.Type > StunNetType.AddressRestrictedCone)
                    {
                        ep = new IPEndPoint(pub, item.Port);
                    }
                    WriteLog("{0}的公网地址:{1}", item.Local, ep);
                    dic.Add(item.Port, ep);
                }
                // Tcp没办法获取公网地址,只能通过Udp获取到的公网地址加上端口形成,所以如果要使用Tcp,服务器必须拥有独立公网地址
                foreach (var item in Servers)
                {
                    if (item.Local.ProtocolType != ProtocolType.Tcp)
                    {
                        continue;
                    }

                    ep = new IPEndPoint(pub, item.Port);
                    WriteLog("{0}的公网地址:{1}", item.Local, ep);
                    dic.Add(item.Port + 100000, ep);
                }
                //var ep = StunClient.GetPublic(Port, 2000);
                //WriteLog("端口{0}的公网地址:{1}", Port, ep);
                //dic.Add(Port, ep);
                //ep = StunClient.GetPublic(Port2, 2000);
                //WriteLog("端口{0}的公网地址:{1}", Port2, ep);
                //dic.Add(Port2, ep);
                WriteLog("成功获取公网地址!");
                Public = dic;
            }
        }
Exemplo n.º 25
0
        private static SysAccessToken GetAccessToken()
        {
            string url = AuthorizeUrl.GetTokenUrl();

            return(NetHelper.HttpGet <SysAccessToken>(url, SerializationType.Json));
        }
Exemplo n.º 26
0
        /// <summary>
        ///     从备用站抓取开奖数据 昨天/今天
        /// </summary>
        /// <param name="IsToday"></param>
        /// <returns></returns>

        #region   爬取爱彩乐网站数据
        private List <JL11X5Entity> GetDocByBackUrl(bool IsToday = true)
        {
            var list = new List <JL11X5Entity>();

            try
            {
                var day = "?op=dcjb&num=jt";
                if (!IsToday)
                {
                    day = "?op=dcjb&num=zt";
                }
                var url          = string.Format("{0}{1}", Config.BackUrl, day);
                var HtmlResource = NetHelper.GetUrlResponse(url);
                if (!string.IsNullOrWhiteSpace(HtmlResource))
                {
                    var doc = new HtmlDocument();
                    doc.LoadHtml(HtmlResource);
                    var tables       = doc.DocumentNode.SelectNodes("//table");
                    var tbody        = tables[0].ChildNodes.Where(node => node.Name == "tbody").ToList();
                    var matchQiHao   = string.Empty;
                    var matchKJHaoMa = string.Empty;
                    foreach (var item in tables[1].ChildNodes)
                    {
                        if (item.HasChildNodes && item.Name == "tr")
                        {
                            var opencode = new List <string>();
                            var num      = string.Empty;
                            foreach (var item2 in item.ChildNodes)
                            {
                                if (item2.GetAttributeValue("class", "") == "chart-bg-qh")
                                {
                                    num = item2.InnerText.Trim();
                                }
                                if (item2.GetAttributeValue("class", "") == "cc")
                                {
                                    //数据加密保存在此,去掉两头然后base64转码
                                    var base64str = item2.InnerText.Trim().Substring(1);
                                    base64str = base64str.Substring(0, base64str.Length - 1);
                                    var codestr = DecodeBase64(Encoding.Default, base64str);
                                    opencode.Add(codestr);
                                }
                            }

                            if (opencode.Count == 5)
                            {
                                var qihao = num;
                                var tmp   = new JL11X5Entity
                                {
                                    QiHao       = num,
                                    KaiJiangHao = CommonHelper.TRHandleCode(string.Join(",", opencode)),
                                    OpenTime    = GetOpenTimeByPeriodNum(int.Parse(num))
                                };
                                list.Add(tmp);
                            }
                        }
                    }
                }

                var checkDataHelper = new CheckDataHelper();
                var dbdata          = services.GetListIn(currentLottery, IsToday)
                                      .ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr());
                checkDataHelper.CheckData(dbdata, list.ToDictionary(w => w.QiHao, w => w.KaiJiangHao), Config.Area,
                                          currentLottery);
            }
            catch (Exception ee)
            {
                log.Error(GetType(),
                          string.Format("【{0}】通过站点抓取开奖列表时发生错误,错误信息【{1}】", Config.Area + currentLottery, ee.Message));
            }

            return(list);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 获取JsApiTicket
        /// </summary>
        /// <returns></returns>
        //private string GetJsApiTicket()
        //{
        //    string ticket = string.Empty;
        //    var cacheKey = "TCWIRELESS.OPERATION.WeiXin.JsApiTicket";
        //    //先从缓存取,并判断是否过期
        //    var cacheValue = CacheHelper.GetValue<WXTokenModel>(cacheKey);
        //    if (cacheValue != null
        //        && DateTime.Now < cacheValue.OverTime)
        //    {
        //        return cacheValue.Ticket;
        //    }

        //    var token = GetAccessToken();
        //    var now = DateTime.Now;
        //    var url = string.Format(TicketUrl, token);
        //    var request = new TCHttpRequest(url);
        //    var result = request.PostDataToServer(HttpRequestMethod.Get, "utf-8");
        //    var model = JsonConvert.DeserializeObject<WXTokenModel>(result);
        //    model.OverTime = now.AddSeconds(model.Expires_In);
        //    CacheHelper.Set(cacheKey, model, TimeSpan.FromSeconds(model.Expires_In));
        //    ticket = model.Ticket;
        //    return ticket;
        //}

        /// <summary>
        /// 获取JsApi配置信息
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        //public virtual WXJsApiTicketModel GetWXJsApiConfig(string url)
        //{
        //    var model = new WXJsApiTicketModel
        //    {
        //        AppId = AppId,
        //        TimeStamp = DateTime.Now.ToTimeStamp(),//1414587457,
        //        NonceStr = Guid.NewGuid().ToString("N")//"Wm3WZYTPz0wzccnW"
        //    };
        //    var ticket = GetJsApiTicket();//"sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg";
        //    //组装
        //    var sigStr = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, model.NonceStr,
        //        model.TimeStamp, url);
        //    //sha1加密
        //    model.Signature = FormsAuthentication.HashPasswordForStoringInConfigFile(sigStr, "SHA1").ToLower();//f4d90daf4b3bca3078ab155816175ba34c443a7b
        //    return model;
        //}

        #endregion

        #region 发送消息
        public static void SendMsg(WeiXinMsg msg)
        {
            string token  = GetExistAccessToken();
            string url    = AuthorizeUrl.GetMsgSendUrl(token);
            var    result = NetHelper.HttpPost(url, msg, SerializationType.Json);
        }
Exemplo n.º 28
0
 private void PostResult(string url, string Content)
 {
     result = NetHelper.RequestPostUrl(url, Content);
 }
Exemplo n.º 29
0
 public static void SendTemplateMsg(object msg)
 {
     string token  = GetExistAccessToken();
     string url    = AuthorizeUrl.GetTemplateSendUrl(token);
     var    result = NetHelper.HttpPost(url, msg, SerializationType.Json);
 }
Exemplo n.º 30
0
        /// <summary>
        ///     爬取主网站信息
        /// </summary>
        /// <returns></returns>
        private List <OpenCode5DTModel> GetOpenListFromMainUrl(string mainUrl)
        {
            var result = new List <OpenCode5DTModel>();

            try
            {
                var htmlResource = NetHelper.GetUrlResponse(mainUrl, Encoding.GetEncoding("gb2312"));
                if (htmlResource == null)
                {
                    return(result);
                }
                var doc = new HtmlDocument();
                doc.LoadHtml(htmlResource);
                var table = doc.DocumentNode.SelectNodes("//table[@style='word-break:break-all']");
                if (table == null)
                {
                    return(result);
                }
                var trs = table[0].ChildNodes.Where(s => s.Name.ToLower() == "tr").ToList();

                List <HtmlNode>  tds = null;
                string           term = string.Empty, openCodeString = string.Empty, optimizeUrl = string.Empty;
                OpenCode5DTModel model = null;
                for (var i = 1; i < trs.Count; i++)
                {
                    tds = trs[i].ChildNodes.Where(S => S.Name.ToLower() == "td").ToList();
                    if (tds.Count < 8)
                    {
                        continue;
                    }

                    model = new OpenCode5DTModel();
                    term  = tds[0].InnerText.Trim();
                    if (term.StartsWith((CommonHelper.SCCSysDateTime.Year - 1).ToString()))
                    {
                        break;
                    }

                    model.Term      = Convert.ToInt64(term);
                    openCodeString  = tds[2].InnerText.Trim();
                    model.OpenCode1 = Convert.ToInt32(openCodeString.Substring(0, 2));
                    model.OpenCode2 = Convert.ToInt32(openCodeString.Substring(3, 2));
                    model.OpenCode3 = Convert.ToInt32(openCodeString.Substring(6, 2));
                    model.OpenCode4 = Convert.ToInt32(openCodeString.Substring(9, 2));
                    model.OpenCode5 = Convert.ToInt32(openCodeString.Substring(12, 2));
                    model.OpenTime  = Convert.ToDateTime(tds[1].InnerText.Trim());
                    //组装开奖详情
                    var details = GetKaijiangDetails(tds);
                    model.Spare = details;

                    model.DetailUrl = mainUrl;

                    result.Add(model);
                }

                var checkDataHelper = new CheckDataHelper();
                var dbdata          = services.GetListS <OpenCode5DTModel>(currentLottery)
                                      .ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr());
                checkDataHelper.CheckData(dbdata, result.ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr()),
                                          Config.Area, currentLottery);
            }
            catch (Exception ex)
            {
                log.Error(GetType(),
                          string.Format("【{0}】通过主站点抓取开奖列表时发生错误,错误信息【{1}】", Config.Area + currentLottery, ex.Message));
            }

            return(result);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="Account">账户</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        public ActionResult CheckLogin(string Account, string Password, string Token)
        {
            string Msg = "";

            try
            {
                IPScanerHelper objScan   = new IPScanerHelper();
                string         IPAddress = NetHelper.GetIPAddress();
                objScan.IP       = IPAddress;
                objScan.DataPath = Server.MapPath("~/Resource/IPScaner/QQWry.Dat");
                string IPAddressName = objScan.IPLocation();
                string outmsg        = "";
                VerifyIPAddress(Account, IPAddress, IPAddressName, Token);
                //系统管理
                if (Account == ConfigHelper.AppSettings("CurrentUserName"))
                {
                    if (ConfigHelper.AppSettings("CurrentPassword") == Password)
                    {
                        IManageUser imanageuser = new IManageUser();
                        imanageuser.UserId        = "System";
                        imanageuser.Account       = "System";
                        imanageuser.UserName      = "******";
                        imanageuser.Gender        = "男";
                        imanageuser.Code          = "System";
                        imanageuser.LogTime       = DateTime.Now;
                        imanageuser.CompanyId     = "系统";
                        imanageuser.DepartmentId  = "系统";
                        imanageuser.IPAddress     = IPAddress;
                        imanageuser.IPAddressName = IPAddressName;
                        imanageuser.IsSystem      = true;
                        ManageProvider.Provider.AddCurrent(imanageuser);
                        //对在线人数全局变量进行加1处理
                        HttpContext rq = System.Web.HttpContext.Current;
                        rq.Application["OnLineCount"] = (int)rq.Application["OnLineCount"] + 1;
                        Msg = "3";//验证成功
                        Base_SysLogBll.Instance.WriteLog(Account, OperationType.Login, "1", "登陆成功、IP所在城市:" + IPAddressName);
                    }
                    else
                    {
                        return(Content("4"));
                    }
                }
                else
                {
                    Base_User base_user = base_userbll.UserLogin(Account, Password, out outmsg);
                    switch (outmsg)
                    {
                    case "-1":          //账户不存在
                        Msg = "-1";
                        Base_SysLogBll.Instance.WriteLog(Account, OperationType.Login, "-1", "账户不存在、IP所在城市:" + IPAddressName);
                        break;

                    case "lock":        //账户锁定
                        Msg = "2";
                        Base_SysLogBll.Instance.WriteLog(Account, OperationType.Login, "-1", "账户锁定、IP所在城市:" + IPAddressName);
                        break;

                    case "error":       //密码错误
                        Msg = "4";
                        Base_SysLogBll.Instance.WriteLog(Account, OperationType.Login, "-1", "密码错误、IP所在城市:" + IPAddressName);
                        break;

                    case "succeed":     //验证成功
                        IManageUser imanageuser = new IManageUser();
                        imanageuser.UserId        = base_user.UserId;
                        imanageuser.Account       = base_user.Account;
                        imanageuser.UserName      = base_user.RealName;
                        imanageuser.Gender        = base_user.Gender;
                        imanageuser.Password      = base_user.Password;
                        imanageuser.Code          = base_user.Code;
                        imanageuser.Secretkey     = base_user.Secretkey;
                        imanageuser.LogTime       = DateTime.Now;
                        imanageuser.CompanyId     = base_user.CompanyId;
                        imanageuser.DepartmentId  = base_user.DepartmentId;
                        imanageuser.ObjectId      = base_objectuserrelationbll.GetObjectId(imanageuser.UserId);
                        imanageuser.IPAddress     = IPAddress;
                        imanageuser.IPAddressName = IPAddressName;
                        imanageuser.IsSystem      = false;
                        ManageProvider.Provider.AddCurrent(imanageuser);
                        //对在线人数全局变量进行加1处理
                        HttpContext rq = System.Web.HttpContext.Current;
                        rq.Application["OnLineCount"] = (int)rq.Application["OnLineCount"] + 1;
                        Msg = "3";    //验证成功
                        Base_SysLogBll.Instance.WriteLog(Account, OperationType.Login, "1", "登陆成功、IP所在城市:" + IPAddressName);
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
            }
            return(Content(Msg));
        }
Exemplo n.º 32
0
 public void sendToDoctor(NetCommand command)
 {
     NetHelper.SendNetCommand(client, command);
 }
Exemplo n.º 33
0
 private void PostChangeContents()
 {
     RepairMetadata();
     UpdateTileFrameWithNetSend(true);
     NetHelper.SendTEUpdate(ID, Position);
 }
Exemplo n.º 34
0
        public void Validate(ClusterDefinition clusterDefinition)
        {
            Covenant.Requires <ArgumentNullException>(clusterDefinition != null);

            // Verify that custom node label names and values satisfy the
            // following criteria:
            //
            // NAMES:
            //
            //      1. Have an optional reverse domain prefix.
            //      2. Be at least one character long.
            //      3. Start and end with an alpha numeric character.
            //      4. Include only alpha numeric characters, dashes,
            //         underscores or dots.
            //      5. Does not have consecutive dots or dashes.
            //
            // VALUES:
            //
            //      1. Must start or end with an alphnumeric character.
            //      2. May include alphanumerics, dashes, underscores or dots
            //         between the begining and ending characters.
            //      3. Values can be empty.
            //      4. Maximum length is 63 characters.

            foreach (var item in Custom)
            {
                if (item.Key.Length == 0)
                {
                    throw new ClusterDefinitionException($"Custom node label for value [{item.Value}] has no label name.");
                }

                var pSlash = item.Key.IndexOf('/');
                var domain = pSlash == -1 ? null : item.Key.Substring(0, pSlash);
                var name   = pSlash == -1 ? item.Key : item.Key.Substring(pSlash + 1);
                var value  = item.Value;

                // Validate the NAME:

                if (domain != null)
                {
                    if (!NetHelper.IsValidHost(domain))
                    {
                        throw new ClusterDefinitionException($"Custom node label [{item.Key}] has an invalid reverse domain prefix.");
                    }

                    if (domain.Length > 253)
                    {
                        throw new ClusterDefinitionException($"Custom node label [{item.Key}] has a reverse domain prefix that's longer than 253 characters.");
                    }
                }

                if (name.Length == 0)
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] is empty.");
                }
                else if (name.Contains(".."))
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] has consecutive dots.");
                }
                else if (name.Contains("--"))
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] has consecutive dashes.");
                }
                else if (name.Contains("__"))
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] has consecutive underscores.");
                }
                else if (!char.IsLetterOrDigit(name.First()))
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] does not begin with a letter or digit.");
                }
                else if (!char.IsLetterOrDigit(name.Last()))
                {
                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] does not end with a letter or digit.");
                }

                foreach (var ch in name)
                {
                    if (char.IsLetterOrDigit(ch) || ch == '.' || ch == '-' || ch == '_')
                    {
                        continue;
                    }

                    throw new ClusterDefinitionException($"Custom node label name in [{item.Key}] has an illegal character.  Only letters, digits, dashs, underscores and dots are allowed.");
                }

                // Validate the VALUE:

                if (value == string.Empty)
                {
                    continue;
                }

                if (!char.IsLetterOrDigit(value.First()) || !char.IsLetterOrDigit(value.First()))
                {
                    throw new ClusterDefinitionException($"Custom node label value in [{item.Key}={item.Value}] has an illegal value.  Values must start and end with a letter or digit.");
                }

                foreach (var ch in value)
                {
                    if (char.IsLetterOrDigit(ch) || ch == '.' || ch == '-' || ch == '_')
                    {
                        continue;
                    }

                    throw new ClusterDefinitionException($"Custom node label value in [{item.Key}={item.Value}] has an illegal character.  Only letters, digits, dashs, underscores and dots are allowed.");
                }

                if (value.Length > 63)
                {
                    throw new ClusterDefinitionException($"Custom node label value in [{item.Key}={item.Value}] is too long.  Values can have a maximum of 63 characters.");
                }
            }
        }
Exemplo n.º 35
0
        /// <summary>
        ///     副站数据爬取 地址:https://fx.cp2y.com/draw/history_10065_Y/
        /// </summary>
        /// <returns></returns>
        private List <OpenCode8DTModel> GetOpenListFromBackUrl()
        {
            var result = new List <OpenCode8DTModel>();

            try
            {
                var htmlResource = NetHelper.GetUrlResponse(Config.BackUrl, Encoding.GetEncoding("utf-8"));
                if (htmlResource == null)
                {
                    return(result);
                }

                var doc = new HtmlDocument();
                doc.LoadHtml(htmlResource);
                var table = doc.DocumentNode.SelectSingleNode("//table");
                if (table == null)
                {
                    return(result);
                }
                var              trs = table.ChildNodes.Where(node => node.Name == "tr").ToList();
                List <HtmlNode>  tds = null;
                string           term = string.Empty, openCodeString = string.Empty, optimizeUrl = string.Empty;
                OpenCode8DTModel model = null;
                for (var i = 0; i < trs.Count; i++)
                {
                    tds = trs[i].ChildNodes.Where(S => S.Name.ToLower() == "td").ToList();
                    if (tds.Count < 4)
                    {
                        continue;
                    }

                    model           = new OpenCode8DTModel();
                    term            = tds[0].InnerText.Trim();
                    model.OpenTime  = Convert.ToDateTime(tds[1].InnerText.Trim());
                    model.Term      = Convert.ToInt64(term);
                    openCodeString  = tds[2].InnerText.Replace("&nbsp;", "").Replace("\t\t    ", "").Trim();
                    model.OpenCode1 = Convert.ToInt32(openCodeString.Substring(0, 2));
                    model.OpenCode2 = Convert.ToInt32(openCodeString.Substring(2, 2));
                    model.OpenCode3 = Convert.ToInt32(openCodeString.Substring(4, 2));
                    model.OpenCode4 = Convert.ToInt32(openCodeString.Substring(6, 2));
                    model.OpenCode5 = Convert.ToInt32(openCodeString.Substring(8, 2));
                    model.OpenCode6 = Convert.ToInt32(openCodeString.Substring(10, 2));
                    model.OpenCode7 = Convert.ToInt32(openCodeString.Substring(12, 2));
                    model.OpenCode8 = Convert.ToInt32(openCodeString.Substring(14, 2));
                    //组装开奖详情
                    result.Add(model);
                }

                var checkDataHelper = new CheckDataHelper();
                var dbdata          = services.GetListS <OpenCode8DTModel>(currentLottery)
                                      .ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr());
                checkDataHelper.CheckData(dbdata, result.ToDictionary(w => w.Term.ToString(), w => w.GetCodeStr()),
                                          Config.Area, currentLottery);
            }
            catch (Exception ex)
            {
                log.Error(GetType(),
                          string.Format("【{0}】通过副站点抓取开奖列表时发生错误,错误信息【{1}】", Config.Area + currentLottery, ex.Message));
            }

            return(result);
        }
Exemplo n.º 36
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="moudleName">文件存放目录</param>
        /// <param name="encoding">默认为gb2312</param>
        /// <param name="rename">为0时不重命名已上传文件的名称保存,不为0时文件名重命名为filename(若filename为空则用guid命名)</param>
        /// <param name="waterRemarkType">水印图片类型</param>
        /// <param name="filename">保存文件名</param>
        /// <returns></returns>
        protected WebApiRet UploadBase(string moudleName, string encoding = "", string rename = "", int waterRemarkType = 0, string filename = "")
        {
            WebApiRet ret = new WebApiRet();

            ret.RetCode = "0";

            long imgSize = 0;

            if (Request.Files.Count <= 0)
            {
                ret.RetCode = "-1";
                ret.RetMsg  = "请选择文件上传";
            }
            if (ret.RetCode == "0")
            {
                HttpFileCollectionBase files = Request.Files;
                HttpPostedFileBase     file  = files[0];//获取上传的文件

                int    hzIndex = file.FileName.LastIndexOf(".");
                string hz      = file.FileName.Substring(hzIndex + 1);

                if (ret.RetCode == "0")
                {
                    if (hz.ToLower() != "zip")
                    {
                        imgSize = file.InputStream.Length;
                        if (imgSize > ConfigHelper.MaxExcelProcessNum * 1024 * 1024)
                        {
                            ret.RetCode = "-3";
                            ret.RetMsg  = string.Format("文件不能超过{0}M,请选择其他图片上传", ConfigHelper.MaxExcelProcessNum);
                        }
                    }

                    if (ret.RetCode == "0")
                    {
                        int    fileLength = (int)file.InputStream.Length;
                        byte[] bytesRead  = new byte[(int)file.InputStream.Length];
                        Stream fileStream = file.InputStream;
                        fileStream.Read(bytesRead, 0, fileLength);
                        file.InputStream.Close();

                        if (!string.IsNullOrEmpty(filename) && !filename.EndsWith(hz))  //重命名文件名称无后缀时,添加后缀
                        {
                            filename = string.Concat(filename, ".", hz);
                        }
                        else
                        {
                            filename = file.FileName;
                        }

                        ApiRet uploadResult = NetHelper.UploadFile(ConfigHelper.UploadUrlNew, moudleName, filename, bytesRead, encoding, rename);

                        if (uploadResult.RetCode != "0")
                        {
                            ret.RetCode = "-4";
                            ret.RetMsg  = "上传失败";
                            ret.Message = uploadResult;
                        }
                        else
                        {
                            //ret.Message = ConfigHelper.StaticUrl + uploadResult.Message;
                            ret.Message = uploadResult.Message;
                        }
                    }
                }
            }
            return(ret);
        }
Exemplo n.º 37
0
        /// <summary>处理Span集合。默认输出日志,可重定义输出控制台</summary>
        protected override void ProcessSpans(ISpanBuilder[] builders)
        {
            if (builders == null)
            {
                return;
            }

            // 剔除项
            if (Excludes != null)
            {
                builders = builders.Where(e => !Excludes.Any(y => y.IsMatch(e.Name))).ToArray();
            }
            builders = builders.Where(e => !e.Name.EndsWithIgnoreCase("/Trace/Report")).ToArray();
            if (builders.Length == 0)
            {
                return;
            }

            // 初始化
            Init();

            // 构建应用信息
            var info = new AppInfo(_process);

            try
            {
                // 调用WindowApi获取进程的连接数
                var tcps = NetHelper.GetAllTcpConnections();
                if (tcps != null && tcps.Length > 0)
                {
                    var pid = Process.GetCurrentProcess().Id;
                    info.Connections = tcps.Count(e => e.ProcessId == pid);
                }
            }
            catch { }

            // 发送,失败后进入队列
            var model = new TraceModel
            {
                AppId    = AppId,
                AppName  = AppName,
                ClientId = ClientId,
                Version  = _version,
                Info     = info,

                Builders = builders
            };

            try
            {
                // 检查令牌
                if (!AppSecret.IsNullOrEmpty())
                {
                    CheckAuthorize();
                }

                var rs = Client.Invoke <TraceResponse>("Trace/Report", model);
                // 处理响应参数
                if (rs != null)
                {
                    if (rs.Period > 0)
                    {
                        Period = rs.Period;
                    }
                    if (rs.MaxSamples > 0)
                    {
                        MaxSamples = rs.MaxSamples;
                    }
                    if (rs.MaxErrors > 0)
                    {
                        MaxErrors = rs.MaxErrors;
                    }
                    if (rs.Timeout > 0)
                    {
                        Timeout = rs.Timeout;
                    }
                    if (rs.Excludes != null)
                    {
                        Excludes = rs.Excludes;
                    }
                }
            }
            catch (ApiException ex)
            {
                Log?.Error(ex + "");
            }
            catch (Exception ex)
            {
                //XTrace.WriteException(ex);
                Log?.Error(ex + "");
                //throw;

                if (_fails.Count < MaxFails)
                {
                    _fails.Enqueue(model);
                }
                return;
            }

            // 如果发送成功,则继续发送以前失败的数据
            while (_fails.Count > 0)
            {
                model = _fails.Dequeue();
                try
                {
                    Client.Invoke <Object>("Trace/Report", model);
                }
                catch (ApiException ex)
                {
                    Log?.Error(ex + "");
                }
                catch (Exception ex)
                {
                    XTrace.WriteLine("二次上报失败,放弃该批次采样数据,{0}", model.Builders.FirstOrDefault()?.StartTime.ToDateTime());
                    XTrace.WriteException(ex);
                    //Log?.Error(ex + "");

                    // 星尘收集器上报,二次失败后放弃该批次数据,因其很可能是错误数据
                    //_fails.Enqueue(model);
                    break;
                }
            }
        }
        public async Task <SignUpResponseModel> SignUp(SignUpRequestModel model)
        {
            // Get DeviceTag
            var deviceTagResult = LocalDeviceTag;

            if (deviceTagResult.HasLogTag(LogTag.MissingDeviceTag))
            {
                Log.Reports(deviceTagResult.Reports, Request);
                return(SignUpResponseModel.InvalidEntry);
            }
            var deviceTag = deviceTagResult.Value;

            //Get IpAddress
            var clientIpAddress = NetHelper.GetClientIpAddressFrom(Request);

            // Validate model
            if (ModelState.IsValid == false)
            {
                Log.Error(LogTag.InvalidSignUpModelState, Request, new { message = ModelState.Values, model });
                return(SignUpResponseModel.InvalidEntry);
            }
            // Verify email isn't already used
            if ((await UserManager.FindByNameAsync(model.Email)) != null)
            {
                Log.Info(LogTag.SignUpEmailAlreadyInUse, Request, new { model.Email });
                return(SignUpResponseModel.EmailAlreadyInUse);
            }
            // Create AspNet user
            var aspNetUser = new AspNetUser {
                UserName = model.Email, Email = model.Email, UiCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
            };
            var result = await UserManager.CreateAsync(aspNetUser, model.Password);

            if (!result.Succeeded)
            {
                Log.Error(LogTag.AspNetUserCreationError, Request, new { result.Errors });
                return(SignUpResponseModel.UnhandledIssue);
            }

            // Regulate new user
            var user = await UserFromSignUpModel(model, aspNetUser.Id);

            IAccountRegulator regulator = Injection.Kernel.Get <IAccountRegulator>();
            var logReports = regulator.RegulateNewUser(model.Email, model.Password, user, deviceTag, clientIpAddress);

            Log.Reports(logReports, Request);

            //Save Hellolingo user profile
            var newUser = await StoreNewUser(user);

            if (newUser == null)
            {
                Log.Error(LogTag.SignUpUserCreationReturnedNull, Request, new { aspNetUser, model });
                await UserManager.DeleteAsync(aspNetUser);

                return(SignUpResponseModel.UnhandledIssue);
            }

            // Complete non-critical sign up process
            try {
                // Link device to new user
                var ipV4 = NetHelper.GetClientIpAddressAsUIntFrom(Request);
                await DeviceTagManager.LinkDeviceToUser(deviceTag, newUser.Id);

                // Send Email Verification
                if (newUser.StatusId == UserStatuses.PendingEmailValidation)
                {
                    await SendConfirmationEmailAsync(aspNetUser, newUser, aspNetUser.Email);
                }

                // Add Welcome Mail
                string message;
                switch (CultureHelper.GetCurrentCulture())
                {
                case "fr": message = "\n\nNous sommes ravis de vous compter comme nouveau membre de notre communauté. Nous vous recommandons d’explorer la fonction de recherche de partenaires linguistiques et d’envoyer autant d'emails que vous le souhaitez à des partenaires potentiels. Ils vous répondront ici dans votre messagerie. Vous pouvez aussi vous rendre dans la section de chat vocal et textuel pour commencer à pratiquer tout de suite dans les salons de chat publiques et privés (la fonction chat vocal est disponible en conversation privée)." +
                                     "\n\nSi vous avez des soucis, des questions ou des idées, n’hésitez pas à nous contacter via le formulaire de contact ou en répondant directement à cet email. HelloLingo est votre communauté et nous comptons sur vous pour la garder conviviale.Veillez à vous en servir dans un but d’apprentissage linguistique uniquement, soyez respectueux et pensez à reporter les bugs et dérangements quand vous les voyez. C’est la meilleure façon de protéger et d’améliorer HelloLingo." +
                                     "\n\nApprenez et prospérez !\nL’équipe HelloLingo"; break;

                case "de": message = "\n\nWir sind erfreut, dich als neues Mitglied unserer Sprachlern - Gemeinschaft zu begrüßen. Wir empfehlen dir die Finden - Funktion zu erkunden und so viele Emails an potentielle Partner zu versenden wie du möchtest. Sie werden dir genau hier antworten, in deiner Mailbox. Du kannst auch zum Text & Voice Chat gehen und sofort beginnen, in öffentlichen oder privaten Räumen zu lernen. Voice Chat Unterhaltungen können von einem beliebigen privaten Raum gestartet werden." +
                                     "\n\nSolltest du Probleme, Fragen oder Anregungen haben, lass es uns bitte wissen. Dafür kannst du das Kontaktformular benutzen oder direkt auf diese Email antworten. Hellolingo ist deine Community und wir zählen auf deinen Beitrag dazu, dass sie großartig bleibt. Bitte verwende sie nur zum Sprachen lernen, sei rücksichtsvoll und denke darüber nach, Störungen oder Fehler zu melden, sobald du sie siehst.Das ist der beste Weg, um Hellolingo zu bewahren und zu verbessern." +
                                     "\n\nLearn and prosper!\nThe Hellolingo Team"; break;

                case "ko": message = "\n\n우리는 귀하가 언어습득 모임의 새 회원이 되신것을 매우 반갑게 생각합니다. 당신이 우리의 다양한 기능을 탐색해 보고 잠재적 파트너에게 많은 이메일을 보내시는것을 추천합니다. 그들은 당신의 메일박스에 회신할 것입니다. 또한 텍스트&보이스 채팅에서 오픈된 혹은 개인적 채팅룸에서 즉시 연습하실수 있습니다. " +
                                     "\n\n만일 다른 사항, 질문 혹은 아이디어가 있으시면 이 이메일로 회신을 주시면 감사하겠습니다. Hellolingo는 당신의 커뮤니티이고 항상 멋지게 유지되길 기대하고 있습니다. 반드시 이 사이트는 언어를 배우는 것으로만 사용해 주시고 다른이들을 배려하며 불편사항이나 버그를 발견하시면 말씀해 주시기 바랍니다. 이것은 Hellolingo를 보호하고 발전시키는 가장 좋은 방법입니다. " +
                                     "\n\n배우고 발전하자!\nHellolingo 팀 드림"; break;

                case "nl": message = "\n\nWe zijn heel verheugd om jou als een nieuwe deelnemer in onze gemeenschap te mogen verwelkomen.We raden je aan om vooral de find feature uit te proberen, en zoveel mogelijk e - mails te versturen naar potentiele partners.Ze zullen je hier beantwoorden, in jouw mailbox. Je kan ook naar de tekst&voice chat gaan en direct beginnen met oefenen in publieke of privé kamers. Chats met voice gesprekken kunnen geïnitieerd worden vanuit elke privé kamer." +
                                     "\n\nAls je enige problemen, vragen of ideeën hebt, laat het ons alstublieft weten via onze contact formulier, of door direct op deze e-mail te reageren. Hellolingo is jouw gemeenschap en we rekenen op jou om het aangenaam te houden.Zorg ervoor dat je het alleen gebruikt om talen te oefenen, altijd rekening houdt met anderen en niet vergeet om onderbrekingen en bugs te rapporteren wanneer je die ervaart. Dit is de beste manier waarop Hellolingo beschermt en verbetert kan worden." +
                                     "\n\nLeer en wees succesvol!\nHet Hellolingo Team"; break;

                case "zh-CN": message = "\n\n非常开心你能加入我们的语言学习社区。我们希望你能尽可能的去探索和尝试各种功能,你可以随时发邮件给你的潜在语言搭档,他们的回复会出现在你的邮箱里。你也可以使用文本 & 语音聊天功能在公共聊天室或者私人聊天室立刻开始进行你的语言练习。任何私人聊天室都是可以进行语音对话的。" +
                                        "\n\n如果你有任何疑问, 建议或者想法,请随时通过上述联系方式来联系我们。hellolingo是属于你的语言社区,你有责任把它变的越来越好,不是吗?:-)同时,我们希望你在这里进行的只有语言学习这一件事,也请在学习的同时,去关心和体谅他人。如果你遇到了任何bug,请及时反馈给我们,这是让hellolingo能更好的为你服务的最佳方式。" +
                                        "\n祝:学习进步,生活开心。\n\nhellolingo团队敬上"; break;

                default: message = "\n\nWe're thrilled to have you as a new member of our language learning community. We recommend you to explore the Find feature and send as many emails as you want to potential partners. They'll reply to you right here, in you mailbox. You can also go to the Text & Voice chat and start practicing immediately in public or private rooms. Voice chat conversations can be initiated from any private room." +
                                   "\n\nIf you have any issues, questions or ideas, please let us know from the contact form or by replying to this email directly. Hellolingo is your community and we count on you to keep it awesome. Make sure to use it for language learning only, always be considerate of others and think about reporting disruptions or bugs when you see them. This is the best way to protect and improve Hellolingo." +
                                   "\n\nLearn and prosper!\nThe Hellolingo Team"; break;
                    //"\n\nP.S.: We're looking to translate this message in the following languages: 日本語. Email us if you can help.";
                }
                Entity.Mails.Add(new Mail {
                    When             = DateTime.Now,
                    FromId           = 1, ToId = user.Id, FromStatus = MailStatuses.Deleted, ToStatus = MailStatuses.New,
                    RegulationStatus = MailRegulationStatuses.ManualPass, NotifyStatus = NotifyStatuses.Blocked,
                    Subject          = "Welcome to Hellolingo!", Message = message, ReplyToMail = null
                });
                await Entity.SaveChangesAsync();
            } catch (Exception ex) {
                Log.Error(LogTag.CompletingSignUpFailed, Request, new { aspNetUser, model, ex });
            }

            // Sign new user in
            return(await SignInCreatedUser(aspNetUser.Id));
        }
Exemplo n.º 39
0
        public static async Task <BookmarkView> Insert(Bookmark bookmark, bool isNotAllowNet)
        {
            if (bookmark == null)
            {
                throw new ArgumentNullException(nameof(bookmark));
            }
            using (DbHelper db = new DbHelper())
            {
                // 处理URL
                bookmark.Url = bookmark.Url.Trim();
                if (await BookmarkRepository.IsExistUrl(db, bookmark.CatalogId, bookmark.Url))
                {
                    throw new Exception("该目录已存在此URL,请勿重复增加");
                }
                // 处理title
                if (string.IsNullOrWhiteSpace(bookmark.Title))
                {
                    if (!isNotAllowNet)
                    {
                        bookmark.Title = await NetHelper.GetTitle(bookmark.Url);
                    }
                }
                bookmark.Title = bookmark.Title.Replace(System.Environment.NewLine, " ");
                // 处理Site
                string host      = NetHelper.GetHost(bookmark.Url);
                Site   site      = null;
                bool   isNewSite = false;
                if (await SiteRepository.IsExist(db, host))
                {
                    site = await SiteRepository.GetSiteWithHostAsync(db, host);

                    isNewSite = false;
                }
                else
                {
                    byte[] icon = null;
                    if (isNotAllowNet)
                    {
                        icon = ObjectHelper.ImageToByte(BookmarkManager.Properties.Resources.Hyperlink);
                    }
                    else
                    {
                        icon = NetHelper.GetFavicon(bookmark.Url);
                    }
                    site = new Site {
                        Id = Guid.NewGuid().ToString(), Host = host, Icon = icon
                    };
                    isNewSite = true;
                }
                bookmark.SiteId = site.Id;
                // 修改数据库
                using (var trans = db.BeginTransaction())
                {
                    try
                    {
                        if (isNewSite)
                        {
                            await SiteRepository.Insert(db, site);
                        }
                        await BookmarkRepository.Insert(db, bookmark);

                        trans.Commit();
                    }
                    catch (Exception)
                    {
                        trans.Rollback();
                        throw;
                    }
                }
                return(await BookmarkViewRepository.GetById(db, bookmark.Id));
            }
        }
Exemplo n.º 40
0
 public void SetHost(HomeGenieService hg, SchedulerItem item)
 {
     homegenie = hg;
     schedulerItem = item;
     Reset();
     netHelper = new NetHelper(homegenie);
     serialPortHelper = new SerialPortHelper();
     tcpClientHelper = new TcpClientHelper();
     udpClientHelper = new UdpClientHelper();
     mqttClientHelper = new MqttClientHelper();
     knxClientHelper = new KnxClientHelper();
     schedulerHelper = new SchedulerHelper(homegenie);
     programHelper = new ProgramHelperBase(homegenie);
 }
Exemplo n.º 41
0
        /// <summary>处理收到的数据</summary>
        /// <param name="pk"></param>
        /// <param name="remote"></param>
        protected override Boolean OnReceive(Packet pk, IPEndPoint remote)
        {
            // 过滤自己广播的环回数据。放在这里,兼容UdpSession
            if (!Loopback && remote.Port == Port)
            {
                if (!Local.Address.IsAny())
                {
                    if (remote.Address.Equals(Local.Address))
                    {
                        return(false);
                    }
                }
                else
                {
                    foreach (var item in NetHelper.GetIPsWithCache())
                    {
                        if (remote.Address.Equals(item))
                        {
                            return(false);
                        }
                    }
                }
            }

#if !__MOBILE__
            // 更新全局远程IP地址
            NewLife.Web.WebHelper.UserHost = remote?.Address + "";
#endif
            LastRemote = remote;

            StatReceive?.Increment(pk.Count);
            if (base.OnReceive(pk, remote))
            {
                return(true);
            }

            // 分析处理
            var e = new ReceivedEventArgs(pk)
            {
                UserState = remote
            };

            // 为该连接单独创建一个会话,方便直接通信
            var session = CreateSession(remote);
            // 数据直接转交给会话,不再经过事件,那样在会话较多时极为浪费资源
            if (session is UdpSession us)
            {
                us.OnReceive(e);
            }
            else
            {
                // 没有匹配到任何会话时,才在这里显示日志。理论上不存在这个可能性
                if (Log.Enable && LogReceive)
                {
                    WriteLog("Recv [{0}]: {1}", e.Length, e.ToHex(32, null));
                }
            }

            if (session != null)
            {
                RaiseReceive(session, e);
            }

            return(true);
        }
Exemplo n.º 42
0
        private QiZi[] winQizi; //标记连成一条线的五个棋子

        #endregion Fields

        #region Constructors

        public Board(int r, Graphics g, int w, int rectPix, bool isServer, string ip)
            : this(r, g, w, rectPix)
        {
            this.isServer = isServer;
            localnet = new NetHelper(isServer, r, g, ip);
        }
Exemplo n.º 43
0
        private void DataManaging(ContextKey key)
        {
            int streamHashCode = key.NetStream.GetHashCode();
            int headerLen      = this.contractHelper.MessageHeaderLength;

            while ((key.NetStream.DataAvailable) && (!this.stop))
            {
                byte[] rentBuff = null;                 //每次分派的消息中,最多有一个rentBuff

                try
                {
                    #region 构造 RoundedMessage
                    NetHelper.ReceiveData(key.NetStream, key.Buffer, 0, headerLen);
                    IMessageHeader header = this.contractHelper.ParseMessageHeader(key.Buffer, 0);
                    if (!this.contractHelper.ValidateMessageToken(header))
                    {
                        this.DisposeOneConnection(streamHashCode, DisconnectedCause.MessageTokenInvalid);
                        return;
                    }

                    RoundedMessage requestMsg = new RoundedMessage();
                    requestMsg.ConnectID = streamHashCode;
                    requestMsg.Header    = header;

                    if (!key.FirstMessageExist)
                    {
                        requestMsg.IsFirstMessage = true;
                        key.FirstMessageExist     = true;
                    }

                    if ((headerLen + header.MessageBodyLength) > this.maxMessageSize)
                    {
                        this.DisposeOneConnection(streamHashCode, DisconnectedCause.MessageSizeOverflow);
                        return;
                    }

                    if (header.MessageBodyLength > 0)
                    {
                        if ((header.MessageBodyLength + headerLen) <= this.recieveBuffSize)
                        {
                            NetHelper.ReceiveData(key.NetStream, key.Buffer, 0, header.MessageBodyLength);
                            requestMsg.Body = key.Buffer;
                        }
                        else
                        {
                            rentBuff = this.bufferPool.RentBuffer(header.MessageBodyLength);

                            NetHelper.ReceiveData(key.NetStream, rentBuff, 0, header.MessageBodyLength);
                            requestMsg.Body = rentBuff;
                        }
                    }
                    #endregion

                    bool       closeConnection = false;
                    NetMessage resMsg          = this.tcpStreamDispatcher.DealRequestData(requestMsg, ref closeConnection);

                    if (rentBuff != null)
                    {
                        this.bufferPool.GivebackBuffer(rentBuff);
                    }

                    if (closeConnection)
                    {
                        this.DisposeOneConnection(streamHashCode, DisconnectedCause.OtherCause);
                        return;
                    }

                    if ((resMsg != null) && (!this.stop))
                    {
                        byte[] bRes = resMsg.ToStream();
                        key.NetStream.Write(bRes, 0, bRes.Length);

                        if (this.ServiceCommitted != null)
                        {
                            this.ServiceCommitted(streamHashCode, resMsg);
                        }
                    }
                }
                catch (Exception ee)
                {
                    if (ee is System.IO.IOException)                    //正在读写流的时候,连接断开
                    {
                        this.DisposeOneConnection(streamHashCode, DisconnectedCause.NetworkError);
                        break;
                    }
                    else
                    {
                        this.esbLogger.Log(ee.GetType().ToString(), ee.Message, "ESFramework.Network.Tcp.AgileTcp", ErrorLevel.Standard);
                    }

                    ee = ee;
                }
            }

            key.IsDataManaging = false;
        }