コード例 #1
0
        /// <summary>
        /// Сохранение настроек в файл конфигурации
        /// </summary>
        public void SaveSettings()
        {
            // создаем объект
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // вносим изменения
            config.AppSettings.Settings["ServicePort"].Value         = ServicePort.ToString();
            config.AppSettings.Settings["LoadLevel"].Value           = LoadLevel.ToString();
            config.AppSettings.Settings["WatchInterval"].Value       = WatchInterval.ToString();
            config.AppSettings.Settings["ApplicationWorkTime"].Value = ApplicationWorkTime.ToString();
            config.AppSettings.Settings["ApplicationPath"].Value     = ApplicationPath;
            config.AppSettings.Settings["IsActive"].Value            = IsActive;
            // сохраняем
            config.Save(ConfigurationSaveMode.Modified);
            // обновялем
            ConfigurationManager.RefreshSection("appSettings");
        }
コード例 #2
0
    public async void Connect()
    {
        if (State == ConnectionState.Connecting || State == ConnectionState.Connected)
        {
            throw new InvalidOperationException("Connection is active");
        }

        State = ConnectionState.Connecting;

        try{
            socket = new StreamSocket();
            socket.Control.KeepAlive                 = true;
            socket.Control.QualityOfService          = SocketQualityOfService.Normal;
            socket.Control.OutboundBufferSizeInBytes = receivingBufferSize;

            Debug.LogFormat("Trying to connect to service {0} {1}", ServiceIPAddress, ServicePort.ToString());

            await socket.ConnectAsync(new HostName(ServiceIPAddress), ServicePort.ToString());

            State = ConnectionState.Connected;
        }
        catch (Exception e)
        {
            Debug.LogFormat("Connecting failed to service {0} {1}, {2}", ServiceIPAddress, ServicePort.ToString(), e.ToString());

            State = ConnectionState.Failed;
            throw e;
        }

        Debug.LogFormat("Connected to service {0} {1}", ServiceIPAddress, ServicePort.ToString());

        // start receiving
        writer = new DataWriter(socket.OutputStream);

        if (tokenSource == null)
        {
            tokenSource = new CancellationTokenSource();
        }

        receivingTask = Task.Factory.StartNew(SocketReceiveHandler, tokenSource.Token);
    }
コード例 #3
0
        private async void ServiceDiscovery_Click(object sender, EventArgs e)
        {
            int[] PortRanges = new int[]
            {
                80,  // Only for HTTP
                443, // Only for HTTPS
                5846,
                5847,
                5848,
                5849,
                5850,
                5851,
                5852,
                5853,
                5854,
                5855,
                5856
            };

            string commandString  = string.Empty;
            string responseString = string.Empty;
            string cardServiceURI = string.Empty;

            textBoxCommand.Text    = commandString;
            textBoxResponse.Text   = responseString;
            textBoxCardReader.Text = cardServiceURI;
            textBoxEvent.Text      = string.Empty;

            ServicePort = null;


            foreach (int port in PortRanges)
            {
                try
                {
                    WebSocketState state;
                    using (var socket = new ClientWebSocket())
                    {
                        var cancels = new CancellationTokenSource();
                        cancels.CancelAfter(400);
                        await socket.ConnectAsync(new Uri($"{textBoxServiceURI.Text}:{port}/xfs4iot/v1.0"), cancels.Token);

                        state = socket.State;
                    }

                    if (state == WebSocketState.Open)
                    {
                        ServicePort = port;
                        var Discovery = new XFS4IoTClient.ClientConnection(new Uri($"{textBoxServiceURI.Text}:{ServicePort}/xfs4iot/v1.0"));

                        try
                        {
                            await Discovery.ConnectAsync();
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        var getServiceCommand = new GetServiceCommand(Guid.NewGuid().ToString(), new GetServiceCommand.PayloadData(CommandTimeout));
                        commandString = getServiceCommand.Serialise();
                        await Discovery.SendCommandAsync(getServiceCommand);

                        object cmdResponse = await Discovery.ReceiveMessageAsync();

                        if (cmdResponse is GetServiceCompletion response)
                        {
                            responseString = response.Serialise();
                            var service =
                                (from ep in response.Payload.Services
                                 where ep.ServiceUri.Contains("CardReader")
                                 select ep
                                ).FirstOrDefault()
                                ?.ServiceUri;

                            if (!string.IsNullOrEmpty(service))
                            {
                                cardServiceURI = service;
                            }
                        }
                        break;
                    }
                }
                catch (WebSocketException)
                { }
                catch (System.Net.HttpListenerException)
                { }
                catch (TaskCanceledException)
                { }
            }

            if (ServicePort is null)
            {
                textBoxPort.Text = "";
                MessageBox.Show("Failed on finding services.");
            }
            else
            {
                textBoxPort.Text = ServicePort.ToString();
            }

            textBoxCommand.Text    = commandString;
            textBoxResponse.Text   = responseString;
            textBoxCardReader.Text = cardServiceURI;
        }
コード例 #4
0
        public string Upload(int taskId, string fileName, int profileId, int userId, string hdNumber)
        {
            //no need to find and call com server, client should already be directly communicating with the correct imaging server
            var guid = ConfigurationManager.AppSettings["ComServerUniqueId"];

            _thisComServer = new ServiceClientComServer().GetServerByGuid(guid);

            if (_thisComServer == null)
            {
                log.Error($"Com Server With Guid {guid} Not Found");
                return("0");
            }

            var appPath = Path.Combine(HttpContext.Current.Server.MapPath("~"), "private", "apps");

            var task = new ServiceActiveImagingTask().GetTask(taskId);

            if (task == null)
            {
                return("0");
            }

            var imageProfile = new ServiceImageProfile().ReadProfile(profileId);

            var uploadPort = new ServicePort().GetNextPort(task.ComServerId);

            var path = _thisComServer.LocalStoragePath;


            try
            {
                var dir = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{ hdNumber}");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                log.Error("Could Not Create Directory");
                log.Error(ex.Message);
                return("0");
            }

            path = Path.Combine(path, "images", imageProfile.Image.Name, $"hd{hdNumber}", fileName);
            string arguments    = " /c \"";
            var    receiverPath = Path.Combine(appPath, "udp-receiver.exe");

            arguments += $"{receiverPath}\" --portbase {uploadPort}";
            arguments += $" --interface {_thisComServer.ImagingIp} --file {path}";

            var pid = StartReceiver(arguments, imageProfile.Image.Name);
            //use multicast session even though it's not a multicast, uploads still use udpcast
            var activeMulticast = new EntityActiveMulticastSession();

            if (pid != 0)
            {
                activeMulticast.ImageProfileId = imageProfile.Id;
                activeMulticast.Name           = imageProfile.Image.Name;
                activeMulticast.Pid            = pid;
                activeMulticast.Port           = uploadPort;
                activeMulticast.ComServerId    = _thisComServer.Id;
                activeMulticast.UserId         = userId;
                activeMulticast.UploadTaskId   = task.Id;

                var result = new ServiceActiveMulticastSession().AddActiveMulticastSession(activeMulticast);
                if (result)
                {
                    return(uploadPort.ToString());
                }
            }
            return("0");
        }
コード例 #5
0
        protected InjectorHostBase(bool forceCanInject = false)
        {
            _forceCanInject = forceCanInject;

            var dtoAssembly = typeof(NewAssemblyMessage).GetTypeInfo().Assembly;

            _messageHub.AdditionalTypeResolutionAssemblies.Add(dtoAssembly);

            // set up the discovery responder
            _servicePublisher = new InjectorServiceDefinition(async() =>
            {
                // get the current interfaces
                var ifs    = await CommsInterface.GetAllInterfacesAsync();
                var usable = ifs.Where(iface => iface.IsUsable && !iface.IsLoopback)
                             .Where(iface => iface.ConnectionStatus == CommsInterfaceStatus.Connected).ToList();

                // if none (how :O), we won't respond. how could we event
                if (!usable.Any())
                {
                    return(null);
                }

                return(new InjectorHostServiceResponse
                {
                    ServiceGuid = ServiceGuid,
                    ServiceName = GetType().FullName,
                    Port = ServicePort,
                    NumConnectedClients = ConnectedClients.Count,
                    RunningAt = ifs.Select(iface => String.Join(":", iface.IpAddress, ServicePort.ToString())).ToList()
                });
            }).CreateServicePublisher();
        }