예제 #1
0
        public bool ApplyNetworkSettings()
        {
            uint interfaceIndex = _currentNetworkInterface.Index;

            if (interfaceIndex == 0)
            {
                return(false);
            }

            try
            {
                NetworkUtil.SetLowestTapMetric(interfaceIndex);
            }
            catch (NetworkUtilException e)
            {
                _logger.Error("Failed to apply network settings. Error code: " + e.Code);
                return(false);
            }

            return(true);
        }
예제 #2
0
        public static void StartServerPool()
        {
            if (ServerManager.ShadowsocksList.Count < 1)
            {
                return;
            }

            List <int> portInUse = NetworkUtil.GetPortInUse(2000);

            foreach (Shadowsocks server in ServerManager.ShadowsocksList)
            {
                int listen = NetworkUtil.GetAvailablePort(2000, portInUse);
                if (listen > 0)
                {
                    ServerManager.AddProcess(server, listen);
                    portInUse.Add(listen);
                }
            }

            SettingManager.IsServerPoolEnabled = true;
        }
예제 #3
0
        public static IPAddress ChooseAddressFromDNS(string targetName)
        {
            Exception ex;

            IPAddress[] dnsAddresses = NetworkUtil.GetDnsAddresses(targetName, ref ex);
            foreach (IPAddress ipaddress in dnsAddresses)
            {
                if (ipaddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    return(ipaddress);
                }
            }
            foreach (IPAddress ipaddress2 in dnsAddresses)
            {
                if (ipaddress2.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    return(ipaddress2);
                }
            }
            return(null);
        }
예제 #4
0
        public void DownloadLatestMonomod(string targetFolder)
        {
            Console.WriteLine("Retrieving MonoMod latest release");
            var releaseInfos = NetworkUtil.GetJson("http://api.github.com/repos/0x0ade/MonoMod/releases/latest");

            var assetInfos = releaseInfos.Element("root").Elements("assets")
                             .First(a => {
                var name = a.Element("name").Value;
                return(name.Contains("net35") && name.EndsWith(".zip"));
            });

            var fileUrl  = assetInfos.Element("browser_download_url").Value;
            var filePath = Path.Combine(targetFolder, "monomod.zip");

            Console.WriteLine("Retrieved MonoMod latest release");

            Console.WriteLine("Download URL: " + fileUrl);
            Console.WriteLine("Downloading MonoMod");
            NetworkUtil.DownloadFile(fileUrl, filePath);
            Console.WriteLine("Downloaded MonoMod");
        }
예제 #5
0
        public void T010_TestUnauthenticatedLogin()
        {
            TestHelper.InMethod();
            // We want to use our own LoginService for this test, one that
            // doesn't require authentication.
            LoginService loginService = new LLStandaloneLoginService((UserManagerBase)m_commsManager.UserService, "Hello folks", new TestInventoryService(),
                                                                     m_commsManager.NetworkServersInfo, false, new LibraryRootFolder(String.Empty), m_regionConnector);

            Hashtable loginParams = new Hashtable();

            loginParams["first"]  = m_firstName;
            loginParams["last"]   = m_lastName;
            loginParams["passwd"] = "boingboing";

            ArrayList sendParams = new ArrayList();

            sendParams.Add(loginParams);
            sendParams.Add(m_capsEndPoint);                    // is this parameter correct?
            sendParams.Add(new Uri("http://localhost:8002/")); // is this parameter correct?

            XmlRpcRequest request = new XmlRpcRequest("login_to_simulator", sendParams);

            IPAddress      tmpLocal = Util.GetLocalHost();
            IPEndPoint     tmpEnd   = new IPEndPoint(tmpLocal, 80);
            XmlRpcResponse response = m_loginService.XmlRpcLoginMethod(request, tmpEnd);

            Hashtable responseData = (Hashtable)response.Value;

            Assert.That(responseData["first_name"], Is.EqualTo(m_firstName));
            Assert.That(responseData["last_name"], Is.EqualTo(m_lastName));
            Assert.That(
                responseData["circuit_code"], Is.GreaterThanOrEqualTo(0) & Is.LessThanOrEqualTo(Int32.MaxValue));

            Regex capsSeedPattern
                = new Regex("^http://"
                            + NetworkUtil.GetHostFor(tmpLocal, m_regionExternalName)
                            + ":9000/CAPS/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}0000/$");

            Assert.That(capsSeedPattern.IsMatch((string)responseData["seed_capability"]), Is.True);
        }
예제 #6
0
        public override BaseState Run()
        {
            var eventNames = BotConstants.sampleEventNames[new Random().Next(6)];

            var eventModel = new EventRequestModel
            {
                event_datetime = DateTime.Now,
                event_common   = this.eventCommon,
                event_dic      = new Dictionary <string, string>()
            };

            foreach (var eventName in eventNames)
            {
                eventModel.event_name = eventName;

                if (eventName == BotConstants.LOGIN_EVENT)
                {
                    eventModel.event_dic.Add("user_id", Guid.NewGuid().ToString());
                }

                if (eventName == BotConstants.LOGOUT_EVENT)
                {
                    eventModel.event_dic.Remove("user_id");
                }
            }

            var httpRequestModel = new HttpRequestModel
            {
                Url        = "",
                HttpMethod = HttpMethod.Post,
                Headers    = new Dictionary <string, string> {
                    { "content-type", "application/json" }
                },
                Body = JsonConvert.SerializeObject(eventModel)
            };

            NetworkUtil.HttpRequestAsync(httpRequestModel).Wait();

            return(this);
        }
예제 #7
0
        private void ApplyNetworkSettings()
        {
            var tapGuid = GetTapGuid();

            if (tapGuid == null)
            {
                return;
            }

            try
            {
                var localInterfaceIp = NetworkUtil.GetBestInterfaceIp(_tapAdapterId).ToString();

                NetworkUtil.DeleteDefaultGatewayForIface(tapGuid.Value, localInterfaceIp);
                NetworkUtil.AddDefaultGatewayForIface(tapGuid.Value, localInterfaceIp);
                NetworkUtil.SetLowestTapMetric(tapGuid.Value);
            }
            catch (NetworkUtilException e)
            {
                _logger.Error("Failed to apply network settings. Error code: " + e.Code);
            }
        }
예제 #8
0
        protected override void OnRun(byte[] buffer)
        {
            try
            {
                DataPacket packet = server.Network.GetPacket((short)server.Network.GetTypeOf(buffer));
                if (packet != null)
                {
                    packet.Buffer = buffer;
                    if (packet.IsValid)
                    {
                        packet.Decode();
                        LogFactory.GetLog(server.Name)
                        .LogInfo($"Received Packet [{packet.Pid().ToString()}] [{packet.Buffer.Length}]");
                        LogFactory.GetLog(server.Name).LogInfo($"\n{NetworkUtil.DumpPacket(packet.Buffer)}");
                        HandlePacket(packet);
                    }
                    else
                    {
                        LogFactory.GetLog(server.Name)
                        .LogWarning(
                            $"Received Invalid Packet [{packet.Pid().ToString()}] [{packet.Buffer.Length}]");
                        packet.Decode();
                        LogFactory.GetLog(server.Name).LogInfo($"\n{NetworkUtil.DumpPacket(packet.Buffer)}");
                    }
                }
                else
                {
                    LogFactory.GetLog(server.Name)
                    .LogWarning($"Unknown Packet with ID {(short) server.Network.GetTypeOf(buffer)}.");
                    LogFactory.GetLog(server.Name).LogInfo($"\n{NetworkUtil.DumpPacket(buffer)}");
                }
            }
            catch (Exception e)
            {
                LogFactory.GetLog(server.Name).LogFatal(e);
            }

            base.OnRun(buffer);
        }
예제 #9
0
        /// <summary>
        /// Convert from a <see cref="System.String"/> value to a <see cref="System.Net.IPAddress"/> instance.
        /// </summary>
        /// <param name="context">
        /// A <see cref="System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.
        /// </param>
        /// <param name="culture">
        /// The <see cref="System.Globalization.CultureInfo"/> to use as the current culture.
        /// </param>
        /// <param name="value">
        /// The value that is to be converted.
        /// </param>
        /// <returns>
        /// A <see cref="System.Net.IPAddress"/> if successful.
        /// </returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                try
                {
                    string host = (string)value;
                    if (!NetworkUtil.IsIPAddress(host))
                    {
                        throw new ArgumentException($"Cannot parse '{host}' to a valid IPAddress.");
                    }

                    return(IPAddress.Parse(host));
                }
                catch (Exception ex)
                { throw new TypeConvertException(value, typeof(IPAddress), ex); }
            }
            else
            {
                throw new TypeConvertException(value, typeof(IPAddress));
            }
        }
예제 #10
0
    public static void onCreateTable(int gameid, int roomid, long money, int maxplayer, int choinhanh, String password)
    {
        Message msg = new Message(CMDClient.CMD_CREATE_TABLE);

        try
        {
            BaseInfo.gI().numberPlayer = maxplayer;
            msg.writer().WriteInt(gameid);
            msg.writer().WriteInt(roomid);
            msg.writer().WriteLong(money);
            msg.writer().WriteInt(maxplayer);
            msg.writer().WriteInt(choinhanh);
            msg.writer().WriteUTF(password);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block\

            Debug.LogException(e);
        }
        NetworkUtil.GI().sendMessage(msg);
    }
예제 #11
0
 /**
  *
  * @param username
  * @param pass
  * @param type
  *            : 1-facebook 2-choingay 3-gmail 4-login normal
  * @param imei
  * @param link_avatar
  * @param tudangky
  *            : 1 la tu dang ky, 0
  * @param displayName
  * @param accessToken
  * @param regPhone
  */
 public void login(sbyte type, string username, string pass,
                   string imei, string link_avatar, sbyte tudangky, string displayName,
                   string accessToken, string regPhone)
 {
     BaseInfo.gI().isPurchase = false;
     if (checkNetWork())
     {
         //if (NetworkUtil.GI().isConnected()) {
         //    NetworkUtil.GI().close();
         //}
         //if(net != null) {
         //    StartCoroutine(net.Start());
         //}
         Message msg = new Message(CMDClient.CMD_LOGIN_NEW);
         try {
             msg.writer().WriteByte(type);
             msg.writer().WriteUTF(username);
             msg.writer().WriteUTF(pass);
             msg.writer().WriteUTF(Res.version);
             msg.writer().WriteByte(CMDClient.PROVIDER_ID);
             msg.writer().WriteUTF(imei);
             msg.writer().WriteUTF(link_avatar);
             msg.writer().WriteByte(tudangky);
             msg.writer().WriteUTF(displayName);
             msg.writer().WriteUTF(accessToken);
             msg.writer().WriteUTF(regPhone);
         } catch (Exception ex) {
             Debug.LogException(ex);
         }
         //SendData.isLogin = true;
         NetworkUtil.GI().sendMessage(msg);
         BaseInfo.gI().username = username;
         BaseInfo.gI().pass     = pass;
     }
     else
     {
         gameControl.panelMessageSytem.onShow("Vui lòng kiểm tra kết nối mạng!");
     }
 }
예제 #12
0
    public static void onFinalMauBinh(int[] card)
    {
        Message msg = new Message(CMDClient.CMD_FINAL_MAUBINH);

        try {
            // msg.writer().WriteShort(1);
            // SerializerHelper.WriteInt(card);
            byte[] data = new byte[card.Length];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)card[i];
            }
            // SerializerHelper.writeArrayInt(card);
            msg.writer().WriteInt(data.Length);
            msg.writer().Write(data, 0, data.Length);
        } catch (Exception e) {
            Debug.LogException(e);
        }
        // SerializerHelper.WriteInt(Integer.parseInt(tbid));

        NetworkUtil.GI().sendMessage(msg);
    }
예제 #13
0
            public void Validate304HasNoHeaders()
            {
                var serviceUri = new Uri("http://" + Environment.MachineName + ":" + NetworkUtil.GetRandomPortNumber() + "/" + System.Guid.NewGuid() + "/Service/");

                using (WebServiceHost host = new WebServiceHost(typeof(NotModifiedHeadersBug), serviceUri))
                {
                    host.Open();
                    try
                    {
                        HttpWebRequest setCustomerNameToNullRequest = CreateRequest(serviceUri, "Customers(1)/Name/$value", "DELETE", UnitTestsUtil.AtomFormat, Tuple.Create <string, string>("If-Match", "*"));

                        HttpWebResponse setCustomerNameToNullResponse = (HttpWebResponse)setCustomerNameToNullRequest.GetResponse();
                        Assert.AreEqual(HttpStatusCode.NoContent, setCustomerNameToNullResponse.StatusCode);
                        string         etag = setCustomerNameToNullResponse.Headers["ETag"];
                        HttpWebRequest getCustomerNameRequest = CreateRequest(serviceUri, "Customers(1)/Name", "GET", UnitTestsUtil.AtomFormat, Tuple.Create <string, string>("If-None-Match", "*"));
                        try
                        {
                            getCustomerNameRequest.GetResponse();
                            throw new InvalidOperationException("Should have failed with 304");
                        }
                        catch (WebException exc)
                        {
                            var response = ((HttpWebResponse)exc.Response);
                            Assert.AreEqual(HttpStatusCode.NotModified, response.StatusCode);
                            Assert.AreEqual(6, response.Headers.Count);
                            Assert.AreEqual("0", response.Headers["Content-Length"]);
                            Assert.AreEqual("nosniff", response.Headers["X-Content-Type-Options"]);
                            Assert.AreEqual("Microsoft-HTTPAPI/2.0", response.Headers["Server"]);
                            Assert.AreEqual("MyCustomValue", response.Headers["MyCustomHeader"]);
                            Assert.IsTrue(response.Headers["ETag"] != null);
                            Assert.IsTrue(response.Headers["Date"] != null);
                        }
                    }
                    finally
                    {
                        host.Close();
                    }
                }
            }
예제 #14
0
        void AssetSupplier.SupplyAsset(AssetRequest assetRequest, AssetSupplyListener listener)
        {
            Debug.Log("Begin fetching assets.");
            inteceptHelper.OnBeginSession(listener);
            var assetRequestJson = JsonUtility.ToJson(assetRequest);

            Debug.Log("Forward requst to Web.... " + assetRequestJson);
            WWWForm wwwForm = new WWWForm();

            wwwForm.AddField("assetRequestInJson", assetRequestJson);
            UnityWebRequest www = UnityWebRequest.Post(serverURL, wwwForm);

            NetworkUtil.ProcessWebRequest(www, (givenWebReq) => {
                bool didSuccess = false;
                if (givenWebReq.isNetworkError || givenWebReq.isHttpError)
                {
                    Debug.Log(givenWebReq.error);
                }
                else
                {
                    Debug.Log(Encoding.UTF8.GetString(givenWebReq.downloadHandler.data));
                    var assetPick = RequiredFuncs.FromJson <AssetPick>(givenWebReq.downloadHandler.data);
                    if (assetPick != null)
                    {
                        if (assetPick.units.Count > 0)
                        {
                            didSuccess = true;
                            listener.supplyTaker.Take(assetPick);
                        }
                    }
                }
                if (!didSuccess)
                {
                    listener.supplyTaker.None();
                }
                inteceptHelper.OnEndSession(listener);
            }
                                          );
        }
예제 #15
0
파일: SendData.cs 프로젝트: ping203/SoDoVIP
    public static void onFireCardTL(int[] card)
    {
        Message msg = new Message(CMDClient.CMD_FIRE_CARD);

        try {
            msg.writer().WriteShort(1);
            // SerializerHelper.WriteInt(card);

            sbyte[] data = new sbyte[card.Length];
            msg.writer().WriteInt(data.Length);
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (sbyte)card[i];
                msg.writer().WriteByte(card[i]);
            }
        } catch (Exception ex) {
            Debug.LogException(ex);
        }
        // SerializerHelper.WriteInt(Integer.parseInt(tbid));

        NetworkUtil.GI().sendMessage(msg);
    }
예제 #16
0
        public static bool StartServer()
        {
            Config     config    = SettingManager.Configuration;
            List <int> portInUse = NetworkUtil.GetPortInUse(2000);

            // proxy port
            if (config.SystemProxyPort == 0 || portInUse.Contains(config.SystemProxyPort))
            {
                config.SystemProxyPort = NetworkUtil.GetAvailablePort(2000, portInUse);
                portInUse.Add(config.SystemProxyPort);
            }
            else
            {
                portInUse.Add(config.SystemProxyPort);
            }

            // shadowsocks port
            if (config.LocalSocks5Port == 0 || portInUse.Contains(config.LocalSocks5Port))
            {
                config.LocalSocks5Port = NetworkUtil.GetAvailablePort(2000, portInUse);
                portInUse.Add(config.LocalSocks5Port);
            }
            else
            {
                portInUse.Add(config.LocalSocks5Port);
            }

            if (!ProcPrivoxy.Start(config.SystemProxyPort, config.LocalSocks5Port))
            {
                return(false);
            }

            if (SettingManager.RemoteServer != null)
            {
                return(ServerManager.AddProcess(SettingManager.RemoteServer, config.LocalSocks5Port));
            }

            return(true);
        }
예제 #17
0
        /// <summary>
        /// 重置用户密码为12345678
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public ActionResult ResetPassword(string id)
        {
            CommonResult result = new CommonResult();

            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    result.ErrorMessage = "用户id不能为空";
                }
                else
                {
                    UserInfo info = BLLFactory <User> .Instance.FindByID(id);

                    if (info != null)
                    {
                        string defaultPassword = Const.defaultPwd;
                        string ip       = NetworkUtil.GetLocalIP();
                        string macAddr  = HardwareInfoHelper.GetMacAddress();
                        bool   tempBool = BLLFactory <User> .Instance.ModifyPassword(info.Name, defaultPassword, Const.SystemTypeID, ip, macAddr);

                        if (tempBool)
                        {
                            result.Success = true;
                        }
                        else
                        {
                            result.ErrorMessage = "口令初始化失败";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(UserController));
                result.ErrorMessage = ex.Message;
            }
            return(ToJsonContent(result));
        }
예제 #18
0
        private void RouterEditCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DemonSaw.Entity.Entity entity = ClientController.SelectedItem;
            RouterEditWindow       wnd    = new RouterEditWindow(entity)
            {
                Owner = this
            };

            bool result = (bool)wnd.ShowDialog();

            if (result)
            {
                if (!NetworkUtil.IsPortValid(wnd.Port.Text))
                {
                    return;
                }

                // Router
                ServerComponent server      = entity.Get <ServerComponent>();
                bool            nameChanged = !server.Name.Equals(wnd.RouterName.Text);
                server.Name       = wnd.RouterName.Text;
                server.Address    = wnd.Address.Text;
                server.Port       = int.Parse(wnd.Port.Text);
                server.Passphrase = wnd.Passphrase.Text;

                // Machine
                MachineComponent machine = entity.Get <MachineComponent>();
                machine.Restart();

                // Controller
                MenuController.Update();

                if (nameChanged)
                {
                    BrowseController.Select();
                }
            }
        }
예제 #19
0
        /// <summary>
        /// 启动检查,检查1、数据交换服务器IP设置,2、WMS服务器IP设置,3、PDA设置,4、3台PLC设置是否都正确。
        /// </summary>
        private void SetupCheck()
        {
            bool checkResult = true; string strStaus = string.Empty;
            CDictionary <string, string> checkIPList = new CDictionary <string, string>();

            checkIPList = AppConfig.Instance().GetAppSettingsByPreKeyIsIP();
            if (checkIPList != null && checkIPList.Count > 0)
            {
                foreach (var item in checkIPList)
                {
                    Splasher.Status = strStaus = $">> 检查{item.Key}网络是否正常.";
                    Application.DoEvents();
                    txtMsg.AppendText(strStaus + Environment.NewLine);
                    if (NetworkUtil.TestNetConnectity(item.Value))
                    {
                        Splasher.Status = strStaus = $">> {item.Key}({item.Value})网络正常.";
                        Application.DoEvents();
                        txtMsg.AppendText(strStaus + Environment.NewLine);
                    }
                    else
                    {
                        checkResult     = false;
                        Splasher.Status = strStaus = $">> {item.Key}({item.Value})网络异常,请检查.";
                        Application.DoEvents();
                        txtMsg.AppendRichText(strStaus + Environment.NewLine, new Font("微软雅黑", 9), Color.Crimson);
                        return;
                    }
                }
            }

            if (checkResult)
            {
                Thread.Sleep(50);
                btnTCPStart_Click(null, null);
                Splasher.Status = ">> 启动数据交换服务器MES.SocketService";
                Application.DoEvents();
            }
        }
예제 #20
0
파일: SendData.cs 프로젝트: ping203/SoDoVIP
    public static void onSendArrayPhom(int currentTableID, int[][] array)
    {
        Message msg = new Message(CMDClient.CMD_HA_PHOM_TAY);

        try {
            msg.writer().WriteShort((short)currentTableID);
            msg.writer().WriteByte((byte)array.Length);
            for (int i = 0; i < array.Length; i++)
            {
                sbyte[] card = new sbyte[array[i].Length];
                msg.writer().WriteInt(array[i].Length);
                for (int j = 0; j < card.Length; j++)
                {
                    card[j] = (sbyte)array[i][j];
                    msg.writer().WriteByte(card[j]);
                }
            }
        } catch (Exception ex) {
            Debug.LogException(ex);
        }

        NetworkUtil.GI().sendMessage(msg);
    }
예제 #21
0
        public static void PickFromDownloadLink <ContentType>(string url, AssetBasicTaker <ContentType> collector)
        {
            UnityWebRequest www = null;

            if (typeof(ContentType) == typeof(Texture2D))
            {
                www = UnityWebRequestTexture.GetTexture(url);
            }
            else
            {
                www = UnityWebRequest.Get(url);
            }
            NetworkUtil.ProcessWebRequest(www, (givenWWW) => {
                if (string.IsNullOrEmpty(givenWWW.error))
                {
                    if (typeof(ContentType) == typeof(byte[]))
                    {
                        collector.CollectAsset((ContentType)(object)givenWWW.downloadHandler.data);
                    }
                    else if (typeof(ContentType) == typeof(AudioClip))
                    {
                        collector.CollectAsset((ContentType)(object)DownloadHandlerAudioClip.GetContent(givenWWW));
                    }
                    else if (typeof(ContentType) == typeof(Texture2D))
                    {
                        var texture = DownloadHandlerTexture.GetContent(givenWWW);
                        Debug.Log(texture);
                        collector.CollectAsset((ContentType)(object)texture);
                    }
                    else
                    {
                        collector.CollectRawAsset(givenWWW.downloadHandler.data);
                    }
                }
                collector.OnFinish();
            });
        }
예제 #22
0
        private void LoadData(Action <object> onLoadAction)
        {
            var info = new List <Info>();

            Task.Factory.StartNew(() =>
            {
                info.Add(new Info()
                {
                    Description = "Extern IP-address", Value = NetworkUtil.GetExternalAddress().ToString()
                });
                info.Add(new Info()
                {
                    Description = "Intern IP-address", Value = NetworkUtil.LocalIPAddress()
                });
                info.Add(new Info()
                {
                    Description = "", Value = ""
                });
                info.Add(new Info()
                {
                    Description = "*** Network adapters ***", Value = ""
                });
                var adapters = NetworkUtil.GetNetworkAdapters();
                foreach (var adapter in adapters)
                {
                    info.Add(new Info()
                    {
                        Description = adapter.Name, Value = adapter.Status.ToString()
                    });
                }
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((task =>
            {
                NetworkInfo = new ObservableCollection <Info>(info);
                onLoadAction.Invoke(null);
            }), TaskScheduler.FromCurrentSynchronizationContext());
        }
예제 #23
0
        private void AcceptConnection(Session session, JoinRequestMessage joinRequestMessage, UUID mxpSessionID, UUID userId)
        {
            JoinResponseMessage joinResponseMessage = (JoinResponseMessage)MessageFactory.Current.ReserveMessage(
                typeof(JoinResponseMessage));

            joinResponseMessage.RequestMessageId = joinRequestMessage.MessageId;
            joinResponseMessage.FailureCode      = MxpResponseCodes.SUCCESS;

            joinResponseMessage.BubbleId            = joinRequestMessage.BubbleId;
            joinResponseMessage.ParticipantId       = userId.Guid;
            joinResponseMessage.AvatarId            = userId.Guid;
            joinResponseMessage.BubbleAssetCacheUrl = "http://" +
                                                      NetworkUtil.GetHostFor(session.RemoteEndPoint.Address,
                                                                             m_scenes[
                                                                                 new UUID(joinRequestMessage.BubbleId)].
                                                                             RegionInfo.
                                                                             ExternalHostName) + ":" +
                                                      m_scenes[new UUID(joinRequestMessage.BubbleId)].RegionInfo.
                                                      HttpPort + "/assets/";

            joinResponseMessage.BubbleName = m_scenes[new UUID(joinRequestMessage.BubbleId)].RegionInfo.RegionName;

            joinResponseMessage.BubbleRange            = 128;
            joinResponseMessage.BubblePerceptionRange  = 128 + 256;
            joinResponseMessage.BubbleRealTime         = 0;
            joinResponseMessage.ProgramName            = m_programName;
            joinResponseMessage.ProgramMajorVersion    = m_programMajorVersion;
            joinResponseMessage.ProgramMinorVersion    = m_programMinorVersion;
            joinResponseMessage.ProtocolMajorVersion   = MxpConstants.ProtocolMajorVersion;
            joinResponseMessage.ProtocolMinorVersion   = MxpConstants.ProtocolMinorVersion;
            joinResponseMessage.ProtocolSourceRevision = MxpConstants.ProtocolSourceRevision;

            session.Send(joinResponseMessage);

            session.SetStateConnected();
        }
        public async Task <bool> SendLoginCodeSms(string phoneNumber)
        {
            if (Configuration == null)
            {
                throw new GameServiceException("You Must Configuration First").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SendLoginCodeSms");
            }

            if (!await NetworkUtil.IsConnected())
            {
                throw new GameServiceException("Network Unreachable").LogException(typeof(LoginOrSignUpProvider),
                                                                                   DebugLocation.Internal, "SendLoginCodeSms");
            }

            if (string.IsNullOrEmpty(phoneNumber))
            {
                throw new GameServiceException("phoneNumber Cant Be EmptyOrNull").LogException(
                          typeof(LoginOrSignUpProvider),
                          DebugLocation.Internal, "SendLoginCodeSms");
            }

            return(await ApiRequest.SendLoginCodeWithSms(phoneNumber));
        }
예제 #25
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            // Check network connection
            if (!NetworkUtil.NetworkIsConnected())
            {
                MessageBox.Show(
                    "無法開始設定。你的電腦尚未連接到網際網路,應用程式需要網際網路來運作。",
                    Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return;
            }

            if (!IsAdministrator())
            {
                MessageBox.Show(
                    "錯誤 (0x00000001)\n無法開始設定,將會以系統管理員身份重新開啟設定精靈。",
                    "Auto Google Meet 設定精靈",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                // Restart
                new Process {
                    StartInfo = new ProcessStartInfo {
                        UseShellExecute = true,
                        FileName        = Application.ExecutablePath,
                        Verb            = "runas"
                    }
                }.Start();
                Application.Exit();
                return;
            }

            // show User agreement UI
            new frmUserAgreement().Show();
            Close();
        }
예제 #26
0
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="name">用户名称</param>
        /// <param name="oldpass">旧密码</param>
        /// <param name="newpass">修改密码</param>
        /// <returns></returns>
        public ActionResult ModifyPass(string name, string oldpass, string newpass)
        {
            CommonResult result = new CommonResult();

            try
            {
                // TODO 这里要修改为Request IP
                string ip       = NetworkUtil.GetLocalIP();
                string macAddr  = HardwareInfoHelper.GetMacAddress();
                string identity = BLLFactory <User> .Instance.VerifyUser(name, oldpass, Const.SystemTypeID, ip, macAddr);

                if (string.IsNullOrEmpty(identity))
                {
                    result.ErrorMessage = "原口令错误";
                }
                else
                {
                    bool tempBool = BLLFactory <User> .Instance.ModifyPassword(name, newpass, Const.SystemTypeID, ip, macAddr);

                    if (tempBool)
                    {
                        result.Success = true;
                    }
                    else
                    {
                        result.ErrorMessage = "口令修改失败";
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(UserController));
                result.ErrorMessage = ex.Message;
            }
            return(ToJsonContent(result));
        }
예제 #27
0
 public void Create(NITag tag)
 {
     NetworkUtil.HttpPostString(TAGS, NIAUTHHEADER, JsonConvert.SerializeObject(new JsonNITag(tag)));
 }
예제 #28
0
 public void UpdateTag(string path, string value, NITagType type)
 {
     NetworkUtil.HttpPutString(TAGS + "/" + path + "/values/current", NIAUTHHEADER, "{ \"value\": { \"type\": \"" + type + "\", \"value\": \"" + value + "\" }}");
 }
예제 #29
0
 public void Activate(NITag t, bool state)
 {
     NetworkUtil.HttpPostString(TAGS, NIAUTHHEADER, "{ \"type\": \"" + t.type + "\", \"path\": \"" + t.path + "\", \"properties\":{\"active\":\"" + state + "\"}}");
 }
예제 #30
0
 public void ActivateHistorian(string path, string id, bool state)
 {
     NetworkUtil.HttpPostString(TAGSHISTORYTAG + path + "/update-values", NIAUTHHEADER, "{\"values\": [{ \"id\": \"" + id + "\", \"properties\":{\"active\":\"" + state + "\"}}]}");
 }