Esempio n. 1
0
        public static IPAddress GetServerIP()                       //静态函数, 无需实例化即可调用.
        {
            IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName()); //不多说了, Dns类的两个静态函数

            return(ieh.AddressList[0]);                             //返回Address类的一个实例. 这里AddressList是数组并不奇怪,一个Server有N个IP都有可能
        }
Esempio n. 2
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args).UseUrls($"http://{Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString()}:{5000}")
 .UseStartup <Startup>();
 public IEnumerable <string> DomainNames() => new[] {
     Dns.GetHostName(),
         domainName,
         knownDomainName
 };
Esempio n. 4
0
 ///<summary>
 ///</summary>
 ///<returns></returns>
 public static string GetHostName()
 {
     return(Dns.GetHostName());
 }
Esempio n. 5
0
        private void mnuStartServer_Click(object sender, EventArgs e)
        {
            #region 设置处理文件夹路径Tar包存放文件夹路径
            try
            {
                //接收TAR包存放路径
                sRevTarPath = serverini.ReadValue("FolderSet", "RevTarFolder");
                if (!Directory.Exists(sRevTarPath))
                {
                    Directory.CreateDirectory(sRevTarPath);//不存在该路径就创建
                }
                //接收到的Tar包解压存放路径
                sUnTarPath = serverini.ReadValue("FolderSet", "UnTarFolder");
                if (!Directory.Exists(sUnTarPath))
                {
                    Directory.CreateDirectory(sUnTarPath);//不存在该路径就创建
                }
                //生成的需发送的XML文件路径
                sSourcePath = serverini.ReadValue("FolderSet", "XmlBuildFolder");
                if (!Directory.Exists(sSourcePath))
                {
                    Directory.CreateDirectory(sSourcePath);//
                }
                //生成的TAR包,将要被发送的位置
                sSendTarPath = serverini.ReadValue("FolderSet", "SndTarFolder");
                if (!Directory.Exists(sSendTarPath))
                {
                    Directory.CreateDirectory(sSendTarPath);
                }
                sAudioFilesFolder = serverini.ReadValue("FolderSet", "AudioFileFolder");
                if (!Directory.Exists(sAudioFilesFolder))
                {
                    Directory.CreateDirectory(sAudioFilesFolder);
                }
                //预处理文件夹
                strBeUnTarFolder = serverini.ReadValue("FolderSet", "BeUnTarFolder");
                if (!Directory.Exists(strBeUnTarFolder))
                {
                    Directory.CreateDirectory(strBeUnTarFolder);
                }
                strBeSendFileMakeFolder = serverini.ReadValue("FolderSet", "BeXmlFileMakeFolder");
                if (!Directory.Exists(strBeSendFileMakeFolder))
                {
                    Directory.CreateDirectory(strBeSendFileMakeFolder);
                }
                //预处理文件夹
                if (strBeUnTarFolder == "" || strBeSendFileMakeFolder == "")
                {
                    MessageBox.Show("预处理文件夹路径不能为空,请设置好路径!");
                    this.Close();
                }

                if (sRevTarPath == "" || sSendTarPath == "" || sSourcePath == "" || sUnTarPath == "")
                {
                    MessageBox.Show("文件夹路径不能为空,请设置好路径!");
                    this.Close();
                }
            }
            catch (Exception em)
            {
                MessageBox.Show("文件夹设置错误,请重新:" + em.Message);
                this.Close();
            }
            #endregion 文件夹路径设置END

            bDeal = true;//解析开关
            try
            {
                IPAddress[] ipArr;
                ipArr = Dns.GetHostAddresses(Dns.GetHostName());
                if (!ipArr.Contains(iServerIP))
                {
                    MessageBox.Show("IP设置错误,请重新设置后运行服务!");
                    return;
                }
                httpServer = new HttpServer(iServerIP, iServerPort);
            }
            catch (Exception es)
            {
                MessageBox.Show("可能端口已经使用中,请重新分配端口:" + es.Message);
                return;
            }


            if (mnuStartServer.Text == "启动伺服")
            {
                //启动服务
                MessageShowDlg = new MessageShowForm {
                    label1 = { Text = @"启动服务?" }
                };
                MessageShowDlg.ShowDialog();
                if (MessageShowDlg.IsSure)
                {
                    mnuStartServer.Text     = "停止伺服";
                    httpthread              = new Thread(new ThreadStart(httpServer.listen));
                    httpthread.IsBackground = true;
                    httpthread.Name         = "HttpServer服务";
                    httpthread.Start();
                    skinDataGridView_Main.Visible = true;
                    // skinDataGridView_Main.Dock=Dock.f
                }
            }
            else
            {
                //停止服务
                MessageShowDlg = new MessageShowForm {
                    label1 = { Text = @"停止服务?" }
                };
                MessageShowDlg.ShowDialog();
                if (MessageShowDlg.IsSure)
                {
                    mnuStartServer.Text = "启动伺服";
                    if (httpthread != null)
                    {
                        httpthread.Abort();
                        httpthread = null;
                    }
                    httpServer.StopListen();
                    skinDataGridView_Main.Visible = false;
                }
            }
        }
Esempio n. 6
0
        //http://www.ryadel.com/en/asp-net-c-helper-class-to-get-web-server-ip-address-and-other-network-related-methods/
        /// <summary>
        /// Gets all the IP addresses of the server machine hosting the application.
        /// </summary>
        /// <returns>a string array containing all the IP addresses of the server machine</returns>
        public IPAddress[] GetIPAddresses()
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated.

            return(ipHostInfo.AddressList);
        }
Esempio n. 7
0
        private async Task StartContainerAsync(Application application, Service service, DockerRunInfo docker, string?dockerNetwork)
        {
            var serviceDescription   = service.Description;
            var environmentArguments = "";
            var volumes          = "";
            var workingDirectory = docker.WorkingDirectory != null ? $"-w \"{docker.WorkingDirectory}\"" : "";
            var hostname         = "host.docker.internal";
            var dockerImage      = docker.Image ?? service.Description.Name;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // See: https://github.com/docker/for-linux/issues/264
                //
                // host.docker.internal is making it's way into linux docker but doesn't work yet
                // instead we use the machine IP
                var addresses = await Dns.GetHostAddressesAsync(Dns.GetHostName());

                hostname = addresses[0].ToString();
            }

            async Task RunDockerContainer(IEnumerable <(int ExternalPort, int Port, int?ContainerPort, string?Protocol)> ports, CancellationToken cancellationToken)
            {
                var hasPorts = ports.Any();

                var replica = service.Description.Name.ToLower() + "_" + Guid.NewGuid().ToString().Substring(0, 10).ToLower();
                var status  = new DockerStatus(service, replica);

                service.Replicas[replica] = status;

                service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Added, status));

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

                var portString = "";

                if (hasPorts)
                {
                    status.Ports    = ports.Select(p => p.Port);
                    status.Bindings = ports.Select(p => new ReplicaBinding()
                    {
                        Port = p.Port, ExternalPort = p.ExternalPort, Protocol = p.Protocol
                    }).ToList();

                    // These are the ports that the application should use for binding

                    // 1. Tell the docker container what port to bind to
                    portString = docker.Private ? "" : string.Join(" ", ports.Select(p => $"-p {p.Port}:{p.ContainerPort ?? p.Port}"));

                    if (docker.IsAspNet)
                    {
                        // 2. Configure ASP.NET Core to bind to those same ports
                        environment["ASPNETCORE_URLS"] = string.Join(";", ports.Select(p => $"{p.Protocol ?? "http"}://*:{p.ContainerPort ?? p.Port}"));

                        // Set the HTTPS port for the redirect middleware
                        foreach (var p in ports)
                        {
                            if (string.Equals(p.Protocol, "https", StringComparison.OrdinalIgnoreCase))
                            {
                                // We need to set the redirect URL to the exposed port so the redirect works cleanly
                                environment["HTTPS_PORT"] = p.ExternalPort.ToString();
                            }
                        }
                    }

                    // 3. For non-ASP.NET Core apps, pass the same information in the PORT env variable as a semicolon separated list.
                    environment["PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}"));

                    // This the port for the container proxy (containerport:externalport)
                    environment["PROXY_PORT"] = string.Join(";", ports.Select(p => $"{p.ContainerPort ?? p.Port}:{p.ExternalPort}"));
                }

                // See: https://github.com/docker/for-linux/issues/264
                //
                // The way we do proxying here doesn't really work for multi-container scenarios on linux
                // without some more setup.
                application.PopulateEnvironment(service, (key, value) => environment[key] = value, hostname !);

                environment["APP_INSTANCE"]   = replica;
                environment["CONTAINER_HOST"] = hostname !;

                status.Environment = environment;

                foreach (var pair in environment)
                {
                    environmentArguments += $"-e \"{pair.Key}={pair.Value}\" ";
                }

                foreach (var volumeMapping in docker.VolumeMappings)
                {
                    if (volumeMapping.Source != null)
                    {
                        var sourcePath = Path.GetFullPath(Path.Combine(application.ContextDirectory, volumeMapping.Source));
                        volumes += $"-v \"{sourcePath}:{volumeMapping.Target}\" ";
                    }
                    else if (volumeMapping.Name != null)
                    {
                        volumes += $"-v \"{volumeMapping.Name}:{volumeMapping.Target}\" ";
                    }
                }

                var command = $"run -d {workingDirectory} {volumes} {environmentArguments} {portString} --name {replica} --restart=unless-stopped {dockerImage} {docker.Args ?? ""}";

                if (!docker.IsProxy)
                {
                    _logger.LogInformation("Running image {Image} for {Replica}", docker.Image, replica);
                }
                else
                {
                    _logger.LogDebug("Running proxy image {Image} for {Replica}", docker.Image, replica);
                }

                service.Logs.OnNext($"[{replica}]: docker {command}");

                status.DockerCommand = command;
                status.DockerNetwork = dockerNetwork;

                WriteReplicaToStore(replica);
                var result = await ProcessUtil.RunAsync(
                    "docker",
                    command,
                    throwOnError : false,
                    cancellationToken : cancellationToken,
                    outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"),
                    errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"));

                if (result.ExitCode != 0)
                {
                    _logger.LogError("docker run failed for {ServiceName} with exit code {ExitCode}:" + result.StandardError, service.Description.Name, result.ExitCode);
                    service.Replicas.TryRemove(replica, out var _);
                    service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status));

                    PrintStdOutAndErr(service, replica, result);
                    return;
                }

                var containerId = (string?)result.StandardOutput.Trim();

                // There's a race condition that sometimes makes us miss the output
                // so keep trying to get the container id
                while (string.IsNullOrEmpty(containerId))
                {
                    // Try to get the ID of the container
                    result = await ProcessUtil.RunAsync("docker", $"ps --no-trunc -f name={replica} --format " + "{{.ID}}");

                    containerId = result.ExitCode == 0 ? result.StandardOutput.Trim() : null;
                }

                var shortContainerId = containerId.Substring(0, Math.Min(12, containerId.Length));

                status.ContainerId = shortContainerId;

                _logger.LogInformation("Running container {ContainerName} with ID {ContainerId}", replica, shortContainerId);

                if (!string.IsNullOrEmpty(dockerNetwork))
                {
                    status.DockerNetworkAlias = docker.NetworkAlias ?? serviceDescription !.Name;

                    var networkCommand = $"network connect {dockerNetwork} {replica} --alias {status.DockerNetworkAlias}";

                    service.Logs.OnNext($"[{replica}]: docker {networkCommand}");

                    _logger.LogInformation("Running docker command {Command}", networkCommand);

                    result = await ProcessUtil.RunAsync("docker", networkCommand);

                    PrintStdOutAndErr(service, replica, result);
                }

                var sentStartedEvent = false;

                while (!cancellationToken.IsCancellationRequested)
                {
                    if (sentStartedEvent)
                    {
                        using var restartCts = new CancellationTokenSource(DockerStopTimeout);
                        result = await ProcessUtil.RunAsync("docker", $"restart {containerId}", throwOnError : false, cancellationToken : restartCts.Token);

                        if (restartCts.IsCancellationRequested)
                        {
                            _logger.LogWarning($"Failed to restart container after {DockerStopTimeout.Seconds} seconds.", replica, shortContainerId);
                            break; // implement retry mechanism?
                        }
                        else if (result.ExitCode != 0)
                        {
                            _logger.LogWarning($"Failed to restart container due to exit code {result.ExitCode}.", replica, shortContainerId);
                            break;
                        }

                        service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status));
                    }

                    using var stoppingCts      = new CancellationTokenSource();
                    status.StoppingTokenSource = stoppingCts;
                    service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Started, status));
                    sentStartedEvent = true;

                    await using var _ = cancellationToken.Register(() => status.StoppingTokenSource.Cancel());

                    _logger.LogInformation("Collecting docker logs for {ContainerName}.", replica);

                    var backOff = TimeSpan.FromSeconds(5);

                    while (!status.StoppingTokenSource.Token.IsCancellationRequested)
                    {
                        var logsRes = await ProcessUtil.RunAsync("docker", $"logs -f {containerId}",
                                                                 outputDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"),
                                                                 errorDataReceived : data => service.Logs.OnNext($"[{replica}]: {data}"),
                                                                 throwOnError : false,
                                                                 cancellationToken : status.StoppingTokenSource.Token);

                        if (logsRes.ExitCode != 0)
                        {
                            break;
                        }

                        if (!status.StoppingTokenSource.IsCancellationRequested)
                        {
                            try
                            {
                                // Avoid spamming logs if restarts are happening
                                await Task.Delay(backOff, status.StoppingTokenSource.Token);
                            }
                            catch (OperationCanceledException)
                            {
                                break;
                            }
                        }

                        backOff *= 2;
                    }

                    _logger.LogInformation("docker logs collection for {ContainerName} complete with exit code {ExitCode}", replica, result.ExitCode);

                    status.StoppingTokenSource = null;
                }

                // Docker has a tendency to get stuck so we're going to timeout this shutdown process
                var timeoutCts = new CancellationTokenSource(DockerStopTimeout);

                _logger.LogInformation("Stopping container {ContainerName} with ID {ContainerId}", replica, shortContainerId);

                result = await ProcessUtil.RunAsync("docker", $"stop {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token);

                if (timeoutCts.IsCancellationRequested)
                {
                    _logger.LogWarning($"Failed to stop container after {DockerStopTimeout.Seconds} seconds, container will most likely be running.", replica, shortContainerId);
                }

                PrintStdOutAndErr(service, replica, result);

                if (sentStartedEvent)
                {
                    service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Stopped, status));
                }

                _logger.LogInformation("Stopped container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode);

                result = await ProcessUtil.RunAsync("docker", $"rm {containerId}", throwOnError : false, cancellationToken : timeoutCts.Token);

                if (timeoutCts.IsCancellationRequested)
                {
                    _logger.LogWarning($"Failed to remove container after {DockerStopTimeout.Seconds} seconds, container will most likely still exist.", replica, shortContainerId);
                }

                PrintStdOutAndErr(service, replica, result);

                _logger.LogInformation("Removed container {ContainerName} with ID {ContainerId} exited with {ExitCode}", replica, shortContainerId, result.ExitCode);

                service.Replicas.TryRemove(replica, out var _);

                service.ReplicaEvents.OnNext(new ReplicaEvent(ReplicaState.Removed, status));
            };

            async Task DockerBuildAsync(CancellationToken cancellationToken)
            {
                if (docker.DockerFile != null)
                {
                    _logger.LogInformation("Building docker image {Image} from docker file", dockerImage);

                    void Log(string data)
                    {
                        _logger.LogInformation("[" + serviceDescription !.Name + "]:" + data);
                        service.Logs.OnNext(data);
                    }

                    var arguments = new StringBuilder($"build \"{docker.DockerFileContext?.FullName}\" -t {dockerImage} -f \"{docker.DockerFile}\"");

                    foreach (var buildArg in docker.BuildArgs)
                    {
                        arguments.Append($" --build-arg {buildArg.Key}={buildArg.Value}");
                    }

                    var dockerBuildResult = await ProcessUtil.RunAsync(
                        $"docker",
                        arguments.ToString(),
                        outputDataReceived : Log,
                        errorDataReceived : Log,
                        workingDirectory : docker.WorkingDirectory,
                        cancellationToken : cancellationToken,
                        throwOnError : false);

                    if (dockerBuildResult.ExitCode != 0)
                    {
                        throw new CommandException("'docker build' failed.");
                    }
                }
            }

            Task DockerRunAsync(CancellationToken cancellationToken)
            {
                var tasks = new Task[serviceDescription !.Replicas];

                if (serviceDescription.Bindings.Count > 0)
                {
                    // Each replica is assigned a list of internal ports, one mapped to each external
                    // port
                    for (var i = 0; i < serviceDescription.Replicas; i++)
                    {
                        var ports = new List <(int, int, int?, string?)>();
                        foreach (var binding in serviceDescription.Bindings)
                        {
                            if (binding.Port == null)
                            {
                                continue;
                            }

                            ports.Add((binding.Port.Value, binding.ReplicaPorts[i], binding.ContainerPort, binding.Protocol));
                        }

                        tasks[i] = RunDockerContainer(ports, cancellationToken);
                    }
                }
                else
                {
                    for (var i = 0; i < service.Description.Replicas; i++)
                    {
                        tasks[i] = RunDockerContainer(Enumerable.Empty <(int, int, int?, string?)>(), cancellationToken);
                    }
                }

                return(Task.WhenAll(tasks));
            }
Esempio n. 8
0
        public override Task <Grpc.AskResponse> Ask(Grpc.AskRequest request, ServerCallContext context)
        {
            var v = _configuration.GetSection("GrpcServer").GetSection("Service").GetValue <int>("Port");

            var model = new AskResponse()
            {
                Content = $"Ask: {request.Key}: {DateTime.Now.ToString()} -- configuration: {v} --- address: {string.Join(",", Dns.GetHostEntry(Dns.GetHostName()).AddressList.Select(oo => oo.ToString()))}"
            };

            return(Task.FromResult(model));
        }
Esempio n. 9
0
        public void ProcessTrendScan()
        {
            foreach (BranchInfo branch in BranchInfoList)
            {
                if (branch.NextUpdateTime < DateTime.Now)
                {
                    try
                    {
                        if (DownloadBranchPattern(branch) && UnzipBranchPattern(branch))
                        {
                            SetupBranchParam(branch);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Log.ErrorFormat("ProcessTrenscan {0} fail, {1}", branch.BranchName, ex.Message);
                    }
                }
            }

            string[] tickets = Directory.GetFiles(PollDir, @"*.wtp");

            if (tickets.Length == 0)
            {
                return;
            }

            File.Delete(tickets[0]);
            Log.InfoFormat("ticket({0}) were found in {0}.", tickets[0]);

            string[] files = Directory.GetFiles(AtlasDir, @"*.zip");

            if (files.Length == 0)
            {
                Log.InfoFormat("ProcessTrendScan() : No .wtp files were fuound in {0}.", PollDir);
                return;
            }

            string engineVersion = string.Empty;

            if (File.Exists(Settings.VscanEngine))
            {
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Settings.VscanEngine);

                engineVersion = string.Format("ENG[{0}]", fvi.FileVersion);
            }

            foreach (string fullPathName in files)
            {
                Dictionary <string, HashSet <string> > statistics = new Dictionary <string, HashSet <string> >();

                StringBuilder botInfo = new StringBuilder();


                foreach (BranchInfo branch in BranchInfoList)
                {
                    try
                    {
                        string[] results = branch.DoScan(fullPathName, 10 * 60 * 1000);

                        if (results == null)
                        {
                            Log.InfoFormat("{0} scan fail, no result is generated", branch.BranchName);

                            continue;
                        }

                        foreach (string line in results)
                        {
                            string[] columns = line.Split(',');

                            if (!statistics.ContainsKey(columns[0]))
                            {
                                statistics.Add(columns[0], new HashSet <string>());
                            }
                            statistics[columns[0]].Add(string.Format("{0}\t: {1}", branch.BranchName.ToUpper(), columns[1]));
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Log.ErrorFormat("ProcessTrendScan: {0}", ex.Message);
                    }
                }

                StringBuilder sb = new StringBuilder();

                if (statistics.Count > 0)
                {
                    sb.Append(Environment.NewLine);

                    foreach (KeyValuePair <string, HashSet <string> > blocks in statistics)
                    {
                        sb.AppendFormat("FileName\t: {0}", blocks.Key);
                        sb.Append(Environment.NewLine);

                        foreach (string block in blocks.Value)
                        {
                            sb.AppendLine(block);
                        }
                        sb.AppendLine("FileSize\t: N/A");
                        sb.AppendLine();
                    }
                }
                else
                {
                    sb.AppendLine("No Detection");
                }

                sb.AppendLine("End Of MIST Result");
                sb.AppendLine();

                sb.AppendLine("Name: " + Path.GetFileName(fullPathName));

                FileInfo fileInfo = new FileInfo(fullPathName);
                sb.AppendLine("Size: " + fileInfo.Length.ToString("#,0") + " Bytes");

                sb.AppendLine(string.Format("Scanned by: {0}", Dns.GetHostName()));
                sb.AppendLine();

                foreach (BranchInfo branch in BranchInfoList)
                {
                    sb.AppendLine(branch.BranchName.ToUpper() + "\t: " + engineVersion + branch.VersionInfo);
                }

                string resultName = string.Format(@".\result\{0}-{1}.done.txt", DateTime.Now.ToString("yyyyMMddHHmmss"), Path.GetFileName(fullPathName));

                Log.InfoFormat("writing {0} ...", Path.GetFullPath(resultName));

                try
                {
                    File.WriteAllText(resultName, sb.ToString());

                    Log.InfoFormat("{0} is generated success!", resultName);
                }
                catch (System.Exception ex)
                {
                    Log.ErrorFormat("{0}, {1} generated fail!", ex.Message, resultName);
                }


                try
                {
                    if (Directory.Exists(@".\backup"))
                    {
                        string target = string.Format(@".\backup\{0}", Path.GetFileName(fullPathName));
                        if (File.Exists(target))
                        {
                            File.Delete(target);
                        }
                        File.Move(fullPathName, target);
                    }
                    else
                    {
                        File.Delete(fullPathName);
                    }
                }
                catch (System.Exception ex)
                {
                    Log.ErrorFormat("ProcessTrendScan: {0}", ex.Message);
                }
            }
        }
Esempio n. 10
0
        public static void StartClient(string sendData)
        {
            StateData.userForm = new User();
            // Buffert
            byte[] bytes = new byte[1024];

            try
            {
                // Uni IP
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 25565);

                // Socket
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Anslut med try-catch
                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                                      sender.RemoteEndPoint.ToString());

                    // Encode
                    byte[] msg = Encoding.UTF8.GetBytes($"{sendData}<EOM>");

                    // Skicka
                    int bytesSent = sender.Send(msg);

                    // Ta emot
                    int    bytesRec       = sender.Receive(bytes);
                    string messageInHuman = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    Debug.WriteLine(messageInHuman);
                    HandleData(messageInHuman);



                    // Släpp.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 11
0
        public static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Esempio n. 12
0
        public static void ExecuteClient()
        {
            try
            {
                // Establish the remote endpoint
                // for the socket. This example
                // uses port 11111 on the local
                // computer.
                IPHostEntry ipHost        = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddr        = ipHost.AddressList[0];
                IPEndPoint  localEndPoint = new IPEndPoint(ipAddr, 11111);

                // Creation TCP/IP Socket using
                // Socket Class Costructor
                Socket sender = new Socket(ipAddr.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    // Connect Socket to the remote
                    // endpoint using method Connect()
                    sender.Connect(localEndPoint);

                    // We print EndPoint information
                    // that we are connected
                    Console.WriteLine("Socket connected to -> {0} ",
                                      sender.RemoteEndPoint.ToString());

                    // Creation of messagge that
                    // we will send to Server
                    byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
                    int    byteSent    = sender.Send(messageSent);

                    // Data buffer
                    byte[] messageReceived = new byte[1024];

                    // We receive the messagge using
                    // the method Receive(). This
                    // method returns number of bytes
                    // received, that we'll use to
                    // convert them to string
                    int byteRecv = sender.Receive(messageReceived);
                    Console.WriteLine("Message from Server -> {0}",
                                      Encoding.ASCII.GetString(messageReceived,
                                                               0, byteRecv));

                    // Close Socket using
                    // the method Close()
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }

                // Manage of Socket's Exceptions
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }

                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }

                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 13
0
        static Utility()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            localAddresses = host.AddressList;
        }
Esempio n. 14
0
        /// <summary>Initializes a new instance of the <see cref="SCHost"/> class.</summary>
        /// <param name="nickname">The nickname to be associated with this host.</param>
        /// <param name="chatID">The chat ID of the communication this host will take part into.</param>
        /// <param name="key">The encryption key used in this communication.</param>
        /// <param name="broadcast">The broadcast address of the local network.</param>
        /// <param name="port">The port to be used in this communication.</param>
        /// <param name="firstHello">If <code>true</code>, makes the host send a broadcast hello PDU once initialized.</param>
        public SCHost(string nickname, string chatID, byte[] key, IPAddress broadcast = null, int port = 4412, bool firstHello = true)
        {
            if (key.Length != 16)
            {
                throw new ScedaException("A SCEDA key must be 16 bytes long.");
            }
            this.myself          = new SCHostInfo();
            this.myself.Nickname = nickname;
            this.myself.ChatID   = chatID;
            this.myself.Port     = port;
            this.key             = key;
            this.others          = new List <SCHostInfo>();
            this.socket          = new UdpClient(this.myself.Port);
            this.socket.Client.EnableBroadcast = true;
            this.myself.Ip = IPAddress.Loopback;
            if (broadcast == null)
            {
                this.broadcast = IPAddress.Broadcast;
            }
            else
            {
                this.broadcast = broadcast;
            }
            this.disposed = false;
            this.remainingMalformedNotifications = 4;
            this.malformedTimer          = new System.Timers.Timer(600000);
            this.malformedTimer.Elapsed += delegate
            {
                this.remainingMalformedNotifications = 4;
            };
            this.listener = new Thread(delegate()
            {
                for (; ;)
                {
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, this.myself.Port);
                    byte[] binaryPdu    = this.socket.Receive(ref endPoint);
                    bool local          = endPoint.Address.Equals(IPAddress.Loopback);
                    foreach (IPAddress item in Dns.GetHostAddresses(Dns.GetHostName()))
                    {
                        if (endPoint.Address.Equals(item))
                        {
                            local = true;
                        }
                    }
                    if (!local && SCPdu.CheckChatID(binaryPdu, this.myself.ChatID))
                    {
                        SCHostInfo info = new SCHostInfo(endPoint.Address, endPoint.Port, this.GetNicknameFromIp(endPoint.Address), this.myself.ChatID);
                        try
                        {
                            SCPdu pdu = SCPdu.FromBinary(binaryPdu, this.key);
                            switch (pdu.Type)
                            {
                            case SCPduType.Hello:
                                {
                                    info.Nickname = pdu.Encoding.GetString(pdu.Payload);
                                    this.ManualSend(endPoint.Address, new SCPdu(this.myself.ChatID, SCPduType.Welcome, Encoding.Default, Encoding.Default.GetBytes(this.myself.Nickname)));
                                    if (this.Add(info, true) && this.OnHello != null)
                                    {
                                        this.OnHello(info);
                                    }
                                    break;
                                }

                            case SCPduType.Welcome:
                                {
                                    info.Nickname = pdu.Encoding.GetString(pdu.Payload);
                                    if (this.Add(info, true) && this.OnWelcome != null)
                                    {
                                        this.OnWelcome(info);
                                    }
                                    break;
                                }

                            case SCPduType.Leave:
                                {
                                    this.others.RemoveAll(item => item.Ip.Equals(info.Ip));
                                    if (this.OnLeave != null)
                                    {
                                        this.OnLeave(info);
                                    }
                                    break;
                                }

                            case SCPduType.Message:
                                {
                                    if (this.OnReceive != null)
                                    {
                                        this.OnReceive(info, pdu, pdu.Encoding.GetString(pdu.Payload));
                                    }
                                    break;
                                }

                            case SCPduType.MalformedPduNotification:
                                {
                                    if (this.OnMalformedNotification != null)
                                    {
                                        this.OnMalformedNotification(info, pdu.Payload);
                                    }
                                    break;
                                }

                            case SCPduType.NicknameConflictNotification:
                                {
                                    if (this.OnConflictNotification != null)
                                    {
                                        this.OnConflictNotification(info, new SCHostInfo(IPAddress.Parse(pdu.Encoding.GetString(pdu.Payload)), this.myself.Port, this.myself.Nickname, this.myself.ChatID));
                                    }
                                    break;
                                }
                            }
                        }
                        catch (MalformedPduException)
                        {
                            this.remainingMalformedNotifications--;
                            if (this.remainingMalformedNotifications > -1)
                            {
                                this.ManualSend(endPoint.Address, new SCPdu(this.myself.ChatID, SCPduType.Hello, Encoding.Default, new byte[0]));
                                this.malformedTimer.Start();
                            }
                            if (this.OnMalformedReceived != null)
                            {
                                this.OnMalformedReceived(info, binaryPdu);
                            }
                        }
                    }
                }
            });
            this.listener.Start();
            if (firstHello)
            {
                this.Hello();
            }
        }
Esempio n. 15
0
        [SkipOnHelix] // https://github.com/aspnet/AspNetCore/issues/7267
        public async Task RegisterAddresses_HostName_Success()
        {
            var hostName = Dns.GetHostName();

            await RegisterAddresses_Success($"http://{hostName}:0", $"http://{hostName}");
        }
        // Occurs when the user leaves the host name field
        private void m_hostNameTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                IPAddress[]             hostIPs  = Dns.GetHostAddresses(m_hostNameTextBox.Text);
                IEnumerable <IPAddress> localIPs = Dns.GetHostAddresses("localhost").Concat(Dns.GetHostAddresses(Dns.GetHostName()));

                // Check to see if entered host name corresponds to a local IP address
                if (!hostIPs.Any(localIPs.Contains))
                {
                    MessageBox.Show("You have entered a non-local host name for your MySql instance. By default remote access to MySQL database server is disabled for security reasons. If you have trouble connecting, check the security settings on the remote MySQL database server.", "MySql Security", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch
            {
                MessageBox.Show("The configuration utility could not determine if you entered a non-local host name for your MySql instance. Keep in mind that remote access to MySQL database server is disabled by default for security reasons. If you have trouble connecting, check the security settings on the remote MySQL database server.", "MySql Security", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Esempio n. 17
0
 public static string getHostName()
 {
     return  Dns.GetHostName();
 }
Esempio n. 18
0
        public static IServiceCollection AddOrleans(this IServiceCollection services, IConfiguration config, IWebHostEnvironment environment)
        {
            services.AddOrleans(config, environment, builder =>
            {
                builder.ConfigureServices(siloServices =>
                {
                    siloServices.Configure <ClusterOptions>(options =>
                    {
                        options.Configure();
                    });

                    siloServices.Configure <ProcessExitHandlingOptions>(options =>
                    {
                        options.FastKillOnProcessExit = false;
                    });

                    siloServices.Configure <DashboardOptions>(options =>
                    {
                        options.HideTrace = true;
                    });

                    siloServices.AddSingleton <IIncomingGrainCallFilter, LocalCacheFilter>();
                });

                builder.ConfigureApplicationParts(parts =>
                {
                    parts.AddApplicationPart(SquidexEntities.Assembly);
                    parts.AddApplicationPart(SquidexInfrastructure.Assembly);
                });

                builder.UseDashboard(options =>
                {
                    options.HostSelf = false;
                });

                var gatewayPort = config.GetOptionalValue("orleans:gatewayPort", 40000);

                var siloPort = config.GetOptionalValue("orleans:siloPort", 11111);

                config.ConfigureByOption("orleans:clustering", new Alternatives
                {
                    ["MongoDB"] = () =>
                    {
                        builder.ConfigureEndpoints(Dns.GetHostName(), siloPort, gatewayPort, listenOnAnyHostAddress: true);

                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        builder.UseMongoDBClustering(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    },
                    ["Development"] = () =>
                    {
                        builder.UseLocalhostClustering(siloPort, gatewayPort, null, Constants.OrleansClusterId, Constants.OrleansClusterId);
                        builder.Configure <ClusterMembershipOptions>(options => options.ExpectedClusterSize = 1);
                    }
                });

                config.ConfigureByOption("store:type", new Alternatives
                {
                    ["MongoDB"] = () =>
                    {
                        var mongoConfiguration = config.GetRequiredValue("store:mongoDb:configuration");
                        var mongoDatabaseName  = config.GetRequiredValue("store:mongoDb:database");

                        builder.UseMongoDBReminders(options =>
                        {
                            options.ConnectionString = mongoConfiguration;
                            options.CollectionPrefix = "Orleans_";
                            options.DatabaseName     = mongoDatabaseName;
                        });
                    }
                });
            });

            return(services);
        }
        void BuildSink(IServerChannelSinkProvider sinkProvider)
        {
            //resolve names (modified from TcpChannel)
            if (machineName == null)
            {
                if (useIPAddress)
                {
                    if (!bindAddress.Equals(IPAddress.Any))
                    {
                        machineName = bindAddress.ToString();
                    }
                    else
                    {
                        IPHostEntry hostEntry = Dns.Resolve(Dns.GetHostName());
                        if (hostEntry.AddressList.Length == 0)
                        {
                            throw new RemotingException("IP address could not be determined for this host");
                        }
                        // We DON'T want to take the resolved address from the hostEntry, since the socket
                        // should still bind to IPAddress.Any, so that we get the loopback too
                        machineName = hostEntry.AddressList[0].ToString();
                    }
                }
                else
                {
                    IPHostEntry hostEntry = Dns.GetHostByName(Dns.GetHostName());
                    bindAddress = hostEntry.AddressList[0];
                    machineName = hostEntry.HostName;
                }
            }

            if (sinkProvider == null)
            {
                //build a default chain that can handle wsdl, soap, binary
                sinkProvider           = new SdlChannelSinkProvider(); //for wsdl
                sinkProvider.Next      = new SoapServerFormatterSinkProvider();
                sinkProvider.Next.Next = new BinaryServerFormatterSinkProvider();
            }

            //MS compat: channelData is null when port < 0
            if (port >= 0)
            {
                channelData = new ChannelDataStore(null);
                IServerChannelSinkProvider provider = sinkProvider;
                while (provider != null)
                {
                    provider.GetChannelData(channelData);
                    provider = provider.Next;
                }
            }

            //create the sink chain and add an HTTP sink
            IServerChannelSink nextSink = ChannelServices.CreateServerChannelSinkChain(sinkProvider, this);

            sink = new HttpServerTransportSink(nextSink);

            // BaseChannelWithProperties wants this to be set with the chain
            base.SinksWithProperties = nextSink;

            StartListening(null);
        }
Esempio n. 20
0
        internal static void SetTraceFileName(ITraceConfiguration config, string nodeName, DateTime timestamp)
        {
            const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";

            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (config.TraceFilePattern == null ||
                string.IsNullOrWhiteSpace(config.TraceFilePattern) ||
                config.TraceFilePattern.Equals("false", StringComparison.OrdinalIgnoreCase) ||
                config.TraceFilePattern.Equals("none", StringComparison.OrdinalIgnoreCase))
            {
                config.TraceFileName = null;
            }
            else if (string.Empty.Equals(config.TraceFileName))
            {
                config.TraceFileName = null; // normalize
            }
            else
            {
                string traceFileDir = Path.GetDirectoryName(config.TraceFilePattern);
                if (!String.IsNullOrEmpty(traceFileDir) && !Directory.Exists(traceFileDir))
                {
                    string   traceFileName         = Path.GetFileName(config.TraceFilePattern);
                    string[] alternateDirLocations = { "appdir", "." };
                    foreach (var d in alternateDirLocations)
                    {
                        if (Directory.Exists(d))
                        {
                            config.TraceFilePattern = Path.Combine(d, traceFileName);
                            break;
                        }
                    }
                }
                config.TraceFileName = String.Format(config.TraceFilePattern, nodeName, timestamp.ToUniversalTime().ToString(dateFormat), Dns.GetHostName());
            }
        }
Esempio n. 21
0
        public void GetHostName()
        {
            string hostName = Dns.GetHostName();

            Assert.IsNotNull(hostName);
        }
 private void ChangeBalance(string username, int AB)
 {
     //tao ket noi
     SckClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     //tao cong
     ep = new IPEndPoint(IPAddress.Parse("25.81.81.59"), 9999);
     //bat dau gui du lieu
     SckClient.SendTo(Encoding.ASCII.GetBytes("3" + username + " " + AB.ToString() + " " + Dns.GetHostName()), ep);
 }
Esempio n. 23
0
        public object QueryPar(string parName)
        {
            //"申请识别码,患者识别码,申请ID,患者ID,患者姓名,用户ID,用户名称,设备ID,设备名称,
            //房间ID,房间名称,科室ID,科室名称,院区编码,本地日期,服务器日期,本机IP,本机名称";


            switch (parName)
            {
            case "系统_申请ID":
                if (_curBizDatas == null || _curBizDatas.Count <= 0)
                {
                    return(null);
                }
                return(DataHelper.GetItemValueByApplyId(_curBizDatas[0]));

            case "系统_患者ID":
                if (_curBizDatas == null || _curBizDatas.Count <= 0)
                {
                    return(null);
                }
                return(DataHelper.GetItemValueByPatientId(_curBizDatas[0]));

            case "系统_申请识别码":
                if (_curBizDatas == null || _curBizDatas.Count <= 0)
                {
                    return(null);
                }
                return(DataHelper.GetItemValueByApplyCode(_curBizDatas[0]));

            case "系统_患者识别码":
                if (_curBizDatas == null || _curBizDatas.Count <= 0)
                {
                    return(null);
                }
                return(DataHelper.GetItemValueByPatientCode(_curBizDatas[0]));

            case "系统_患者姓名":
                if (_curBizDatas == null || _curBizDatas.Count <= 0)
                {
                    return(null);
                }
                return(DataHelper.GetItemValueByPatientName(_curBizDatas[0]));

            case "系统_用户ID":
                return(_userData.UserId);

            case "系统_用户名称":
                return(_userData.Name);

            case "系统_用户账号":
                return(_userData.Account);

            case "系统_设备ID":
                return(_stationInfo.DeviceId);

            case "系统_设备名称":
                return(_stationInfo.DeviceName);

            case "系统_房间ID":
                return(_stationInfo.RoomId);

            case "系统_房间名称":
                return(_stationInfo.RoomName);

            case "系统_科室ID":
                return(_stationInfo.DepartmentId);

            case "系统_科室名称":
                return(_stationInfo.DepartmentName);

            case "系统_院区编码":
                return(_stationInfo.DistrictCode);

            case "系统_本地日期":
                return(DateTime.Now);

            case "系统_服务器日期":
                DBModel dmDate = new DBModel(_dbQuery);
                return(dmDate.GetServerDate());

            case "系统_本机IP":
                return(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString());

            case "系统_本机名称":
                return(Dns.GetHostName());

            default:
                if (_curBizDatas != null && _curBizDatas.Count > 0)
                {
                    parName = parName.Replace("系统_", "");
                    if (_curBizDatas[0].ContainsKey(parName))
                    {
                        return(_curBizDatas[0][parName]);
                    }
                }
                return(null);
            }
        }
Esempio n. 24
0
 // Start is called before the first frame update
 void Start()
 {
     TMP.text = $"My IP : {Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault().MapToIPv4()}";
 }
Esempio n. 25
0
 public SocketExc(ProtocolType protocol = ProtocolType.Tcp)
 {
     LocalHostName = Dns.GetHostName();
     Server        = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocol);
 }
Esempio n. 26
0
        private static void PersistData(Dictionary <String, Object> collectedData)
        {
            log.Debug("Starting  persistData for transaction " + collectedData["TxnName"]);
            String strsuccess = "Success";

            try
            {
                Dictionary <String, Object> hostDetails  = new Dictionary <String, Object>();
                Dictionary <String, Object> details      = new Dictionary <String, Object>();
                Dictionary <String, Object> others       = new Dictionary <String, Object>();
                Dictionary <String, Double> resourceTime = new Dictionary <String, Double>();

                hostDetails.Add("name", Dns.GetHostName());

                others.Add("domElementCount", collectedData["DomElements"]);
                others.Add("dom", collectedData["DOMContent"].ToString());
                if (collectedData.ContainsKey("msFirstPaint"))
                {
                    others.Add("msFirstPaint", collectedData["msFirstPaint"]);
                }

                details.Add("ClientName", collectedData["ClientName"]);
                details.Add("ProjectName", collectedData["ProjectName"]);
                details.Add("Scenario", collectedData["Scenario"]);
                details.Add("licenseKey", collectedData.ContainsKey("licenseKey")?collectedData["licenseKey"]:"");

                details.Add("dataStoreUrl", collectedData.ContainsKey("dataStoreUrl") ? collectedData["dataStoreUrl"]:"");
                details.Add("transactionName", collectedData["TxnName"]);
                details.Add("url", collectedData["Url"]);
                details.Add("txnStatus", collectedData["txnStatus"]);
                details.Add("Release", collectedData["Release"]);
                details.Add("RunID", collectedData["RunID"].ToString());
                details.Add("RunTime", collectedData["RunTime"]);

                details.Add("BuildNumber", collectedData["BuildNumber"]);
                details.Add("staticResourceExtension", collectedData["staticResourceExtension"]);
                details.Add("imageResourceExtension", collectedData["imageResourceExtension"]);
                details.Add("resourceDurationThreshold", collectedData["resourceDurationThreshold"]);
                details.Add("source", "SeleniumCSharp");

                log.Debug("Calling calculateBackendTime");
                resourceTime = CalculateBackendTime((List <Dictionary <string, object> >)collectedData["ResourceTime"], collectedData["NavType"].ToString());
                log.Debug("Completed calculateBackendTime");
                if (Convert.ToBoolean(collectedData["NavType"]))
                {
                    details.Add("NavType", "Hard");
                    details.Add("speedIndex", collectedData["SpeedIndex"]);
                    details.Add("StartTime", collectedData["StartTime"]);
                    details.Add("resourceLoadTime", resourceTime["backendTime"]);
                    details.Add("visuallyComplete", resourceTime["totalTime"]);
                }
                else
                {
                    details.Add("NavType", "Soft");
                    //details.put("SoftNavTotalTime",(Long.parseLong(collectedData.get("SoftNavTotalTime").toString()) <= 0 ? 0 : collectedData.get("SoftNavTotalTime")));
                    details.Add("StartTime", collectedData["StartTime"]);
                    details.Add("resourceLoadTime", resourceTime["backendTime"]);
                    details.Add("visuallyComplete", resourceTime["totalTime"]);
                }

                Dictionary <string, object> jsonDoc = new Dictionary <string, object>();
                jsonDoc.Add("details", details);
                jsonDoc.Add("host", hostDetails);

                jsonDoc.Add("platform", collectedData["Browser"]);
                jsonDoc.Add("memory", collectedData["Memory"]);
                jsonDoc.Add("others", others);
                jsonDoc.Add("navtime", collectedData["NavigationTime"]);

                if (collectedData.ContainsKey("MarkTime"))
                {
                    jsonDoc.Add("marktime", markListProcessed((List <Dictionary <string, object> >)collectedData["MarkTime"]));
                }

                Boolean crawlEnabled = (collectedData.ContainsKey("isResourceCrawlingEnabled") ? Convert.ToBoolean(collectedData["isResourceCrawlingEnabled"]) : true);
                log.Debug("Crawl Enabled is " + crawlEnabled + " for " + collectedData["TxnName"]);
                if (crawlEnabled)
                {
                    jsonDoc.Add("resources", CrawlUtils.getResourceDetails((List <Dictionary <String, Object> >)collectedData["ResourceTime"]));
                }
                else
                {
                    jsonDoc.Add("resources", collectedData["ResourceTime"]);
                }

                log.Debug("Crawl Completed: ");

                log.Debug("Data collected for " + collectedData["TxnName"] + " : " + jsonDoc.ToString());
                ICXOptimizeService cxOpService = new CXOptimiseServiceImpl();
                String             post        = cxOpService.uploadPerformanceData(JSONUtils.MapToJsonString(jsonDoc));

                log.Debug("Post Status : " + post);

                //Checking if the response is null. If so, then it will go to finally block
                if (post == null)
                {
                    log.Error("Unable to insert stats into datastore for " + collectedData["TxnName"] + ". Please check logs for further details.");
                    return;
                }
                if (!post.Contains(strsuccess))
                {
                    log.Error("The data could not be uploaded for " + collectedData["TxnName"] + ". The response from data store is " + post);
                }
                else
                {
                    log.Info("DataUploaded for succesfully for {}" + collectedData["TxnName"]);
                }
            }
            catch (Exception e)
            {
                log.Error("Exception in persistData for " + collectedData["TxnName"] + " at " + e);
            }
        }
 public string GetHostName() => Dns.GetHostName();
Esempio n. 28
0
        [SkipOnHelix] // https://github.com/aspnet/AspNetCore/issues/7267
        public async Task ListenAnyIP_HostName_Success()
        {
            var hostName = Dns.GetHostName();

            await ListenAnyIP_Success(new[] { $"http://{hostName}" });
        }
Esempio n. 29
0
 public void Dns_GetHostName_CallsSocketInit_Ok()
 {
     NameResolutionPal.FakesReset();
     Assert.ThrowsAny <Exception>(() => Dns.GetHostName());
     Assert.NotEqual(0, NameResolutionPal.FakesEnsureSocketsAreInitializedCallCount);
 }
Esempio n. 30
0
 // Gets the default value for the issuer.
 private string GetDefaultIssuer()
 {
     return(Dns.GetHostEntry(Dns.GetHostName()).HostName);
 }