public LoginHelper(LoginSettings loginSettings, NetworkHelper networkHelper) { this.loginSettings = loginSettings; this.networkHelper = networkHelper; if (loginSettings.worldId != string.Empty) preferredWorldId = loginSettings.worldId; }
public LoginHelper(LoginForm parentForm, LoginSettings loginSettings, NetworkHelper networkHelper, string logFile, bool patchMedia) : base(parentForm) { this.parentForm = parentForm; this.loginSettings = loginSettings; this.networkHelper = networkHelper; if (loginSettings.worldId != string.Empty) preferredWorldId = loginSettings.worldId; this.logFile = logFile; this.patchMedia = patchMedia; }
public override void Initialize() { networkHelper = new NetworkHelper(); int centerX = Game.Window.ClientBounds.Width / 2; int centerY = Game.Window.ClientBounds.Width / 2; Mouse.SetPosition(centerX, centerY); oldkeyboard = Keyboard.GetState(); rayfall.Position = cameraPosition; // When the camera is made set rayfall position at the same spot rayfall.Direction = Vector3.Down; // || set rayfall direction at the same direction base.Initialize(); }
public LoginForm(LoginSettings loginSettings, NetworkHelper networkHelper, string logFile, bool patchMedia) { LoginHelper loginHelper = new LoginHelper(this, loginSettings, networkHelper, logFile, patchMedia); loginHelper.ParseConfig("../Config/login_settings.xml"); // Change the updateHelper object to be our loginHelper instead base.updateHelper = loginHelper; string url = loginSettings.loginUrl; if (loginSettings.worldId.Length > 0 && url != null && url.Length != 0) { url = url + "?world=" + loginSettings.worldId; } InitializeComponent(); Initialize(url, false); }
private void ProcessDataReceived(Packet packet) { Logger.Net($"<color=\"#00FFFF\">Received [packet:{packet}], time:{TimeUtils.GetLocalTime( TimeUtils.utcTime )}</color>"); if (packet == null) { return; } bool isQCMD = packet.module == Module.GENERIC && packet.command == Command.ACMD_REPLY; if (isQCMD) { _DTO_reply dto = (( _PACKET_GENERIC_ACMD_REPLY )packet).dto; this._qcmdListener.Invoke(NetworkHelper.EncodePacketID(dto.src_module, dto.src_cmd), packet); } else { this._acmdListener.Invoke(NetworkHelper.EncodePacketID(packet.module, packet.command), packet); } }
internal void OnActionCalled(CpAction action, IList <object> inParams, object clientState) { if (!action.IsConnected) { throw new UPnPDisconnectedException("Action '{0}' is not connected to a UPnP network action", action.FullQualifiedName); } CpService service = action.ParentService; ServiceDescriptor sd = GetServiceDescriptor(service); string message = SOAPHandler.EncodeCall(action, inParams, _rootDescriptor.SSDPRootEntry.UPnPVersion); HttpWebRequest request = CreateActionCallRequest(sd, action); ActionCallState state = new ActionCallState(action, clientState, request); state.SetRequestMessage(message); using (_cpData.Lock.EnterWrite()) _pendingCalls.Add(state); IAsyncResult result = state.Request.BeginGetResponse(OnCallResponseReceived, state); NetworkHelper.AddTimeout(request, result, PENDING_ACTION_CALL_TIMEOUT * 1000); }
private void CreateServers() { ServerSettings settings = ServiceRegistration.Get <ISettingsManager>().Load <ServerSettings>(); List <string> filters = settings.IPAddressBindingsList; List <IPAddress> validAddresses = new List <IPAddress>(); if (settings.UseIPv4) { validAddresses.AddRange(NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetwork, filters)); } if (settings.UseIPv6) { validAddresses.AddRange(NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetworkV6, filters)); } foreach (IPAddress address in validAddresses) { HttpServer.HttpServer httpServer = new HttpServer.HttpServer(new HttpLogWriter()); _httpServers[address] = httpServer; } }
public void Start() { IPAddress address = _endpoint.EndPointIPAddress; AddressFamily family = address.AddressFamily; // Multicast socket - used for receiving multicast GENA event messages Socket socket = new Socket(family, SocketType.Dgram, ProtocolType.Udp); _endpoint.GENA_UDP_MulticastReceiveSocket = socket; try { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); NetworkHelper.BindAndConfigureGENAMulticastSocket(socket, address); StartReceive(new UDPAsyncReceiveState <EndpointConfiguration>(_endpoint, UPnPConsts.UDP_GENA_RECEIVE_BUFFER_SIZE, socket)); } catch (Exception e) // SocketException, SecurityException { UPnPConfiguration.LOGGER.Info("GENAClientController: Unable to bind to multicast address(es) for endpoint '{0}'", e, NetworkHelper.IPAddrToString(address)); } }
private static RouterNode New(this RouterComponent self, string innerAddress, uint connectId, uint outerConn, uint innerConn, IPEndPoint syncEndPoint) { RouterNode routerNode = self.AddChild <RouterNode>(); routerNode.ConnectId = connectId; routerNode.OuterConn = outerConn; routerNode.InnerConn = innerConn; routerNode.InnerIpEndPoint = NetworkHelper.ToIPEndPoint(innerAddress); routerNode.SyncIpEndPoint = syncEndPoint; routerNode.InnerAddress = innerAddress; routerNode.LastRecvInnerTime = TimeHelper.ClientNow(); self.ConnectIdNodes.Add(connectId, routerNode); routerNode.Status = RouterStatus.Sync; Log.Info($"router new: outerConn: {outerConn} innerConn: {innerConn} {syncEndPoint}"); return(routerNode); }
void Game_EventStart(object sender, int countdown) { //Routines when the game starts if (countdown == 0) { GetComponent <PowerGenerator>().enabled = true; if (NetworkHelper.IsServerSide()) { var power_controllers = from player in ShipsInGame select player.GetComponent <PowerController>(); foreach (var power_controller in power_controllers) { //Adds a boost to the ship, only it this is the server power_controller.AddPower(new Boost()); } } } }
void OnJoinedRoom() { IsMultiMap = PhotonNetwork.room.name.Split('`')[1].StartsWith("Multi-Map"); Muted = new List <int>(); FirstJoin = true; PhotonNetwork.player.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { { "GuardianMod", 1 }, }); string[] roomInfo = PhotonNetwork.room.name.Split('`'); if (roomInfo.Length > 6) { DiscordHelper.SetPresence(new Discord.Activity { Details = $"Playing in {(roomInfo[5].Length == 0 ? string.Empty : "[PWD]")} {roomInfo[0].Uncolored()}", State = $"({NetworkHelper.GetRegionCode()}) {roomInfo[1]} / {roomInfo[2].ToUpper()}" }); } }
public void Awake(NetworkProtocol protocol, NetworkType type, string address, bool needReconnect) { _protocol = protocol; _type = type; _needReconnect = needReconnect; var ipEndPoint = NetworkHelper.ToIPEndPoint(address); switch (protocol) { case NetworkProtocol.TCP: _service = new TcpService(type, ipEndPoint, OnConnect) { Parent = this }; break; default: throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null); } }
public async void Login() { Session session = null; try { IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint("127.0.0.1:10002"); session = NetworkClient.Instance.Create(connetEndPoint); R2C_Login r2CLogin = (R2C_Login)await session.Call(new C2R_Login() { Account = "Test1", Password = "******" }); Debug.LogError($"R2C_Login: {r2CLogin.Address}"); if (string.IsNullOrEmpty(r2CLogin.Address)) { return; } connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address); gateSession = NetworkClient.Instance.Create(connetEndPoint); G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await gateSession.Call(new C2G_LoginGate() { Key = r2CLogin.Key }); Debug.LogError("登陆gate成功!"); Debug.LogError(g2CLoginGate.PlayerId.ToString()); } catch (Exception e) { Log.Error(e.ToString()); } finally { session?.Dispose(); } }
public ActionResult Customers() { #region Fetch OAUTH token if (!Helper.CheckSessionOAUTHToken((OAUTHtoken)this.Session["OAUTHtoken"])) { this.Session["OAUTHtoken"] = Helper.GetOAUTHToken(); } OAUTHtoken token = (OAUTHtoken)this.Session["OAUTHtoken"]; #endregion List <Customer> theCustomers = new List <Customer>(); #region Followed by customer list using (HttpClient client = NetworkHelper.GetHttpClient(ConfigurationManager.AppSettings[ConfigurationParams.ServiceGatewayURI], token.access_token)) { HttpResponseMessage response = client.GetAsync(String.Format(ServiceGatewayURI.CustomerURI)).Result; if (response != null) { using (response) { if (response.StatusCode == HttpStatusCode.OK) { theCustomers = response.Content.ReadAsAsync <List <Customer> >().Result; } else { return(new HttpStatusCodeResult(response.StatusCode)); } } } } #endregion TypeAheadResults <Customer> container = new TypeAheadResults <Customer>(); container.data.TheResults = theCustomers; return(Content(JsonConvert.SerializeObject(container))); }
public ShuntForm(ITrain train, ArrDep arrDep, Station sta) { Eto.Serialization.Xaml.XamlReader.Load(this); this.arrDep = arrDep; this.station = sta; var dir = new NetworkHelper(train.ParentTimetable).GetTrainDirectionAtStation(train, sta); var th = new TrackHelper(); arrivalLabel.Font = new Font(arrivalLabel.Font.FamilyName, arrivalLabel.Font.Size, FontStyle.Bold); departureLabel.Font = new Font(departureLabel.Font.FamilyName, departureLabel.Font.Size, FontStyle.Bold); var arrivalTrack = dir.HasValue ? th.GetTrack(train, sta, dir.Value, arrDep, TrackQuery.Departure) : "-"; arrivalLabel.Text = arrivalLabel.Text.Replace("{time}", arrDep.Arrival != default ? arrDep.Arrival.ToTimeString() : "-"); arrivalLabel.Text = arrivalLabel.Text.Replace("{track}", arrivalTrack); var departureTrack = dir.HasValue ? th.GetTrack(train, sta, dir.Value, arrDep, TrackQuery.Departure) : "-"; departureLabel.Text = departureLabel.Text.Replace("{time}", arrDep.Departure != default ? arrDep.Departure.ToTimeString() : "-"); departureLabel.Text = departureLabel.Text.Replace("{track}", departureTrack); Title = Title.Replace("{station}", station.SName); var tracks = sta.Tracks.Select(t => t.Name).ToArray(); gridView.AddColumn <ShuntMove, TimeEntry>(s => s.Time, ts => ts.ToTimeString(), s => { TimeEntry.TryParse(s, out var res); return(res); }, T._("Zeit"), editable: true); gridView.AddDropDownColumn <ShuntMove>(s => s.SourceTrack, tracks, T._("Startgleis"), editable: true); gridView.AddDropDownColumn <ShuntMove>(s => s.TargetTrack, tracks, T._("Zielgleis"), editable: true); gridView.AddCheckColumn <ShuntMove>(s => s.EmptyAfterwards, T._("Alle Wagen?"), editable: true); gridView.SelectedItemsChanged += (s, e) => removeButton.Enabled = gridView.SelectedItem != null; this.AddSizeStateHandler(); shuntBackup = arrDep.Copy().ShuntMoves.ToList(); Shown += (s, e) => RefreshList(); }
public static void Main() { Debug.WriteLine("Hello from a webserver!"); try { int connectRetry = 0; Debug.WriteLine("Waiting for network up and IP address..."); bool success; CancellationTokenSource cs = new(60000); #if HAS_WIFI success = NetworkHelper.ConnectWifiDhcp(MySsid, MyPassword, setDateTime: true, token: cs.Token); #else success = NetworkHelper.WaitForValidIPAndDate(true, System.Net.NetworkInformation.NetworkInterfaceType.Ethernet, cs.Token); #endif if (!success) { Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.ConnectionError.Error}."); if (NetworkHelper.ConnectionError.Exception != null) { Debug.WriteLine($"Exception: {NetworkHelper.ConnectionError.Exception}"); } return; } // Instantiate a new web server on port 80. using (WebServer server = new WebServer(80, HttpProtocol.Http, new Type[] { typeof(ControllerGpio) })) { // Start the server. server.Start(); Thread.Sleep(Timeout.Infinite); } } catch (Exception ex) { Debug.WriteLine($"{ex}"); } }
void _bcReader_ResultFound(Result obj) { try { barCode = obj.Text; if (!obj.Text.Equals(tbBarcodeData.Text)) { tbBarcodeType.Text = obj.BarcodeFormat.ToString(); tbBarcodeData.Text = obj.Text; VibrateController.Default.Start(TimeSpan.FromMilliseconds(100)); line.Visibility = System.Windows.Visibility.Collapsed; Ok.Visibility = System.Windows.Visibility.Visible; string response = Cache.getFromCache(obj.Text); if (response.Equals("")) { if (!BadRequest.checkNetworkConnection()) { NavigationService.Navigate(new Uri("/SorryPage.xaml?SorryString=" + BadRequest.response("0"), UriKind.Relative)); } else { NetworkHelper.getRequest(obj.Text, new UploadStringCompletedEventHandler(handler)); } } else { addToInterface(response); Cache.saveCache(barCode, response); } } } catch (Exception e) { MessageBox.Show("Can't recognize BarCode"); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } }
public async void OnLogin() { try { IPEndPoint connetEndPoint = NetworkHelper.ToIPEndPoint(GlobalConfigComponent.Instance.GlobalProto.Address); string text = this.account.GetComponent <InputField>().text; R2C_Login r2CLogin; using (Session session = Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint)) { r2CLogin = (R2C_Login)await session.Call(new C2R_Login() { Account = text, Password = "******" }); } connetEndPoint = NetworkHelper.ToIPEndPoint(r2CLogin.Address); Session gateSession = Game.Scene.GetComponent <NetOuterComponent>().Create(connetEndPoint); Game.Scene.AddComponent <SessionComponent>().Session = gateSession; G2C_LoginGate g2CLoginGate = (G2C_LoginGate)await SessionComponent.Instance.Session.Call(new C2G_LoginGate() { Key = r2CLogin.Key }); Log.Info("登陆gate成功!"); // 创建Player Player player = Model.ComponentFactory.CreateWithId <Player>(g2CLoginGate.PlayerId); PlayerComponent playerComponent = Game.Scene.GetComponent <PlayerComponent>(); playerComponent.MyPlayer = player; Hotfix.Scene.GetComponent <UIComponent>().Create(UIType.UILobby); Hotfix.Scene.GetComponent <UIComponent>().Remove(UIType.UILogin); } catch (Exception e) { Log.Error(e.ToStr()); } }
static Program() { _runOneRet = ProcessHelper.RunOne(); if (_runOneRet) { AllocConsole(); XmlConfigurator.Configure(new FileInfo($"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}{Path.DirectorySeparatorChar}Log4net.config")); Database.SetInitializer <DbContext>(null); ContainerBuilder containerBuilder = new ContainerBuilder(); ILog log = LogManager.GetLogger("Log4net.config"); containerBuilder.RegisterType <MainForm>().As <MainForm>().SingleInstance(); BsyWarningHelper bsyWarningHelper = new BsyWarningHelper(); string ip; try { ip = NetworkHelper.GetOuterNetIP(); } catch (Exception) { IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName()); ip = ipe.AddressList[4].ToString(); } int ipNum = 0; string[] parts = ip.Split('.'); for (int i = 0, len = parts.Length; i < len; i++) { ipNum += Convert.ToInt32(parts[0]) << ((3 - i) * 8); } IdWorker idWorker = new IdWorker((ipNum >> 27) & 31, ipNum & 31); AllStatic.IdWorker = idWorker; containerBuilder.Register(c => new DistributedTransactionScan()); containerBuilder.Register(c => new DistributeRepository()); containerBuilder.RegisterInstance(idWorker).As <IdWorker>().SingleInstance().PropertiesAutowired(); containerBuilder.RegisterInstance(bsyWarningHelper).As <BsyWarningHelper>().SingleInstance().PropertiesAutowired(); containerBuilder.RegisterInstance(log).As <ILog>().SingleInstance().PropertiesAutowired(); containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly).Where(n => n.Name.EndsWith("Repository") || n.Name.EndsWith("Service") || n.Name.EndsWith("Controller")) .SingleInstance().AsSelf().PropertiesAutowired().EnableClassInterceptors(); Container = containerBuilder.Build(); } }
public void AddManyBranchesWithSimpleBranchFeature() { DateTime t = DateTime.Now; const int count = 10000; var network = new HydroNetwork(); for (int i = 0; i < count; i++) { var from = new HydroNode(); var to = new HydroNode(); network.Nodes.Add(from); network.Nodes.Add(to); var channel = new Channel { Source = from, Target = to }; var compositeBranchStructure = new CompositeBranchStructure(); NetworkHelper.AddBranchFeatureToBranch(channel, compositeBranchStructure, 0); HydroNetworkHelper.AddStructureToComposite(compositeBranchStructure, new Weir()); network.Branches.Add(channel); } int weirCount = 0; foreach (IWeir weir in network.Weirs) // access all Weirs should be also fast { weirCount++; } TimeSpan dt = DateTime.Now - t; log.InfoFormat("Added {0} branches with {1} weirs in {2} sec", count, weirCount, dt.TotalSeconds); // 20091029 set to 5 seconds; original test only added weirs and created an invalid hydronetwork Assert.LessOrEqual(dt.TotalSeconds, 2.7); }
public async Task SearchUrbanDictionary(EduardoContext context, string searchQuery) { string json = await NetworkHelper.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={searchQuery.Replace(' ', '+')}"); Urban data = JsonConvert.DeserializeObject <Urban>(json); if (!data.List.Any()) { await context.Channel.SendMessageAsync(Format.Bold($"Couldn't find anything related to {searchQuery}")); return; } UrbanList termInfo = data.List[new Random().Next(0, data.List.Count)]; await context.Channel.SendMessageAsync(embed : new EmbedBuilder() .WithColor(Color.Gold) .AddField($"Definition of {termInfo.Word}", termInfo.Definition) .AddField("Example", termInfo.Example) .WithFooter($"Related Terms: {string.Join(", ", data.Tags) ?? "No related terms."}") .Build()); }
/// <summary> /// Deserializes the ID's and creates them in the <see cref="Drive"/>. /// </summary> /// <param name="reader"></param> public override void Deserialize(NetworkReader reader) { byte[][] ByteArray = new byte[4][]; ByteArray[0] = reader.ReadBytesAndSize(); ByteArray[1] = reader.ReadBytesAndSize(); ByteArray[2] = reader.ReadBytesAndSize(); ByteArray[3] = reader.ReadBytesAndSize(); int[] IDs = NetworkHelper.DeserializeIntArray(ByteArray); byte[] Equippeds = reader.ReadBytesAndSize(); Drive.Clear(); for (int i = 0; i < IDs.Length; i++) { int ID = IDs[i]; if (ID >= 0) { Drive.AddItemToIndex(ItemDB.Singleton.Get(ID), i); Drive.GetSlots()[i].Equipped = (Equippeds[i] == 1 ? true : false); } } }
private void OnGENAReceive(IAsyncResult ar) { using (_cpData.Lock.EnterRead()) if (!_isActive) { return; } UDPAsyncReceiveState <EndpointConfiguration> state = (UDPAsyncReceiveState <EndpointConfiguration>)ar.AsyncState; EndpointConfiguration config = state.Endpoint; Socket socket = state.Socket; try { EndPoint remoteEP = new IPEndPoint( state.Endpoint.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); // To retrieve the remote endpoint address, it is necessary that the SocketOptionName.PacketInformation is set to true on the socket Stream stream = new MemoryStream(state.Buffer, 0, socket.EndReceiveFrom(ar, ref remoteEP)); try { SimpleHTTPRequest request; SimpleHTTPRequest.Parse(stream, out request); HandleMulticastEventNotification(request); } catch (Exception e) { UPnPConfiguration.LOGGER.Debug("GENAClientController: Problem parsing incoming multicast packet at IP endpoint '{0}'. Error message: '{1}'", e, NetworkHelper.IPAddrToString(config.EndPointIPAddress), e.Message); } StartReceive(state); } catch (Exception) // SocketException, ObjectDisposedException { // Socket was closed - ignore this exception UPnPConfiguration.LOGGER.Info("GENAClientController: Stopping listening for multicast messages at IP endpoint '{0}'", NetworkHelper.IPAddrToString(config.EndPointIPAddress)); } }
public void Connect(IPEndPoint endPoint) { if (!_tcpClient.Connected) { try { _tcpClient.Connect(endPoint); _stream = _tcpClient.GetStream(); NetworkHelper.SendSingleMessage(_tcpClient, new ConnectMessage(_networkManager.username), new PlayerInfo(ClientId, _networkManager.username)); NetworkMessage message = NetworkHelper.ReceiveSingleMessage(_tcpClient); if (message is ConnectMessage) { ConnectMessage connectMessage = (ConnectMessage)message; this.ClientId = connectMessage.playerInfo.userId; this._playerInfo = connectMessage.playerInfo; _logger.Debug("Received client id: " + ClientId); _stream.BeginRead(_headerBuffer, 0, _headerBuffer.Length, ReadHeader, null); // Notify callbacks that we're connected _listeners.ForEach(listener => listener?.OnConnected()); } else { _tcpClient.Close(); _listeners.ForEach(listener => listener?.OnDisconnected()); throw new Exception("Client expected ConnectMessage, but received: " + message.GetType()); } } catch (Exception e) { _logger.Debug(e); if (_networkManager.IsServer) { _networkManager.StopServer(); } _listeners.ForEach(listener => listener?.OnDisconnected()); throw new Exception("Could not connect to the server!"); } } }
public async Task <ServiceResult> ReSendValidationEmail(string userUUID) { if (string.IsNullOrWhiteSpace(userUUID)) { return(ServiceResponse.Error("Invalid user id.")); } UserManager userManager = new UserManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); User user = (User)userManager.GetBy(userUUID); if (user == null) { return(ServiceResponse.Error("User not found!")); } NetworkHelper network = new NetworkHelper(); string ip = network.GetClientIpAddress(this.Request); EmailSettings settings = new EmailSettings(); settings.HostPassword = Globals.Application.AppSetting("EmailHostPassword"); settings.EncryptionKey = Globals.Application.AppSetting("AppKey"); settings.HostUser = Globals.Application.AppSetting("EmailHostUser"); settings.MailHost = Globals.Application.AppSetting("MailHost"); settings.MailPort = StringEx.ConvertTo <int>(Globals.Application.AppSetting("MailPort")); settings.SiteDomain = Globals.Application.AppSetting("SiteDomain"); settings.SiteEmail = Globals.Application.AppSetting("SiteEmail"); settings.UseSSL = StringEx.ConvertTo <bool>(Globals.Application.AppSetting("UseSSL")); ServiceResult res = await userManager.SendUserEmailValidationAsync(user, user.ProviderUserKey, ip, settings); if (res.Code == 200) { return(ServiceResponse.Error("Verification email will be sent. Please follow the instructions in the email. Check your spam/junk folder for the confirmation email if you have not received it.")); } else { return(ServiceResponse.Error("Failed to resend validation email. Try again later.")); } }
private void OnSSDPUnicastReceive(IAsyncResult ar) { lock (_cpData.SyncObj) if (!_isActive) { return; } UDPAsyncReceiveState <EndpointConfiguration> state = (UDPAsyncReceiveState <EndpointConfiguration>)ar.AsyncState; EndpointConfiguration config = state.Endpoint; Socket socket = config.SSDP_UDP_UnicastSocket; if (socket == null) { return; } try { EndPoint remoteEP = new IPEndPoint(state.Endpoint.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); Stream stream = new MemoryStream(state.Buffer, 0, socket.EndReceiveFrom(ar, ref remoteEP)); try { SimpleHTTPResponse header; SimpleHTTPResponse.Parse(stream, out header); HandleSSDPResponse(header, config, (IPEndPoint)remoteEP); } catch (Exception e) { UPnPConfiguration.LOGGER.Debug("SSDPClientController: Problem parsing incoming unicast UDP packet. Error message: '{0}'", e.Message); } StartUnicastReceive(state); } catch (Exception) // SocketException, ObjectDisposedException { // Socket was closed - ignore this exception UPnPConfiguration.LOGGER.Info("SSDPClientController: Stopping listening for unicast messages at address '{0}'", NetworkHelper.IPAddrToString(config.EndPointIPAddress)); } }
/// <summary> /// Closes this SSDP listener. No more messages will be received. /// </summary> public void Close() { lock (_cpData.SyncObj) { if (!_isActive) { return; } _isActive = false; } foreach (EndpointConfiguration config in _cpData.Endpoints) { Socket socket; lock (_cpData.SyncObj) { socket = config.SSDP_UDP_MulticastReceiveSocket; config.SSDP_UDP_MulticastReceiveSocket = null; } if (socket != null) { NetworkHelper.DisposeSSDPMulticastSocket(socket); } lock (_cpData.SyncObj) { socket = config.SSDP_UDP_UnicastSocket; config.SSDP_UDP_UnicastSocket = null; } if (socket != null) { socket.Close(); } } lock (_cpData.SyncObj) { _cpData.Endpoints.Clear(); _cpData.DeviceEntries.Clear(); _pendingDeviceEntries.Clear(); } }
internal void RefreshTelnetServerStatus() { try { if (!NetworkHelper.IsTelnetSucceeded(RunningParams.CurrentNetworkLocation.ServerAddress, RunningParams.CurrentNetworkLocation.ServerPort, 50)) { RunningParams.TelnetServerStatus = UniversalStatus.NotOk; } else { RunningParams.TelnetServerStatus = UniversalStatus.Ok; //RunningParams.PingServerStatus = UniversalStatus.Ok; } UpdateServerConnectionStatus(); } catch (Exception ex) { RunningParams.ServerConnectionStatus = UniversalStatus.Unknown; throw new ArgumentException("\n>> " + GetType().FullName + ".RefreshTelnetServerStatus Error: " + ex.Message); } }
/// <summary> /// Retrieve the thumbnail of an imgur image /// </summary> /// <param name="imgurInfo"></param> public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo) { if (imgurInfo.SmallSquare == null) { Log.Warn("Imgur URL was null, not retrieving thumbnail."); return; } Log.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET); webRequest.ServicePoint.Expect100Continue = false; // Not for getting the thumbnail, in anonymous modus //SetClientId(webRequest); using (WebResponse response = webRequest.GetResponse()) { LogRateLimitInfo(response); Stream responseStream = response.GetResponseStream(); if (responseStream != null) { imgurInfo.Image = ImageHelper.FromStream(responseStream); } } }
private async Task UpdateApplyList() { applyList = new ObservableCollection <DeliveryListViewModel>(); userApplyList.DataContext = applyList; DeliveryListResponse deliveryListResponse = await NetworkHelper.GetAsync(new DeliveryListRequest() { DelivererId = UserInfo.Id, State = DeliveryState.Alone }); foreach (Item item in deliveryListResponse.Items) { applyList.Add(new DeliveryListViewModel() { GUID = item.GUID.ToString(), Name = item.Name, Quantity = item.Quantity, Departure = item.Departure, Destination = item.Destination }); } }
public static Network LoadNetworkConfiguration() { Network network = new Network(); OpenFileDialog open = new OpenFileDialog(); open.Title = "Open Network Config."; open.Filter = "Txt File (*.txt)|*.txt"; if (open.ShowDialog() == true) { try { List <string> lines = new List <string>(); System.IO.StreamReader file = new System.IO.StreamReader(open.FileName); string line; while ((line = file.ReadLine()) != null) { lines.Add(line.ToLower().Replace(" ", string.Empty)); } file.Close(); if (!ParseText(lines, network)) { MessageBox.Show("File has wrong format !"); } } catch (Exception ex) { MessageBox.Show("Error ! " + ex.Message); } } else { MessageBox.Show("File not selected !"); } return(NetworkHelper.GenerateNetwork(network)); }
private void OnDownloadFinishedCallback(object sender, AsyncCompletedEventArgs e) { if (NetworkHelper.ValidateDownloadedFile(e)) { Process.Start(LauncherSharedConstants.ExecutableName); Environment.Exit(1); } else { LogManager.WriteLog("[UPDATER] Error on update launcher: " + e.Error.Message); if (_downloadsAttempts <= LauncherSharedConstants.MaxDownloadErrosAttempts) { UpdateLauncher(); //try again } else { MessageBox.Show("Error on update the launcher. You will be redirected to the download page, to download the Launcher manually."); Process.Start(FTPSharedSettings.UpdaterURL); } } }
private static string ProcessArticleImage(string articleContent, string imagePrefixUrl = "") { var regex = new Regex(@"<img\s+src=""(?<src>.*?)""", RegexOptions.Singleline | RegexOptions.Multiline); var matches = regex.Matches(articleContent); var preImagePath = ""; foreach (Match match in matches) { var imagePath = match.Groups["src"].ToString(); var imageName = imagePath.Substring(imagePath.LastIndexOf("/") + 1); if (string.IsNullOrEmpty(preImagePath)) { preImagePath = imagePath.Substring(0, imagePath.LastIndexOf("/") + 1); } NetworkHelper.SavePhotoFromUrl(Application.StartupPath + "\\images\\" + imageName, imagePath); } if (matches.Count > 0 && !string.IsNullOrEmpty(imagePrefixUrl)) { return(articleContent.Replace(preImagePath, imagePrefixUrl)); //自己的图床前缀 } return(articleContent); }
public void ConstructStoppersOnVirtualBarriers() { //Arrange NetworkContext ctx = new NetworkContext("Hydro", new List <string>() { "FlowlineMerge" }, new List <string>() { "Hydro_Net_Junctions", "Barriers" }); ctx.LoadGeometricNetwork(GN_Path, null, null); IPoint pnt = new PointClass(); pnt.X = -86.313; pnt.Y = 43.922; IPoint pnt1 = new PointClass(); pnt1.X = -86.31; pnt1.Y = 43.92; List <IPoint> pnts = new List <IPoint>() { pnt, pnt1 }; //Act StopperJunctions stoppers = NetworkHelper.GetStoppers(ctx, pnts, true, 200, 5, "FlowlineMerge", "Hydro_Net_Junctions", null); //Assert Assert.IsNotNull(stoppers); Assert.IsTrue(stoppers.Stoppers != null && stoppers.Stoppers.Length == 2); Assert.IsTrue(stoppers.Stoppers[0] == 624591 && stoppers.Stoppers[1] == 624974); //Act stoppers = NetworkHelper.GetStoppers(ctx, pnts, false, 200, 5, "FlowlineMerge", "Hydro_Net_Junctions", null); Assert.IsNotNull(stoppers); Assert.IsTrue(stoppers.Stoppers != null && stoppers.Stoppers.Length == 2); Assert.IsTrue(stoppers.Stoppers[0] == 624381 && stoppers.Stoppers[1] == 624391); }
public void OnStatusMessage(object sender, NetworkHelper.NetConnectionStatus status, String reason, NetConnection conn) { if (StatusMessage != null) { StatusMessage(sender, new StatusMessageArgs(status, reason, conn)); } }
public void Setup() { // Get references to the components. m_Movement = m_Instance.GetComponent<TankMovement>(); m_Shooting = m_Instance.GetComponent<TankShooting>(); m_NetworkHelper = m_Instance.GetComponent<NetworkHelper>(); m_CanvasGameObject = m_Instance.GetComponentInChildren<Canvas>().gameObject; // Set the player numbers to be consistent across the scripts. m_Movement.m_PlayerNumber = m_PlayerNumber; m_Shooting.m_PlayerNumber = m_PlayerNumber; // Create a string using the correct color that says 'PLAYER 1' etc based on the tank's color and the player's number. m_ColoredPlayerText = "<color=#" + ColorUtility.ToHtmlStringRGB(m_PlayerColor) + ">PLAYER " + m_PlayerNumber + "</color>"; // Get all of the renderers of the tank. MeshRenderer[] renderers = m_Instance.GetComponentsInChildren<MeshRenderer>(); // Go through all the renderers... for (int i = 0; i < renderers.Length; i++) { // ... set their material color to the color specific to this tank. renderers[i].material.color = m_PlayerColor; } }
/// <summary> /// Routine to train the network /// </summary> /// <param name="cnnProject">The CNN project.</param> /// <param name="numberOfRounds">The number of training rounds.</param> public void TrainPattern(CNNProject cnnProject, long numberOfTrainingRounds) { // 1. preparation - both project's imageLists generalized images to the shuffled trainingItem-list #region 1. preparation List<TrainingItem> trainingItemList = new List<TrainingItem>(); #region fills the trainingItemList ImageList imgList; bool matching; for (int i = 0; i < 2; i++) { // at first we include the matching images if (i == 0) { imgList = cnnProject.Matching; matching = true; } // and then the not matching images else { imgList = cnnProject.Matching; matching = false; } foreach (Image img in imgList.Images) { // generalizes the image Image generalizedImg = ImageHandling.GeneralizeImage(img); trainingItemList.Add(new TrainingItem(generalizedImg, matching)); } } #endregion // filled list gets shuffled // (maybe this optimizes the result) StaticClasses.Shuffle<TrainingItem>(trainingItemList); #endregion // 2. build of training data items and add it to the helper #region 2. trainingItem // used later on to create the training thread NetworkHelper helper = new NetworkHelper(_network); foreach (TrainingItem trainingItem in trainingItemList) { Image img = trainingItem.Image; ArrayList arryListInput; #region fills arryListInput // Converts an image of any size to a pattern that can be feed to the network. ImageProcessingHelper imgHelper = new ImageProcessingHelper(); //note: this is a (monochrome) collection of 0's and 1's !! arryListInput = imgHelper.ArrayListFromImage(img); if (img.Width * img.Height != _network.InputLayer.Count) { throw new InvalidInputException("The number of pixels in the input image doesn't match the number of input layer neurons!", null); } #region Debugging /* // Convert an arrayList by rounding each value to a pattern of 0s and 1s PatternProcessingHelper patHelper = new PatternProcessingHelper(); String tmpPatern = patHelper.PatternFromArraylist(tmpImgList); Debug.WriteLine("Added : " + tmpPatern); */ #endregion #endregion ArrayList arryListOutput; #region fills arryListOutput arryListOutput = new ArrayList(); // true is going to be a single 1, false a single 0 arryListOutput.Add(trainingItem.Matching ? 1 : 0); #endregion // a training data item is used for a single training round TrainingData trainingDataItem = new TrainingData(arryListInput, arryListOutput); // this could be also used; one training round directly //_network.TrainNetwork(trainingDataItem); helper.AddTrainingData(trainingDataItem); } #endregion // Let's go! _trainStart = DateTime.Now; // 3. training #region 3. training // ShowProgress delegate helper.TrainingProgress += new NetworkHelper.TrainingProgressEventHandler(ShowProgress); // Start training // --- here we are going to wait -- helper.Train(numberOfTrainingRounds, true); // <-- // releasing helper.TrainingProgress -= new NetworkHelper.TrainingProgressEventHandler(ShowProgress); // show message box if (StopTrainingSilently == false) { MessageBox.Show("Training of the neuronal network completed at " + DateTime.Now, "Training Completed", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion }
public void SetNetworkHelperScipt(NetworkHelper m_NetworkHelper) { this.m_NetworkHelper = m_NetworkHelper; }
/// <summary> /// Overridden to switch to event based keyboard input. /// </summary> /// <returns></returns> protected bool Setup() { // get a reference to the engine singleton engine = new Root(null, null); engine.FixedFPS = fixedFPS; // If the user supplied the command-line arg, limit the // FPS. In any case, limit the frame rate to 100 fps, // since this prevents the render loop spinning when // rendering isn't happening if (maxFPS > 0) engine.MaxFramesPerSecond = maxFPS; else engine.MaxFramesPerSecond = 100; // add event handlers for frame events engine.FrameStarted += new FrameEvent(OnFrameStarted); engine.FrameEnded += new FrameEvent(OnFrameEnded); // Set up our game specific logic // gameWorld = new BetaWorld(this); worldManager = new WorldManager(); gameWorld.WorldManager = worldManager; //if (standalone) { // networkHelper = new LoopbackNetworkHelper(worldManager); //} else networkHelper = new NetworkHelper(worldManager); if (standalone) this.LoopbackWorldServerEntry = networkHelper.GetWorldEntry("standalone"); if (this.LoopbackWorldServerEntry != null) { string worldId = this.LoopbackWorldServerEntry.WorldName; // Bypass the login and connection to master server loginSettings.worldId = worldId; networkHelper.SetWorldEntry(worldId, this.LoopbackWorldServerEntry); networkHelper.MasterToken = this.LoopbackIdToken; networkHelper.OldToken = this.LoopbackOldToken; } else { // Show the login dialog. If we successfully return from this // we have initialized the helper's world entry map with the // resolveresponse data. if (!ShowLoginDialog(networkHelper)) return false; } // Update our media tree (base this on the world to which we connect) WorldServerEntry entry = networkHelper.GetWorldEntry(loginSettings.worldId); // If they specify an alternate location for the media patcher, // use that. if (this.WorldPatcherUrl != null) entry.PatcherUrl = this.WorldPatcherUrl; if (this.WorldUpdateUrl != null) entry.UpdateUrl = this.WorldUpdateUrl; if (this.PatchMedia && entry.PatcherUrl != null && entry.PatcherUrl != string.Empty && entry.UpdateUrl != null && entry.UpdateUrl != string.Empty) { // Fetch the appropriate media (full scan) if (!UpdateWorldAssets(entry.WorldRepository, entry.PatcherUrl, entry.UpdateUrl, fullScan)) return false; } // exit the client after patching media if flag is set if (this.ExitAfterMediaPatch) { return false; } // If we aren't overriding the repository, and we could have // updated, use the world directory. If we don't have an // update url for some reason, use the default repository. if (!useRepository && entry.UpdateUrl != null && entry.UpdateUrl != string.Empty) this.RepositoryPaths = entry.WorldRepositoryDirectories; // Tell the engine where to find media SetupResources(this.RepositoryPaths); // We need to load the Movie plugin here. PluginManager.Instance.LoadPlugins(".", "Multiverse.Movie.dll"); // Set up the scripting system log.Debug("Client.Startup: Loading UiScripting"); UiScripting.SetupInterpreter(); UiScripting.LoadCallingAssembly(); log.Debug("Client.Startup: Finished loading UiScripting"); log.Debug("Client.Startup: Loading Assemblies"); ArrayList assemblies = PluginManager.Instance.GetAssemblies(); foreach (Assembly assembly in assemblies) { UiScripting.LoadAssembly(assembly); } log.Debug("Client.Startup: Finished loading Assemblies"); // Run script that contains world-specific initializations // that must be performed before the display device is // created. But for upward compatibility, if we can't // find the file, don't throw an error. UiScripting.RunFile("ClientInit.py"); // Wait til now to set the networkHelper.UseTCP flag, // because the ClientInit.py may have overriden it. networkHelper.UseTCP = this.UseTCP; // Register our handlers. We must do this before we call // MessageDispatcher.Instance.HandleMessageQueue, so that we will // get the callbacks for the incoming messages. SetupMessageHandlers(); string initialLoadBitmap = ""; if (File.Exists(MultiverseLoadScreen)) initialLoadBitmap = MultiverseLoadScreen; // show the config dialog and collect options if (!Configurate()) { log.Warn("Failed to configure system"); // shutting right back down engine.Shutdown(); throw new ClientException("Failed to configure system"); // return false; } // setup the engine log.Debug("Client.Startup: Calling engine.Initialize()"); window = engine.Initialize(true, "Multiverse World Browser", initialLoadBitmap); log.Debug("Client.Startup: Finished engine.Initialize()"); try { System.Windows.Forms.Control control = window.GetCustomAttribute("HWND") as System.Windows.Forms.Control; System.Windows.Forms.Form f = control.FindForm(); if (allowResize) { if (!window.IsFullScreen) f.MaximizeBox = true; f.Resize += this.OnResize; f.ResizeEnd += this.OnResizeEnd; } f.Closing += new System.ComponentModel.CancelEventHandler(this.OnClosing); } catch (Exception) { log.Warn("Unable to register closing event handler"); } try { System.Windows.Forms.Control control = window.GetCustomAttribute("HWND") as System.Windows.Forms.Control; System.Windows.Forms.Form f = control.FindForm(); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly(); Stream iconStream = assembly.GetManifestResourceStream("MultiverseClient.MultiverseIcon.ico"); control.FindForm().Icon = new System.Drawing.Icon(iconStream); } catch (Exception e) { LogUtil.ExceptionLog.Warn("Unable to load or apply MultiverseIcon. Using default instead"); LogUtil.ExceptionLog.InfoFormat("Exception Detail: {0}", e); } // Tell the MeterManager where it should write logs MeterManager.MeterEventsFile = MeterEventsFile; MeterManager.MeterLogFile = MeterLogFile; // This seems to need the window object to have been initialized TextureManager.Instance.DefaultNumMipMaps = 5; ChooseSceneManager(); // Set up my timers so that I can see how much time is spent in // the various render queues. scene.QueueStarted += new RenderQueueEvent(scene_OnQueueStarted); scene.QueueEnded += new RenderQueueEvent(scene_OnQueueEnded); // XXXMLM - force a reference to the assembly for script reflection log.Debug("Client.Startup: Calling Multiverse.Web.Browser.RegisterForScripting()"); Multiverse.Web.Browser.RegisterForScripting(); log.Debug("Client.Startup: Finished Multiverse.Web.Browser.RegisterForScripting()"); log.Debug("Client.Startup: Calling SetupGui()"); SetupGui(); // Tell Windows that the widget containing the DirectX // screen should now be visible. This may not be the // right place to do this. window.PictureBoxVisible = true; // Set the scene manager worldManager.SceneManager = scene; // Set up a default ambient light for the scene manager scene.AmbientLight = ColorEx.Black; // Sets up the various things attached to the world manager, // as well as registering the various message handlers. // This also initializes the networkHelper. worldManager.Init(rootWindow, this); // At this point, I can have a camera CreateCamera(); // #if !PERFHUD_BUILD inputHandler = new DefaultInputHandler(this); // inputHandler.InitViewpoint(worldManager.Player); // #endif CreateViewports(); // call the overridden CreateScene method CreateScene(); // Set up our game specific stuff (right now, just betaworld) gameWorld.Initialize(); gameWorld.SetupMessageHandlers(); needConnect = true; // retrieve and initialize the input system // input = PlatformManager.Instance.CreateInputReader(); // input.Initialize(window, true, true, false, false); // Initialize the client API and load world specific scripts ClientAPI.InitAPI(gameWorld); Monitor.Enter(scene); log.InfoFormat("Client setup complete at {0}", DateTime.Now); // At this point, you can create timer events. return true; }
protected override void Initialize() { networkHelper = new NetworkHelper(); Window.Title = "Doltmuck"; graphics.GraphicsDevice.Clear(Color.CornflowerBlue); camera = new Camera(this, Vector3.Zero); Components.Add(camera); // Add camera to components terrain = new Terrain(this); // Make a terrain oldkeyboard = Keyboard.GetState(); gunPosition = camera.cameraPosition; gunPosition.Z -= 11; gunPosition.X += 6; gunPosition.Y -= 2; base.Initialize(); }
public bool ShowLoginDialog(NetworkHelper helper) { LoginForm dialog = new LoginForm(loginSettings, helper, PatchLogFile, PatchMedia); System.Windows.Forms.DialogResult rv = dialog.ShowDialog(); if (rv != System.Windows.Forms.DialogResult.OK) return false; fullScan = dialog.FullScan; return true; }
/// <summary> /// Overridden to switch to event based keyboard input. /// </summary> /// <returns></returns> protected bool Setup() { #if USE_PERFORMANCE_COUNTERS SetupPerformanceCategories(); CreateCounters(); #endif this.Tick += new TickEvent(OnTick); worldManager = new WorldManager(verifyServer, behaviorParms); NetworkHelper helper = new NetworkHelper(worldManager); if (this.LoopbackWorldServerEntry != null) { string worldId = this.LoopbackWorldServerEntry.WorldName; // Bypass the login and connection to master server loginSettings.worldId = worldId; helper.SetWorldEntry(worldId, this.LoopbackWorldServerEntry); helper.AuthToken = this.LoopbackIdToken; } networkHelper = helper; // Sets up the various things attached to the world manager, // as well as registering the various message handlers. // This also initializes the networkHelper. worldManager.Init(this); // Register our handlers. We must do this before we call // MessageDispatcher.Instance.HandleMessageQueue, so that we will // get the callbacks for the incoming messages. #if NOT // NOTE: Test client isn't advanced enough to handle these. // Register our handler for the Portal messages, so that we // can drop our connection to the world server, and establish a new // connection to the new world. MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Portal, new MessageHandler(this.HandlePortal)); // Register our handler for the UiTheme messages, so that we // can swap out the user interface. MessageDispatcher.Instance.RegisterHandler(WorldMessageType.UiTheme, new MessageHandler(this.HandleUiTheme)); #endif // Register our handler for the LoginResponse messages, so that we // can throw up a dialog if needed. MessageDispatcher.Instance.RegisterHandler(WorldMessageType.LoginResponse, new WorldMessageHandler(this.HandleLoginResponse)); if (!networkHelper.HasWorldEntry(loginSettings.worldId)) networkHelper.ResolveWorld(loginSettings); WorldServerEntry entry = networkHelper.GetWorldEntry(loginSettings.worldId); NetworkHelperStatus status = networkHelper.ConnectToLogin(loginSettings.worldId); // We need to hook our message filter, whether or not we are // standalone, so instead of doing it later (right before // RdpWorldConnect), do it here. RequireLoginFilter checkAndHandleLogin = new RequireLoginFilter(worldManager); MessageDispatcher.Instance.SetWorldMessageFilter(checkAndHandleLogin.ShouldQueue); if (status != NetworkHelperStatus.Success && status != NetworkHelperStatus.Standalone) { Trace.TraceInformation("World Connect Status: " + status); return false; } networkHelper.DisconnectFromLogin(); CharacterEntry charEntry = SelectCharacter(networkHelper.CharacterEntries, -1); status = networkHelper.ConnectToWorld(charEntry.CharacterId, charEntry.Hostname, charEntry.Port, this.Version); if (status != NetworkHelperStatus.Success) { Trace.TraceInformation("World Connect Status: " + status); return false; } // At this point, the network helper can start handling messages. if (!WaitForStartupMessages()) { if (loginFailed && loginMessage != null) // The server rejected our login throw new ClientException(loginMessage); else if (loginMessage != null) // our login went ok (and we got something back), but something else (terrain/player) failed throw new ClientException("Unable to communicate with server"); else throw new ClientException("Unable to connect to server"); } // At this point, I can have a camera // networkHelper.WorldManager = worldManager; // inputHandler.InitViewpoint(worldManager.Player); Logger.Log(4, "Client setup complete: " + DateTime.Now); // At this point, you can create timer events. return true; }