Beispiel #1
0
		public static async Task<IPEndPoint> ToIPEndPointAsync (this Target self)
		{
			EndPoint endPoint = self.ToEndPoint();
			IPEndPoint ipEndPoint = endPoint as IPEndPoint;
			if (ipEndPoint != null)
				return ipEndPoint;

			var dns = endPoint as DnsEndPoint;
			if (dns == null)
				throw new ArgumentException();


			#if !WINDOWS_PHONE
			try {
				IPHostEntry entry = await Dns.GetHostEntryAsync (dns.Host).ConfigureAwait (false);
				return new IPEndPoint (entry.AddressList.First(), dns.Port);
			} catch (SocketException) {
				return null;
			}
			#else
			var helper = new DnsHelper();
			IAsyncResult result = helper.BeginGetHostEntry (dns.Host, null, null);
			var addresses = await Task<IEnumerable<IPAddress>>.Factory.FromAsync (result, helper.EndGetHostEntry).ConfigureAwait (false);
			var address = addresses.FirstOrDefault();
			if (address == null)
				return null;

			return new IPEndPoint (address, dns.Port);
			#endif
		}
Beispiel #2
0
        /// <summary>
        /// Initialize the icon on the tray.
        /// </summary>
        private void InitializeContextMenu()
        {
            var themesMenu = new MenuItem("Theme");

            foreach (var theme in ThemeManager.Themes)
            {
                var themeOption =
                    new MenuItem(theme.Name, (sender, args) => ChangeTheme(theme.Name))
                {
                    Checked = theme == ThemeManager.CurrentTheme
                };
                themesMenu.MenuItems.Add(themeOption);
            }

            var runOnStartUp = new MenuItem("Run on start up", SwitchStartUpProgram);
            var exit         = new MenuItem("Exit", Exit);

            trayIcon.ContextMenu = new ContextMenu();
            trayIcon.ContextMenu.MenuItems.AddRange(new[] { themesMenu, runOnStartUp, exit });

            trayIcon.MouseClick += MouseClick;
            RefreshRunOnStartUp();

            // TODO: This setup for consistency shouldn't be here, probably.
            DnsHelper.SetDefaultDns();
            RefreshIcons();
        }
Beispiel #3
0
        /// <summary>
        /// 实例化InvokeCaller
        /// </summary>
        /// <param name="appName"></param>
        /// <param name="service"></param>
        public InvokeCaller(string appName, IService service)
        {
            this.appName = appName;
            this.service = service;

            this.hostName  = DnsHelper.GetHostName();
            this.ipAddress = DnsHelper.GetIPAddress();
        }
Beispiel #4
0
 public PublishLogEvent(string logType, string logMessage)
 {
     this.Id         = Guid.NewGuid();
     this.Timestamp  = DateTime.UtcNow;
     this.LogType    = logType;
     this.LogMessage = logMessage;
     this.IP         = DnsHelper.GetIpAddressAsync().GetAwaiter().GetResult();
 }
Beispiel #5
0
        public async Task BeEmptyWhenNoAddresses()
        {
            var hostEntryProvider = Substitute.For <IHostEntryProvider>();

            hostEntryProvider.GetHostEntryAsync().Returns(new IPHostEntry());
            var address = await DnsHelper.GetIpAddressAsync(hostEntryProvider);

            Assert.Empty(address);
        }
Beispiel #6
0
        public async Task RegisterAsync()
        {
            var options = _options.CurrentValue;
            var waitForExpirationTcs = new TaskCompletionSource <Void>();
            var dispos = _options.OnChange(opts =>
            {
                OptionsChanged(this, new OptionsEventArgs
                {
                    Options = opts
                });
            });

            using (dispos)
                using (var zkClient = await CreateAndOpenZkClient(waitForExpirationTcs))
                {
                    var instanceOpts = options.Instance;
                    var serviceName  = instanceOpts.ServiceName;
                    var groupNode    = await zkClient.ProxyNodeAsync(options.GroupName);

                    await groupNode.CreateAsync(Permission.All, Mode.Persistent, true);

                    var serviceNode = await groupNode.ProxyNodeAsync(serviceName);

                    await serviceNode.CreateAsync(Permission.All, Mode.Persistent, true);

                    var instanceNode = await serviceNode.ProxyJsonNodeAsync <InstanceEntry>(SERVICE_ID);

                    var hostName = DnsHelper.ResolveHostName();
                    if (instanceOpts.PreferIpAddress)
                    {
                        hostName = instanceOpts.IpAddress ?? DnsHelper.ResolveIpAddress(hostName);
                    }
                    var entry = instanceOpts.ToEntry();
                    entry.HostName = hostName;
                    Observable.FromEventPattern <OptionsEventArgs>(
                        h => OptionsChanged += h,
                        h => OptionsChanged -= h)
                    .Throttle(TimeSpan.FromSeconds(1))
                    .Subscribe(async x =>
                    {
                        var opts    = x.EventArgs.Options;
                        var insOpts = opts.Instance;
                        if (ShouldUpdate(entry, insOpts))
                        {
                            entry.State  = insOpts.State;
                            entry.Weight = insOpts.Weight;
                            await instanceNode.SetDataAsync(entry);
                            _logger.LogDebug($"[{serviceName}] state: {entry.State}, weight: {entry.Weight}");
                        }
                    });

                    await instanceNode.CreateAsync(entry, Permission.All, Mode.Ephemeral);

                    await waitForExpirationTcs.Task;
                }
        }
Beispiel #7
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="to"></param>
        private void SendMail(Exception ex, string[] to)
        {
            if (to == null || to.Length == 0)
            {
                throw new ArgumentException("请传入收件人地址信息参数!");
            }

            string title = string.Format("【{2}】({3}) - 异常邮件由【{0}({1})】发出", DnsHelper.GetHostName(), DnsHelper.GetIPAddress(),
                                         GetAppTitle(ex), GetServiceTitle(ex));

            SmtpMail.Instance.SendExceptionAsync(ex, title, to);
        }
        /// <summary>
        /// Reset the registry values
        /// </summary>
        private static void ResetRegistry()
        {
            // sql
            string sqlInstanceName    = GetSQLServerInstanceNameStr(false);
            string wapSqlInstanceName = GetSQLServerInstanceNameStr(true);

            WriteSqlRegistryValue(SetupConstants.InstanceNameRegistryValueName, sqlInstanceName);
            WriteWapSqlRegistryValue(SetupConstants.WapInstanceNameRegistryValueName, wapSqlInstanceName);
            string dbName = (String)SetupInputs.Instance.FindItem(SetupInputTags.SqlDatabaseNameTag);

            WriteSqlRegistryValue(SetupConstants.DBNameRegistryValueName, dbName);
            string wapDBName = (String)SetupInputs.Instance.FindItem(SetupInputTags.WapSqlDatabaseNameTag);

            WriteWapSqlRegistryValue(SetupConstants.WapDbNameRegistryValueName, wapDBName);
            string partialConnectionString    = SetupDatabaseHelper.ConstructConnectionString(sqlInstanceName);
            string wapPartialConnectionString = SetupDatabaseHelper.ConstructConnectionString(wapSqlInstanceName);
            string connectionString           = String.Format("{0}database={1}", partialConnectionString, dbName);
            string wapConnectionString        = String.Format("{0}database={1}", partialConnectionString, wapDBName);

            WriteSqlRegistryValue(SetupConstants.ConnectionStringRegistryValueName, connectionString);
            WriteWapSqlRegistryValue(SetupConstants.ConnectionStringRegistryValueName, wapConnectionString);

            string sqlMachineName  = DnsHelper.GetComputerNameFromFqdnOrNetBios((String)SetupInputs.Instance.FindItem(SetupInputTags.GetSqlMachineNameTag(false)));
            bool   onRemoteMachine = String.Compare(sqlMachineName, Environment.MachineName, true) != 0;

            WriteSqlRegistryValue(SetupConstants.OnRemoteRegistryValueName, onRemoteMachine ? 1 : 0);
            WriteSqlRegistryValue(SetupConstants.MachineNameRegistryValueName, sqlMachineName);
            String sqlMachineFqdn = DnsHelper.GetFullyQualifiedName(sqlMachineName);

            WriteSqlRegistryValue(SetupConstants.FqdnRegistryValueName, sqlMachineFqdn);

            sqlMachineName  = DnsHelper.GetComputerNameFromFqdnOrNetBios((String)SetupInputs.Instance.FindItem(SetupInputTags.GetSqlMachineNameTag(true)));
            onRemoteMachine = String.Compare(sqlMachineName, Environment.MachineName, true) != 0;
            WriteWapSqlRegistryValue(SetupConstants.OnRemoteRegistryValueName, onRemoteMachine ? 1 : 0);
            WriteWapSqlRegistryValue(SetupConstants.MachineNameRegistryValueName, sqlMachineName);
            sqlMachineFqdn = DnsHelper.GetFullyQualifiedName(sqlMachineName);
            WriteWapSqlRegistryValue(SetupConstants.FqdnRegistryValueName, sqlMachineFqdn);

            // user name, company name under server
            String userName = SetupInputs.Instance.FindItem(SetupInputTags.UserNameTag);

            WriteServerRegistrationRegistryValue(SetupConstants.UserNameRegistryValueName, userName);

            // VmmServiceAccount
            String serviceAccount = UserAccountHelper.GetServiceAccount();

            if (SetupInputs.Instance.FindItem(SetupInputTags.CmpServiceLocalAccountTag))
            {
                serviceAccount = SetupConstants.LocalSystem;
            }

            WriteConfigSettingsRegistryValue(SetupConstants.ServerSetupInfoRegKey, SetupConstants.VmmServiceAccountValueName, serviceAccount);
        }
Beispiel #9
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="log"></param>
        /// <param name="to"></param>
        private void SendMail(string log, string[] to)
        {
            if (to == null || to.Length == 0)
            {
                throw new ArgumentException("请传入收件人地址信息参数!");
            }

            var    body  = CoreHelper.GetSubString(log, 20, "...");
            string title = string.Format("{2} - 普通邮件由【{0}({1})】发出", DnsHelper.GetHostName(), DnsHelper.GetIPAddress(), body);

            SmtpMail.Instance.SendAsync(title, log, to);
        }
Beispiel #10
0
        public override void ExecuteOption(OptionReport report)
        {
            string dns  = _databaseAdjustDns.dnsIp;
            string name = _databaseAdjustDns.adapterName;

            DnsHelper.SetDns(dns, name);

            List <IPAddress> addresses = DnsHelper.GetActiveEthernetIpv4DnsAddresses();

            report.Success = addresses.Any(address => address.ToString() == dns);

            return;
        }
Beispiel #11
0
        public void SetDnsSetsAValidDns()
        {
            string newIp = "176.28.51.226";
            string name  = "Local Area Connection";

            DnsHelper.SetDns(newIp, name);

            List <IPAddress> ipAddresses = DnsHelper.GetActiveEthernetIpv4DnsAddresses();

            DnsHelper.RemoveDns(name);

            Assert.IsTrue(ipAddresses.Any(ip => ip.ToString() == newIp));
        }
Beispiel #12
0
        private static async Task FetchAndCreateDnsRecords(ILogger log, string subscriptionId, CertificateRenewalInputModel certifcate, AcmeHelper acmeHelper, string domainName)
        {
            var dnsHelper = new DnsHelper(subscriptionId);

            log.LogInformation("Fetching DNS authorization");
            var dnsText = await acmeHelper.GetDnsAuthorizationTextAsync();

            var dnsName = ("_acme-challenge." + domainName).Replace("." + certifcate.DnsZoneName, "").Trim();

            log.LogInformation($"Got DNS challenge {dnsText} for {dnsName}");
            await CreateDnsTxtRecordsIfNecessary(log, certifcate, dnsHelper, dnsText, dnsName);

            log.LogInformation("Waiting 60 seconds for DNS propagation");
            await Task.Delay(60 * 1000);
        }
Beispiel #13
0
        /// <summary>
        /// 生成文档
        /// </summary>
        /// <returns></returns>
        public string MakeDocument(string name)
        {
            string uri  = string.Format("http://{0}:{1}/", DnsHelper.GetIPAddress(), port);
            var    html = htmlTemplate.Replace("${uri}", uri);

            StringBuilder sbUrl = new StringBuilder();

            foreach (var kv in callers)
            {
                sbUrl.Append(GetItemDocument(kv.Value, name));
            }

            html = html.Replace("${body}", sbUrl.ToString());
            return(html);
        }
Beispiel #14
0
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
        {
            var log = loggerFactory
                      .AddNLog()
                      //.AddConsole()
                      //.AddDebug()
                      .CreateLogger <Startup>();

            loggerFactory.ConfigureNLog("NLog.config");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            app.UseSwagger((httpRequest, swaggerDoc) =>
            {
                swaggerDoc.Host = httpRequest.Host.Value;
            });
            app.UseSwaggerUi();



            // add tenant & health check
            var localAddress = DnsHelper.GetIpAddressAsync().Result;
            var uri          = new Uri($"http://{localAddress}:{Program.PORT}/");

            log.LogInformation("Registering tenant at ${uri}");
            var registryInformation = app.AddTenant("values", "1.0.0-pre", uri, tags: new[] { "urlprefix-/values" });

            log.LogInformation("Registering additional health check");
            //var checkId = app.AddHealthCheck(registryInformation, new Uri(uri, "status"), TimeSpan.FromSeconds(15), "status");

            // prepare checkId for options injection
            //app.ApplicationServices.GetService<IOptions<HealthCheckOptions>>().Value.HealthCheckId = checkId;

            // register service & health check cleanup
            applicationLifetime.ApplicationStopping.Register(() =>
            {
                log.LogInformation("Removing tenant & additional health check");
                //app.RemoveHealthCheck(checkId);
                app.RemoveTenant(registryInformation.Id);
                _consulConfigCancellationTokenSource.Cancel();
            });
        }
Beispiel #15
0
        public void StartUdpServer()
        {
            try
            {
                StopUdpServer();

                _mainUdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _mainUdpSocket.EnableBroadcast = true;

                var ip = DnsHelper.GetLocalIp();
                _mainUdpSocket.Bind(new IPEndPoint(ip, 0));
            }
            catch (Exception e)
            {
                _gameLogger.Error($"Server StartUdpServer, error: {e.Message}");
            }
        }
Beispiel #16
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            var ok = IsValidForm();

            if (ok)
            {
                try
                {
                    Application.DoEvents();
                    Cursor = Cursors.WaitCursor;

                    var postData = new Dictionary <string, string>();

                    var msg = string.Empty;
                    msg += "Application Name: " + AssemblyHelper.AssemblyTitle + " " + AssemblyHelper.ApplicationVersion;
                    msg += "\r\nAssembly Guid: " + AssemblyHelper.AssemblyGuid;
                    msg += "\r\nLocal IP: " + DnsHelper.GetIPAddress();
                    msg += "\r\n---\r\n" + memoMessage.Text + "\r\n---";

                    postData.Add("name", txtName.Text);
                    postData.Add("email", txtEmail.Text);
                    postData.Add("subject", txtSubject.Text);
                    postData.Add("message", msg);

                    if (WebRequestHelper.SendData("http://www.programmer.ge/feedback/", "POST", postData) == "OK")
                    {
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        XtraMessageBox.Show(this, "გაგზავნა ვერ მოხერხდა.", "შეცდომა", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(this, "გაგზავნა ვერ მოხერხდა.\n" + ex.Message, "შეცდომა", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }
        }
Beispiel #17
0
        void server_ClientDisconnected(object sender, ServerClientEventArgs e)
        {
            var endPoint = (e.Client.RemoteEndPoint as ScsTcpEndPoint);

            container.Write(string.Format("User Disconnection {0}:{1}!", endPoint.IpAddress, endPoint.TcpPort), LogType.Error);

            //处理登出事件
            var connect = new ConnectInfo
            {
                ConnectTime     = DateTime.Now,
                IPAddress       = endPoint.IpAddress,
                Port            = endPoint.TcpPort,
                ServerIPAddress = epServer.IpAddress ?? DnsHelper.GetIPAddress(),
                ServerPort      = epServer.TcpPort,
                Connected       = false
            };

            MessageCenter.Instance.Notify(connect);
        }
Beispiel #18
0
        public void RetreiveDnsReturnsDns()
        {
            DatabaseAdjustDns databaseAdjustDns = new DatabaseAdjustDns()
            {
                adapterName = "Local Area Connection",
                dnsIp       = "176.28.51.226",
                Schedule    = CreateScheduleAlwaysOnDoOnce(),
            };

            AdjustDns adjustDns = new AdjustDns(Connection, databaseAdjustDns);

            Administration.Option.Options.OptionReport report = new Administration.Option.Options.OptionReport(typeof(AdjustDnsTest));
            adjustDns.ExecuteOption(report);
            bool isSuccess = report.Success;

            DnsHelper.RemoveDns(databaseAdjustDns.adapterName);

            Assert.IsTrue(isSuccess);
        }
Beispiel #19
0
        public void Test()
        {
            var domain = "163.com";

            var list = DnsHelper.GetMXRecordList(domain);

            if (list == null)
            {
                Console.WriteLine("query failure");
            }
            else
            {
                foreach (var st in list)
                {
                    Console.WriteLine("MX:\t{0}\t{1}\t{2}\t{3}\n", domain, st.TTL, st.Preference, st.Value);
                }
            }

            Console.ReadLine();
        }
Beispiel #20
0
        /// <summary>
        /// Gets the service.
        /// </summary>
        /// <param name="reqMsg"></param>
        /// <returns></returns>
        private IService ParseService(RequestMessage reqMsg)
        {
            IService service    = null;
            string   serviceKey = "Service_" + reqMsg.ServiceName;

            if (status.Container.Kernel.HasComponent(serviceKey))
            {
                service = status.Container.Resolve <IService>(serviceKey);
            }

            if (service == null)
            {
                string body = string.Format("The server【{1}({2})】not find matching service ({0})."
                                            , reqMsg.ServiceName, DnsHelper.GetHostName(), DnsHelper.GetIPAddress());

                //获取异常
                throw IoCHelper.GetException(OperationContext.Current, reqMsg, body);
            }

            return(service);
        }
Beispiel #21
0
        /// <summary>
        /// Query a status of Software Access Point
        /// </summary>
        /// <returns>A construct with status of the AP</returns>
        public HostedNetworkStatus getStatus()
        {
            var addressList = GetListArp();

            IntPtr ppStatus = IntPtr.Zero;

            lastErrorCode = (int)NativeWLanAPI.WlanHostedNetworkQueryStatus(handle, out ppStatus, IntPtr.Zero);

            checkStatusAndThrow("Could not retrive SoftAP status", false);

            NativeWLanAPI._WLAN_HOSTED_NETWORK_STATUS qstat = (NativeWLanAPI._WLAN_HOSTED_NETWORK_STATUS)Marshal.PtrToStructure(ppStatus, typeof(NativeWLanAPI._WLAN_HOSTED_NETWORK_STATUS));

            bool   isActive       = qstat.HostedNetworkState == NativeWLanAPI._WLAN_HOSTED_NETWORK_STATE.wlan_hosted_network_active ? true : false;
            int    peersConnected = (int)qstat.dwNumberOfPeers;
            Guid   guid           = qstat.IPDeviceID;
            string networkMac     = BitConverter.ToString(qstat.wlanHostedNetworkBSSID.address);//网卡地址
            LinkedList <HostedNetworkPeer> peers = new LinkedList <HostedNetworkPeer>();

            IntPtr offset = Marshal.OffsetOf(typeof(NativeWLanAPI._WLAN_HOSTED_NETWORK_STATUS), "PeerList");

            for (int i = 0; i < peersConnected; i++)
            {
                IntPtr ppeer = new IntPtr(ppStatus.ToInt64() + offset.ToInt64());
                NativeWLanAPI._WLAN_HOSTED_NETWORK_PEER_STATE peer = (NativeWLanAPI._WLAN_HOSTED_NETWORK_PEER_STATE)Marshal.PtrToStructure(ppeer, typeof(NativeWLanAPI._WLAN_HOSTED_NETWORK_PEER_STATE));

                string mac           = BitConverter.ToString(peer.PeerMacAddress.address);
                bool   authenticated = ((int)peer.PeerAuthState == 1 ? true : false);
                string ipAddress     = addressList.LastOrDefault(x => string.Equals(x.MacAddress, mac, StringComparison.CurrentCultureIgnoreCase))?.IpAddress;

                HostedNetworkPeer hpeer = new HostedNetworkPeer(mac, authenticated, DnsHelper.GetHostName(ipAddress), ipAddress);

                peers.AddLast(hpeer);

                offset += Marshal.SizeOf(peer);
            }

            NativeWLanAPI.WlanFreeMemory(ppStatus);

            return(new HostedNetworkStatus(isActive, guid, peersConnected, peers, networkMac));
        }
Beispiel #22
0
        public static async Task <IPEndPoint> ToIPEndPointAsync(this Target self)
        {
            EndPoint   endPoint   = self.ToEndPoint();
            IPEndPoint ipEndPoint = endPoint as IPEndPoint;

            if (ipEndPoint != null)
            {
                return(ipEndPoint);
            }

            var dns = endPoint as DnsEndPoint;

            if (dns == null)
            {
                throw new ArgumentException();
            }


                        #if !WINDOWS_PHONE
            try {
                IPHostEntry entry = await Dns.GetHostEntryAsync(dns.Host).ConfigureAwait(false);

                return(new IPEndPoint(entry.AddressList.First(), dns.Port));
            } catch (SocketException) {
                return(null);
            }
                        #else
            var          helper    = new DnsHelper();
            IAsyncResult result    = helper.BeginGetHostEntry(dns.Host, null, null);
            var          addresses = await Task <IEnumerable <IPAddress> > .Factory.FromAsync(result, helper.EndGetHostEntry).ConfigureAwait(false);

            var address = addresses.FirstOrDefault();
            if (address == null)
            {
                return(null);
            }

            return(new IPEndPoint(address, dns.Port));
                        #endif
        }
        private void textBoxUserName_LostFocus(object sender, EventArgs e)
        {
            try
            {
                String fullUserName = String.Empty;
                try
                {
                    DnsHelper.CheckAndGetFullUserName(this.textBoxUserName.Text, out fullUserName);
                    fullUserName = this.textBoxUserName.Text;
                }
                catch
                {
                    // Ignore the exception
                }

                string[] nameSplits = fullUserName.Split(SetupConstants.AccountDomainUserSeparator);
                if (nameSplits.Length == 1)
                {
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminDomainTag, String.Empty);
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminNameTag, nameSplits[0]);
                }
                else if (nameSplits.Length == 2)
                {
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminDomainTag, nameSplits[0]);
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminNameTag, nameSplits[1]);
                }
                else
                {
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminDomainTag, String.Empty);
                    SetupInputs.Instance.EditItem(SetupInputTags.WapSqlDBAdminNameTag, String.Empty);
                }
            }
            catch (Exception backEndErrorException)
            {
                SetupLogger.LogException(backEndErrorException);
                SetupHelpers.ShowError(backEndErrorException.Message);
            }

            this.SetNextButtonState();
        }
Beispiel #24
0
        /// <summary>
        /// Called when the mouse clicks on the icon.
        /// </summary>
        /// <param name="sender">The icon sends this event.</param>
        /// <param name="e">The arguments of the event.</param>
        private void MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
            {
                return;
            }

            // TODO: this logic shouldn't be in a ui class (?).
            if (!DnsHelper.Connected)
            {
                return;
            }
            if (DnsHelper.UsingDefault)
            {
                DnsHelper.SetGoogleDns();
            }
            else
            {
                DnsHelper.SetDefaultDns();
            }
            RefreshIcons();
        }
Beispiel #25
0
        void server_ClientConnected(object sender, ServerClientEventArgs e)
        {
            var endPoint = (e.Client.RemoteEndPoint as ScsTcpEndPoint);

            container.Write(string.Format("User connection {0}:{1}!", endPoint.IpAddress, endPoint.TcpPort), LogType.Information);
            e.Client.MessageReceived += Client_MessageReceived;
            e.Client.MessageSent     += Client_MessageSent;
            e.Client.MessageError    += Client_MessageError;

            //处理登入事件
            var connect = new ConnectInfo
            {
                ConnectTime     = DateTime.Now,
                IPAddress       = endPoint.IpAddress,
                Port            = endPoint.TcpPort,
                ServerIPAddress = epServer.IpAddress ?? DnsHelper.GetIPAddress(),
                ServerPort      = epServer.TcpPort,
                Connected       = true
            };

            MessageCenter.Instance.Notify(connect);
        }
        /// <summary>
        ///  Initializes a new instance of the <see cref="ServiceInvocationHandler"/> class.
        /// </summary>
        /// <param name="config"></param>
        /// <param name="container"></param>
        /// <param name="service"></param>
        /// <param name="serviceType"></param>
        /// <param name="cache"></param>
        public ServiceInvocationHandler(CastleFactoryConfiguration config, IServiceContainer container, IService service, Type serviceType, ICacheStrategy cache, IServiceLog logger)
        {
            this.config      = config;
            this.container   = container;
            this.serviceType = serviceType;
            this.service     = service;
            this.cache       = cache;
            this.logger      = logger;

            this.hostName  = DnsHelper.GetHostName();
            this.ipAddress = DnsHelper.GetIPAddress();

            this.cacheTimes = new Dictionary <string, int>();
            var methods = CoreHelper.GetMethodsFromType(serviceType);

            foreach (var method in methods)
            {
                var contract = CoreHelper.GetMemberAttribute <OperationContractAttribute>(method);
                if (contract != null && contract.CacheTime > 0)
                {
                    cacheTimes[method.ToString()] = contract.CacheTime;
                }
            }
        }
Beispiel #27
0
        public Config()
        {
            ApplicationFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            ConfigFile        = Path.Combine(ApplicationFolder, "Config.json");
            dynamic data = JsonParse.Deserialize(File.ReadAllText(ConfigFile));

            GameTitle      = "Bricker";
            GameVersion    = GetVersion();
            DisplayVersion = $"{GameVersion.Major}.{GameVersion.Minor}.{GameVersion.Build}";
            LocalIP        = InterfaceDiscovery.GetLocalIP();
            ServerIP       = JsonParse.GetIPAddress(data.multiplayer.server) ?? DnsHelper.ResolveHost(JsonParse.GetString(data.multiplayer.server));
            ServerPort     = JsonParse.GetUShort(data.multiplayer.port);

            AudioSampleFolder  = Path.Combine(ApplicationFolder, "Samples");
            ImageFolder        = Path.Combine(ApplicationFolder, "Images");
            LogFile            = Path.Combine(ApplicationFolder, "LogFile.txt");
            FontFile           = Path.Combine(ApplicationFolder, "Zorque.ttf");
            HighScoreFile      = Path.Combine(ApplicationFolder, "HighScores.txt");
            InitialsFile       = Path.Combine(ApplicationFolder, "Initials.txt");
            RemoteInstanceFile = Path.Combine(ApplicationFolder, "RemoteInstances.txt");

            Music          = JsonParse.GetBoolean(data.audio.music);
            SoundEffects   = JsonParse.GetBoolean(data.audio.effects);
            ShowGhost      = JsonParse.GetBoolean(data.display.ghost);
            ShowBackground = JsonParse.GetBoolean(data.display.background);
            HighFrameRate  = JsonParse.GetBoolean(data.performance.highFrameRate);
            AntiAlias      = JsonParse.GetBoolean(data.performance.antiAlias);
            ImageFolder    = JsonParse.GetString(data.display.imageFolder, null) ?? ImageFolder;
            if (ImageFolder.StartsWith("./"))
            {
                ImageFolder = Path.Combine(ApplicationFolder, ImageFolder.Substring(2));
            }
            Debug = JsonParse.GetBoolean(data.debug);

            Initials = LoadInitials();
        }
Beispiel #28
0
        /// <summary>
        /// 按域进行无代理发送
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="message"></param>
        /// <exception cref="Adf.SmtpException"></exception>
        public static void Send(string domain, MailMessage message)
        {
            const int port = 25;

            //mx
            MXRecordItem mxe    = null;
            DnsRecord    record = DnsRecord.EMPTY;

            //
            lock (mxrecords)
            {
                if (mxrecords.TryGetValue(domain, out mxe))
                {
                    try
                    {
                        record = mxe.recordList[mxe.index];
                        if (Environment.TickCount - record.Expired > 0)
                        {
                            //set null, trigger dns query
                            mxe = null;
                        }
                    }
                    catch
                    {
                        mxe = null;
                    }
                }
            }

            //query
            if (mxe == null)
            {
                mxe            = new MXRecordItem();
                mxe.recordList = DnsHelper.GetMXRecordList(domain);
                mxe.index      = 0;
                if (mxe.recordList == null || mxe.recordList.Count == 0)
                {
                    throw new Adf.SmtpException("dns no found mx record " + domain);
                }

                //
                lock (mxrecords)
                {
                    mxrecords[domain] = mxe;
                }
            }

            Exception firstException;

            try
            {
                for (int i = 0; i < 2; i++)
                {
                    SmtpClient client    = null;
                    string     clientKey = record.Value + ":" + port;
                    lock (clientDictionary)
                    {
                        if (clientDictionary.TryGetValue(clientKey, out client) == false)
                        {
                            client = new SmtpClient(record.Value, port);
                            clientDictionary.Add(clientKey, client);
                        }
                        else if (client.Connected == false)
                        {
                            client.Dispose();
                            //
                            client = new SmtpClient(record.Value, port);
                            clientDictionary[clientKey] = client;
                        }
                    }
                    //
                    try
                    {
                        client.Send(message);
                        break;
                    }
                    catch (IOException)
                    {
                        if (i == 1)
                        {
                            throw;
                        }

                        client.Dispose();
                    }
                }
                //成功发送退出
                return;
            }
            catch (Exception exception)
            {
                //当为 socket 异常时,允许使用其它MX
                if (exception.GetBaseException() is SocketException)
                {
                    if (mxe.recordList.Count == 1)
                    {
                        throw;
                    }

                    firstException = exception;
                }
                else
                {
                    throw;
                }
            }

            //首选失败后重新选择mx服务器
            for (int i = 0, l = mxe.recordList.Count; i <= l; i++)
            {
                SmtpClient client = null;
                try
                {
                    string clientKey = mxe.recordList[i].Value + ":" + port;
                    lock (clientDictionary)
                    {
                        if (clientDictionary.TryGetValue(clientKey, out client) == false)
                        {
                            client = new SmtpClient(mxe.recordList[i].Value, port);
                            clientDictionary.Add(clientKey, client);
                        }
                        else if (client.Connected == false)
                        {
                            client.Dispose();
                            //
                            client = new SmtpClient(mxe.recordList[i].Value, port);
                            clientDictionary[clientKey] = client;
                        }
                    }
                    //
                    client.Send(message);
                    //发送成功,修改首选
                    mxe.index = i;
                    //发送成功退出
                    return;
                }
                catch (Exception exception)
                {
                    client.Dispose();
                    //
                    if (exception.GetBaseException() is SocketException)
                    {
                        //当为 socket 异常时,允许使用其它MX
                        firstException = exception;
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            //当首选服务器为列表中最后一个服务器且重试失败时将首选异常丢出.
            throw firstException;
        }
Beispiel #29
0
        /// <summary>
        /// 调用服务,并返回字符串
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string CallMethod(string name, string parameters)
        {
            if (callers.ContainsKey(name))
            {
                var caller  = callers[name];
                var message = new InvokeMessage
                {
                    ServiceName = caller.Service.FullName,
                    MethodName  = caller.Method.ToString(),
                    Parameters  = parameters
                };

                string thisKey  = string.Format("{0}${1}${2}", message.ServiceName, message.MethodName, message.Parameters);
                var    cacheKey = string.Format("HttpServiceCaller_{0}", IoCHelper.GetMD5String(thisKey));

                var invokeData = CacheHelper.Get <InvokeData>(cacheKey);
                if (invokeData == null)
                {
                    //获取当前调用者信息
                    var appCaller = new AppCaller
                    {
                        AppPath     = AppDomain.CurrentDomain.BaseDirectory,
                        AppName     = "HttpServer",
                        HostName    = DnsHelper.GetHostName(),
                        IPAddress   = DnsHelper.GetIPAddress(),
                        ServiceName = message.ServiceName,
                        MethodName  = message.MethodName,
                        Parameters  = message.Parameters,
                        CallTime    = DateTime.Now
                    };

                    //创建服务
                    var service = CreateService(appCaller);

                    //初始化上下文
                    SetOperationContext(appCaller);

                    try
                    {
                        //使用Invoke方式调用
                        var invoke = new InvokeCaller(appCaller.AppName, service);
                        invokeData = invoke.CallMethod(message);

                        //插入缓存
                        if (invokeData != null && caller.CacheTime > 0)
                        {
                            CacheHelper.Insert(cacheKey, invokeData, caller.CacheTime);
                        }
                    }
                    finally
                    {
                        //初始化上下文
                        OperationContext.Current = null;
                    }
                }

                //如果缓存不为null,则返回缓存数据
                if (invokeData != null)
                {
                    return(invokeData.Value);
                }
            }

            return("null");
        }
        /// <summary>
        /// Runs the specified MSG.
        /// </summary>
        /// <param name="reqMsg">The MSG.</param>
        /// <returns>The msg.</returns>
        protected override ResponseMessage Run(RequestMessage reqMsg)
        {
            var resMsg = new ResponseMessage
            {
                TransactionId = reqMsg.TransactionId,
                ReturnType    = reqMsg.ReturnType,
                ServiceName   = reqMsg.ServiceName,
                MethodName    = reqMsg.MethodName
            };

            #region 获取相应的方法

            var methodKey = string.Format("{0}${1}", reqMsg.ServiceName, reqMsg.MethodName);
            if (!hashtable.ContainsKey(methodKey))
            {
                var m = CoreHelper.GetMethodFromType(serviceType, reqMsg.MethodName);
                if (m == null)
                {
                    string message = string.Format("The server【{2}({3})】not find matching method. ({0},{1})."
                                                   , reqMsg.ServiceName, reqMsg.MethodName, DnsHelper.GetHostName(), DnsHelper.GetIPAddress());

                    resMsg.Error = new WarningException(message);
                    return(resMsg);
                }

                hashtable[methodKey] = m;
            }

            #endregion

            //容器实例对象
            object instance = null;

            try
            {
                //定义Method
                var method = hashtable[methodKey] as System.Reflection.MethodInfo;

                //解析服务
                instance = container.Resolve(serviceType);

                //返回拦截服务
                var service = AspectFactory.CreateProxyService(serviceType, instance);

                if (reqMsg.InvokeMethod)
                {
                    var objValue   = reqMsg.Parameters["InvokeParameter"];
                    var jsonString = (objValue == null ? string.Empty : objValue.ToString());

                    //解析参数
                    reqMsg.Parameters = IoCHelper.CreateParameters(method, jsonString);
                }

                //参数赋值
                object[] parameters = IoCHelper.CreateParameterValues(method, reqMsg.Parameters);

                //调用对应的服务
                resMsg.Value = DynamicCalls.GetMethodInvoker(method).Invoke(service, parameters);

                //处理返回参数
                IoCHelper.SetRefParameters(method, resMsg.Parameters, parameters);

                //返回结果数据
                if (reqMsg.InvokeMethod)
                {
                    resMsg.Value = new InvokeData
                    {
                        Value         = SerializationManager.SerializeJson(resMsg.Value),
                        Count         = resMsg.Count,
                        OutParameters = resMsg.Parameters.ToString()
                    };

                    //清除参数集合
                    resMsg.Parameters.Clear();
                }
            }
            catch (Exception ex)
            {
                //捕获全局错误
                resMsg.Error = ex;
            }
            finally
            {
                //释放资源
                container.Release(instance);

                instance = null;
            }

            return(resMsg);
        }
Beispiel #31
0
        /// <summary>
        /// 启用服务
        /// </summary>
        public void Start()
        {
            if (config.HttpEnabled)
            {
                httpServer.OnServerStart += () => { Console.WriteLine("[{0}] => Http server started. http://{1}:{2}/", DateTime.Now, DnsHelper.GetIPAddress(), config.HttpPort); };
                httpServer.OnServerStop  += () => { Console.WriteLine("[{0}] => Http server stoped.", DateTime.Now); };

                httpServer.OnServerException += httpServer_OnServerException;
                httpServer.Start();
            }

            //启动服务
            server.Start();
        }