Exemple #1
0
 public void StartSSDPDiscovery()
 {
     _client = NetworkServices.CreateSSDPClient();
     _client.ShowDiagnostics = true;
     _client.NewDeviceFound += _client_NewDeviceFound;
     _client.SsdpQueryAsync(port: 1900);
 }
Exemple #2
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    _psExecServices.RunOnDeviceWithoutAuthentication(device, "cmd.exe /C echo n | gpupdate.exe /force");
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #3
0
        private void MakeDiscoverable(string name)
        {
            if (_ssdpServer == null)
            {
                var _configuration = new UPNPConfiguration()
                {
                    UdpListnerPort  = _uPnPListenerPort,
                    FriendlyName    = name,
                    Manufacture     = "Tampa IoT Dev",
                    ModelName       = Constants.TankBotModelName,
                    DefaultPageHtml = @"<html>
<head>
<title>SoccerBot</title>
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" integrity=""sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"" crossorigin=""anonymous"">
</head>
<body>
<h1>Tampa IoT TankBot SSDP (uPnP) Listener Page</h1>
</body>
</html>"
                };

                try
                {
                    _ssdpServer = NetworkServices.GetSSDPServer();
                    _ssdpServer.MakeDiscoverable(9500, _configuration);
                }
                catch (Exception ex)
                {
                    _logger.NotifyUserError("ConnectionManager_MakeDiscoverable", ex.Message);
                }
            }
        }
Exemple #4
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (device == "")
                    {
                        continue;
                    }

                    ResultConsole.AddConsoleLine(ParseResponse(NetworkServices.PingTest(device), device));
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #5
0
        private async void GetAllSkyJSONData()
        {
            Debug.WriteLine("GetAllSkyJSONData enter");
            if (IsBusy)
            {
                Debug.WriteLine("GetAllSkyJSONData: GetJSON already busy, return");
                return;
            }
            IsBusy = true;

            // Check network status
            if (NetworkServices.IsConnectedToInternet())
            {
                Tuple <AllSkyDataClass, DownloadResult> allskyret;
                allskyret = await Task.Run(() => NetworkServices.GetJSON <AllSkyDataClass>(Settings.AllskyStatusURL));

                //4. Data setting
                DateTime ASDT = DateTimeUtils.UnixTimeStampToDateTime(allskyret.Item1.timestamp);
                AllSkyDate = DateTimeUtils.ConvertToLocal(ASDT).ToString("HH:mm:ss");
            }
            else
            {
                await ParentPage.DisplayAlert("Get allsky data", "No network is available.", "Ok");
            }
            IsBusy = false;
        }
        public void StartWebServer(int port, string name)
        {
            _deviceName = name;

            _webServer = NetworkServices.GetWebServer();
            _webServer.RegisterAPIHandler(new Api.MotionApi(_soccerBot, _logger));
            _webServer.DefaultPageHtml = GetDefaultPageHTML("Ready");
            _webServer.StartServer(port);
        }
Exemple #7
0
        protected virtual void RunScheduleTrigger(string scheduleId, string deviceList)
        {
            var devlist    = ParseDeviceList(deviceList);
            var failedlist = new List <string>();

            Connection = new ConnectionOptions {
                EnablePrivileges = true
            };

            try
            {
                Parallel.ForEach(devlist, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    ManagementScope remote        = null;
                    var remoteConnectExceptionMsg = "";

                    try
                    {
                        remote = WmiService.ConnectToRemoteWmi(device, Scope, Connection);
                    }
                    catch (Exception ex)
                    {
                        remoteConnectExceptionMsg = ex.Message;
                    }

                    if (remote != null)
                    {
                        SccmClientService.TriggerClientAction(scheduleId, remote);
                    }
                    else
                    {
                        ResultConsole.AddConsoleLine($"Error connecting to WMI scope {device}. Process aborted for this device.");
                        Logger.LogWarning($"Error connecting to WMI scope {device}. Process aborted for this device. Exception message: {remoteConnectExceptionMsg}", null);
                        failedlist.Add(device);
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }
            catch (Exception) { }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
        protected override void StartWatcher()
        {
            _logger.NotifyUserInfo("TCPIP Mgr", $"Started Watcher");

            _ssdpClient = NetworkServices.GetSSDPClient();
            _ssdpClient.ShowDiagnostics = true;
            _ssdpClient.NewDeviceFound += _ssdpClient_NewDeviceFound;
            _ssdpClient.SsdpQueryAsync(port: 1900);
        }
        async void fn()
        {
            var result = await NetworkServices.GetDistance();

            result.ForEach(c =>
            {
                var P_Province = c.DeliveryCostProvince;
            });
        }
        public override void Start()
        {
            _logger.NotifyUserInfo("TCPIP Mgr", $"Started Watcher");

            _ssdpClient = NetworkServices.GetSSDPClient();
            _ssdpClient.ShowDiagnostics = true;
            _ssdpClient.NewDeviceFound += _ssdpClient_NewDeviceFound;
            _ssdpClient.SsdpQueryAsync(port: Constants.UPNPListenPort);
        }
Exemple #11
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    var remote = _wmiServices.ConnectToRemoteWmi(device, _wmiServices.RootNamespace, new ConnectionOptions());
                    if (remote != null)
                    {
                        var query = new ObjectQuery("SELECT username FROM Win32_ComputerSystem");

                        var searcher        = new ManagementObjectSearcher(remote, query);
                        var queryCollection = searcher.Get();

                        foreach (var resultobject in queryCollection)
                        {
                            var result = $"{resultobject["username"]} logged in to {device}";

                            if (result == $" logged in to {device}" || result == $"  logged in to {device}")
                            {
                                result = $"There are no users logged in to {device}!";
                            }

                            ResultConsole.AddConsoleLine(result);
                        }
                    }
                    else
                    {
                        Logger.LogWarning("There was an error connecting to WMI namespace on " + device, null);
                        ResultConsole.AddConsoleLine("There was an error connecting to WMI namespace on " + device);
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #12
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    if (FileAndFolderServices.ValidateDirectoryExists(device, GpoCacheDir, ActionName, Logger))
                    {
                        var dirtyContents = Directory.EnumerateDirectories($"\\\\{device}\\C${GpoCacheDir}").ToList();
                        var contents      = new List <string>();

                        foreach (var directory in dirtyContents)
                        {
                            var cleanedPath = $"{GpoCacheDir}\\{directory.Substring(directory.LastIndexOf("\\") + 1)}";
                            contents.Add(cleanedPath);
                        }

                        foreach (var dir in contents)
                        {
                            FileAndFolderServices.CleanDirectory(device, dir, Logger);
                        }

                        _psExecServices.RunOnDeviceWithoutAuthentication(device, "cmd.exe /C gpupdate.exe /force");
                    }
                    else
                    {
                        ResultConsole.AddConsoleLine(
                            "Unable to validate the directory for the GPO cache. Please delete manually.");
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #13
0
        private void CallbackMethod()
        {
            var failedlist = new List <string>();

            try
            {
                foreach (var device in _parsedListCache)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    try
                    {
                        var result = _wmiServices.RepairRemoteWmi(device, _credToken);

                        if (!result)
                        {
                            failedlist.Add(device);
                        }

                        if (failedlist.Count > 0)
                        {
                            WriteToFailedLog(ActionName, failedlist);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError($"There was an error repairing WMI on device {device}. {ex.Message}", ex);
                        ResultConsole.Instance.AddConsoleLine($"There was an error repairing WMI on device {device}.");
                        failedlist.Add(device);
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }

            _credToken.Dispose();
        }
        public GamePlay(NetworkServices network)
        {
            InitializeComponent();
            serverResult                     = clientResult = 0;
            this.network                     = network;
            pressedKeys                      = new List <char>();
            ui                               = new UIService();
            network.ServerStoped            += NetworkServerStoped;
            network.ClientPressedLetter     += NetworkClientPressedLetter;
            network.ClientPlayAgainResponse += NetworkClientPlayAgainResponse;

            simpleSound = new SoundPlayer(@"tick.wav");

            ui.DrawKeyBoard(this, LetterClick);
        }
Exemple #15
0
        private void StartWebServer(int port, string name)
        {
            _deviceName = name;

            try
            {
                _webServer = NetworkServices.GetWebServer();
                _webServer.RegisterAPIHandler(new MotionRestAPI(_tankBot, _logger));
                _webServer.RegisterAPIHandler(new MotionController(this, _logger));
                _webServer.DefaultPageHtml = GetDefaultPageHTML("Ready");
                _webServer.StartServer(port);
            }
            catch (Exception ex)
            {
                _logger.NotifyUserError("ConnectionManager_StartWebServer", ex.Message);
            }
        }
        public CiscoTelePresenceCodec(string address, string username, string password)
        {
            DisableAutoSleepOnStopPlaying = false;
            _deviceAddressString          = address;
            _calls                             = new Calls(this);
            _systemUnit                        = new SystemUnit.SystemUnit(this);
            _cameras                           = new Cameras.Cameras(this);
            _standby                           = new Standby(this);
            _phonebook                         = new Phonebook.Phonebook(this);
            _bookings                          = new Bookings.Bookings(this);
            _audio                             = new Audio.Audio(this);
            _sip                               = new SIP.SIP(this);
            _roomAnalytics                     = new RoomAnalytics.RoomAnalytics(this);
            _video                             = new Video.Video(this);
            _callHistory                       = new CallHistory.CallHistory(this);
            _network[1]                        = new Network.Network(this, 1);
            _networkServices                   = new NetworkServices(this);
            _userInterface                     = new UserInterface.UserInterface(this);
            _diagnostics                       = new Diagnostics.Diagnostics(this);
            _conference                        = new Conference.Conference(this);
            _capabilities                      = new Capabilities.Capabilities(this);
            _sshClient                         = new CiscoSshClient(_deviceAddressString, username, password);
            _sshClient.ReceivedData           += SshClientOnReceivedData;
            _sshClient.ConnectionStatusChange += SshClientOnConnectionStatusChange;
            _httpsClient                       = new HttpsClient(address, username, password);

#if DEBUG
            CrestronConsole.AddNewConsoleCommand(Send,
                                                 "codecsend", "Send a codec xCommand",
                                                 ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(parameters =>
                                                 Send(string.Format("xCommand {0}", parameters)),
                                                 "xCommand", "Send a codec xCommand",
                                                 ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(parameters =>
                                                 Calls.DialNumber(parameters, (code, description, call) =>
            {
            }),
                                                 "Dial", "Dial a number",
                                                 ConsoleAccessLevelEnum.AccessOperator);
            CrestronConsole.AddNewConsoleCommand(parameters => Send("xStatus"),
                                                 "CodecStatus", "Get the full status of the codec",
                                                 ConsoleAccessLevelEnum.AccessOperator);
#endif
        }
Exemple #17
0
        public override void RunCommand(string rawDeviceList)
        {
            var connOps = new ConnectionOptions
            {
                EnablePrivileges = true
            };

            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(devlist, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    var remote = _wmiServices.ConnectToRemoteWmi(device, _wmiServices.RootNamespace, connOps);
                    if (remote != null)
                    {
                        _wmiServices.ForceRebootRemoteDevice(device, remote);
                    }
                    else
                    {
                        Logger.LogWarning($"There was an error connecting to WMI namespace on {device}", null);
                        ResultConsole.AddConsoleLine($"There was an error connecting to WMI namespace on {device}");
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #18
0
        private string ParseResponse(PingReply hostname, string device)
        {
            string returnMsg = "";

            try
            {
                // If the ping reply isn't null...
                if (hostname != null)
                {
                    // based on our connection status, return a message
                    switch (hostname.Status)
                    {
                    case IPStatus.Success:
                        returnMsg = $"Reply from {device} with address {hostname.Address}";
                        break;

                    case IPStatus.TimedOut:
                        returnMsg = "Connection has timed out.";
                        break;

                    default:
                        returnMsg = $"Ping to {device} failed with message {NetworkServices.GetIpStatusMessage(hostname.Status)}";
                        break;
                    }
                }
                else
                {
                    returnMsg = "Connection failed for an unknown reason. Likely, the host name is not known.";
                }
            }
            catch (PingException ex)
            {
                returnMsg = $"Connection Error: {ex.Message}";
            }
            catch (SocketException ex)
            {
                returnMsg = $"Connection Error: {ex.Message}";
            }

            return(returnMsg);
        }
Exemple #19
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(devlist, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine(
                            $"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    var sc = new ServiceController("CMRCService", device);

                    sc.Start();
                    ResultConsole.AddConsoleLine($"CMRCService started on {device}");
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }
            catch (Exception ex)
            {
                ResultConsole.AddConsoleLine($"Ended with error: {ex.Message}");
                Logger.LogError(ex.Message, ex);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #20
0
        private void btnStartClick(object sender, EventArgs e)
        {
            var options = new OptionsDialog();

            if (options.ShowDialog() == DialogResult.OK)
            {
                IPAddress ip   = IPAddress.Parse(cbIp.SelectedItem.ToString());
                int       port = 2000;

                Difficulty = options.Difficulty;
                Category   = options.Category;

                network = new NetworkServices();

                network.ServerStarted   += NetworkServerStarted;
                network.ServerStoped    += NetworkServerStoped;
                network.GameStarted     += NetworkGameStarted;
                network.ClientConnected += NetworkClientConnected;

                _ = network.Start(ip, port);
            }
        }
        public void MakeDiscoverable(string name)
        {
            var _configuration = new UPNPConfiguration()
            {
                UdpListnerPort  = 1900,
                FriendlyName    = name,
                Manufacture     = "Tampa IoT Dev",
                ModelName       = "SoccerBot-mBot",
                DefaultPageHtml = @"<html>
<head>
<title>SoccerBot</title>
<link rel=""stylesheet"" href=""https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" integrity=""sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"" crossorigin=""anonymous"">
</head>
<body>
<h1>Soccer Bot SSDP (uPnP) Listener Page</h1>
</body>
</html>"
            };


            _ssdpServer = NetworkServices.GetSSDPServer();
            _ssdpServer.MakeDiscoverable(9500, _configuration);
        }
Exemple #22
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(devlist, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    if (FileAndFolderServices.ValidateDirectoryExists(device, CcmCachePath, ActionName, Logger))
                    {
                        FileAndFolderServices.CleanDirectory(device, CcmCachePath, Logger);
                    }

                    if (FileAndFolderServices.ValidateDirectoryExists(device, WindowsTemp, ActionName, Logger))
                    {
                        FileAndFolderServices.CleanDirectory(device, WindowsTemp, Logger);
                    }

                    var userDirPaths = Directory.EnumerateDirectories($"\\\\{device}\\C${UsersDirectory}").ToList();
                    var userFolders  = new List <string>();

                    // Create useable paths
                    foreach (var userDir in userDirPaths)
                    {
                        var cleanedPath = $"{UsersDirectory}\\{userDir.Substring(userDir.LastIndexOf("\\") + 1)}";
                        userFolders.Add(cleanedPath);
                    }

                    foreach (var userFolder in userFolders)
                    {
                        if (FileAndFolderServices.ValidateDirectoryExists(device, userFolder, ActionName, Logger))
                        {
                            // Validate and Clean User Temp Folder at "C:\users\[user]\appdata\local\temp"
                            if (FileAndFolderServices.ValidateDirectoryExists(device, userFolder + UserTemp, ActionName, Logger))
                            {
                                FileAndFolderServices.CleanDirectory(device, userFolder + UserTemp, Logger);
                            }

                            // Validate and Clean User Temporary Internet Files at "C:\Users\[user]\AppData\Local\Microsoft\Windows\Temporary Internet Files"
                            if (FileAndFolderServices.ValidateDirectoryExists(device, userFolder + UserTempInternetFiles, ActionName, Logger))
                            {
                                FileAndFolderServices.CleanDirectory(device, userFolder + UserTempInternetFiles, Logger);
                            }

                            // Validate and Clean User Java Cache Files at "C:\Users\[user]\AppData\Local\Microsoft\Windows\Temporary Internet Files"
                            if (FileAndFolderServices.ValidateDirectoryExists(device, userFolder + JavaCache, ActionName, Logger))
                            {
                                FileAndFolderServices.CleanDirectory(device, userFolder + JavaCache, Logger);
                            }
                        }
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #23
0
        private async void GetAllSkyJSONData_old()
        {
            Debug.WriteLine("GetAllSkyJSONData enter");
            if (IsBusy)
            {
                Debug.WriteLine("GetAllSkyJSONData already busy, return");
                return;
            }
            IsBusy        = true;
            GetDataResult = DownloadResult.Undefined;
            Debug.WriteLine("GetAllSkyJSONData started, DownloadResult:" + GetDataResult);

            // Check network status
            if (NetworkServices.IsConnectedToInternet())
            {
                try
                {
                    //1. Download data
                    Uri                 geturi   = new Uri("http://astro.milantiev.com/allsky/stat.php"); //replace your xml url
                    HttpClient          client   = new HttpClient();
                    HttpResponseMessage response = await client.GetAsync(geturi);

                    Debug.WriteLine("GetAllSkyJSONData download completead, StatusCode:" + response.StatusCode);

                    //2. If data ok
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        //2.2. Read string
                        string responseSt = await response.Content.ReadAsStringAsync();

                        Debug.WriteLine("GetAllSkyJSONData DOWNLOAD DATA:" + responseSt);

                        try
                        {
                            //3.1 Set JSON parse options
                            JsonSerializerSettings JSONSettings = new JsonSerializerSettings();
                            JSONSettings.Culture = new CultureInfo("ru-RU");
                            JSONSettings.Culture.NumberFormat.NumberDecimalSeparator = ".";
                            JSONSettings.NullValueHandling = NullValueHandling.Ignore;

                            //3.2. JSON convert
                            AllSkyDataClass objResponse = JsonConvert.DeserializeObject <AllSkyDataClass>(responseSt, JSONSettings);

                            //4. Data setting
                            DateTime ASDT = DateTimeUtils.UnixTimeStampToDateTime(objResponse.timestamp);
                            AllSkyDate = DateTimeUtils.ConvertToLocal(ASDT).ToString("HH:mm:ss");
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception in GetAllSkyJSONData JSON parsing");
                            Debug.WriteLine(ex);
                            GetDataResult = DownloadResult.ParseError;
                        }
                    }
                    else
                    {
                        GetDataResult = DownloadResult.DownloadError;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in GetAllSkyJSONData download");
                    Debug.WriteLine(ex);
                    GetDataResult = DownloadResult.DownloadError;
                }
            }
            else
            {
                await ParentPage.DisplayAlert("Get allsky data", "No network is available.", "Ok");
            }
            IsBusy = false;
        }
Exemple #24
0
        private void CallbackMethod()
        {
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(_parsedListCache, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    var remote = _wmi.ConnectToRemoteWmi(device, _wmi.RootNamespace, new ConnectionOptions());
                    if (remote != null)
                    {
                        var searcher   = new ManagementObjectSearcher(remote, new ObjectQuery(ProfileQuery));
                        var collection = searcher.Get();
                        var profiles   = new List <ManagementObject>();

                        foreach (ManagementObject profileObject in collection)
                        {
                            CancellationToken.Token.ThrowIfCancellationRequested();

                            var queryObjDate = profileObject?["LastUseTime"];
                            if (queryObjDate == null)
                            {
                                continue;
                            }

                            var date = ManagementDateTimeConverter.ToDateTime(queryObjDate.ToString());

                            if (DateTime.Now.DayOfYear - date.DayOfYear >= _dayCountCache)
                            {
                                profiles.Add(profileObject);
                            }
                        }

                        var countText = $"{profiles.Count} profile{(profiles.Count == 1 ? String.Empty : "s")} slated for deletion.\n" +
                                        $"Deleting profiles older than {_dayCountCache} days on device {device}.";

                        ResultConsole.AddConsoleLine(countText);

                        try
                        {
                            Parallel.ForEach(profiles, (queryObj) =>
                            {
                                CancellationToken.Token.ThrowIfCancellationRequested();

                                var path = queryObj["LocalPath"];

                                queryObj.Delete();
                                queryObj.Dispose();

                                ResultConsole.AddConsoleLine($"Delete {path} from device {device} done.");
                            });
                        }
                        catch (Exception e)
                        {
                            Logger.LogError($"Deleting profiles on device {device} returned an error. {e.Message}", e);
                        }
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #25
0
        private void CallbackMethod()
        {
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(_parsedListCache, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        RemoteAccessEnabledKeyName,
                        BoolToIntString(_remoteAccessEnabled).ToString(),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        RequiresUserApprovalKeyName,
                        BoolToIntString(_requiresUserApproval),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        ShowConnectionBannerKeyName,
                        BoolToIntString(_showConnectionBanner),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        ShowTaskbarIconKeyName,
                        BoolToIntString(_showTaskBarIcon),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        AllowAccessOnUnattendedComputersKeyName,
                        BoolToIntString(_allowAccessOnUnattended),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        AllowLocalAdministratorsToRemoteControlKeyName,
                        BoolToIntString(_allowLocalAdministratorsToRemoteControl),
                        RegistryValueKind.DWord);

                    _registry.WriteToSubkey(
                        device,
                        RegistryHive.LocalMachine,
                        SccmRemoteControlRegistryPath,
                        AudibleSignalKeyName,
                        BoolToIntString(_audibleSignal),
                        RegistryValueKind.DWord);
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #26
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(devlist, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    var sc = new ServiceController(UpdateService, device);

                    ResultConsole.Instance.AddConsoleLine($"Stopping update service on device {device}");
                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        sc.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped, _timeouTimeSpan);
                        ResultConsole.Instance.AddConsoleLine($"Update service stopped on device {device}");
                    }
                    else
                    {
                        ResultConsole.Instance.AddConsoleLine($"Update service not running on device {device}. Continuing...");
                    }

                    var remotepath = $"\\\\{device}\\C$\\{SoftwareDistributionPath}";

                    if (FileAndFolderServices.ValidateDirectoryExists(device, SoftwareDistributionPath, ActionName, Logger))
                    {
                        var contentsList = Directory.GetFileSystemEntries(remotepath).ToList();
                        if (contentsList?.Count > 0)
                        {
                            foreach (var str in contentsList)
                            {
                                var isdir = File.Exists(str);
                                if (isdir)
                                {
                                    File.Delete(str);
                                    continue;
                                }

                                Directory.Delete(str, true);
                            }
                        }
                    }

                    ResultConsole.Instance.AddConsoleLine($"Starting update service on device {device}");
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running, _timeouTimeSpan);
                    ResultConsole.Instance.AddConsoleLine($"Update service started on device {device}");
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #27
0
        public override void RunCommand(string rawDeviceList)
        {
            var connOps = new ConnectionOptions
            {
                EnablePrivileges = true
            };

            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    var remote = _wmiServices.ConnectToRemoteWmi(device, _wmiServices.RootNamespace, connOps);
                    if (remote != null)
                    {
                        ObjectQuery query = new SelectQuery("Win32_ComputerSystem");

                        var searcher = new ManagementObjectSearcher(remote, query);

                        ManagementObjectCollection queryCollection = null;

                        try
                        {
                            queryCollection = searcher.Get();
                        }
                        catch (Exception e)
                        {
                            Logger.LogWarning($"QueryCollection returned with exception.", e);
                            ResultConsole.AddConsoleLine($"QueryCollection returned with exception {e.Message}");
                            continue;
                        }


                        if (queryCollection.Count == 0)
                        {
                            Logger.LogWarning($"Query returned null or empty result list for device {device}", null);
                            ResultConsole.AddConsoleLine($"Query returned null or empty result list for device {device}");
                            continue;
                        }

                        foreach (ManagementObject resultobject in queryCollection)
                        {
                            ResultConsole.AddConsoleLine($"{device} returned model ID {resultobject["Model"]}");
                        }
                    }
                    else
                    {
                        var msg = ($"There was an error connecting to WMI namespace on {device}");

                        Logger.LogMessage(msg);
                        ResultConsole.AddConsoleLine(msg);
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
Exemple #28
0
        private void CallbackMethod()
        {
            var failedlist = new List <string>();

            try
            {
                Parallel.ForEach(_parsedListCache, (device) =>
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        return;
                    }

                    var fileName = fileCopyContextCache.FilePath.Split(new char[] { '\\' }).Last();

                    string destPath;
                    if (string.IsNullOrWhiteSpace(fileCopyContextCache.DestinationPath))
                    {
                        destPath = $"\\\\{device}\\C$\\";
                    }
                    else
                    {
                        if (fileCopyContextCache.DestinationPath.StartsWith("\\"))
                        {
                            fileCopyContextCache.DestinationPath = fileCopyContextCache.DestinationPath.Remove(0, 1);
                        }

                        if (fileCopyContextCache.DestinationPath.EndsWith("\\"))
                        {
                            fileCopyContextCache.DestinationPath = fileCopyContextCache.DestinationPath.Remove(fileCopyContextCache.DestinationPath.Length - 1, 1);
                        }

                        destPath = $"\\\\{device}\\C$\\{fileCopyContextCache.DestinationPath}\\";
                    }

                    ResultConsole.AddConsoleLine($"Copying file {fileName} to device {device}");

                    try
                    {
                        if (FileAndFolderServices.ValidateDirectoryExists(device, fileCopyContextCache.DestinationPath, ActionName, Logger))
                        {
                            File.Copy(fileCopyContextCache.FilePath, destPath + fileName, fileCopyContextCache.Overwrite);
                            Logger.LogMessage($"Copied file {fileName} to {destPath}");
                        }
                        else if (fileCopyContextCache.CreateDestination)
                        {
                            Logger.LogMessage($"Creating directory {fileCopyContextCache.DestinationPath}");
                            Directory.CreateDirectory(destPath);

                            Thread.Sleep(100);

                            File.Copy(fileCopyContextCache.FilePath, destPath + fileName, fileCopyContextCache.Overwrite);
                        }
                        else
                        {
                            ResultConsole.AddConsoleLine("Unable to copy, destination doesn't exist.");
                            Logger.LogMessage("Unable to copy, destination doesn't exist.");
                        }
                    }
                    catch (Exception e)
                    {
                        ResultConsole.AddConsoleLine($"Unable to copy file {fileName}. Error: {e.Message}");
                        Logger.LogWarning($"Unable to copy file {fileName}.", e);
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }
 // Use this for initialization
 protected override void Awake()
 {
     base.Awake();   // Unity Bug: must be included in every child of MenuController
     _networkServices = new NetworkServices();
 }
Exemple #30
0
        public override void RunCommand(string rawDeviceList)
        {
            var devlist    = ParseDeviceList(rawDeviceList);
            var failedlist = new List <string>();

            var connOps = new ConnectionOptions
            {
                EnablePrivileges = true
            };

            try
            {
                foreach (var device in devlist)
                {
                    CancellationToken.Token.ThrowIfCancellationRequested();

                    if (!NetworkServices.VerifyDeviceConnectivity(device))
                    {
                        failedlist.Add(device);
                        ResultConsole.Instance.AddConsoleLine($"Device {device} failed connection verification. Added to failed list.");
                        continue;
                    }

                    var remote = _wmiServices.ConnectToRemoteWmi(device, _wmiServices.RootNamespace, connOps);
                    if (remote != null)
                    {
                        ObjectQuery query = new SelectQuery("Win32_OperatingSystem");

                        var searcher        = new ManagementObjectSearcher(remote, query);
                        var queryCollection = searcher.Get();

                        foreach (var resultobject in queryCollection)
                        {
                            var ro = resultobject as ManagementObject;
                            // Obtain in-parameters for the method
                            var inParams = ro.GetMethodParameters("Win32Shutdown");

                            // Add the input parameters.
                            inParams["Flags"] = 4;

                            try
                            {
                                // Execute the method and obtain the return values.
                                var outParams = ro.InvokeMethod("Win32Shutdown", inParams, null);

                                ResultConsole.AddConsoleLine($"Returned with value {_wmiServices.GetProcessReturnValueText(Convert.ToInt32(outParams["ReturnValue"]))}");
                            }
                            catch (Exception e)
                            {
                                ResultConsole.AddConsoleLine($"Error running {ActionName} due to a .Net ManagementExcept error. There are likely no users logged on!");
                                Logger.LogWarning($"Error running {ActionName} due to a .Net ManagementExcept error.", e);
                            }
                        }
                    }
                    else
                    {
                        Logger.LogWarning($"There was an error connecting to WMI namespace on {device}", null);
                        ResultConsole.AddConsoleLine($"There was an error connecting to WMI namespace on {device}");
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                ResetCancelToken(ActionName, e);
            }

            if (failedlist.Count > 0)
            {
                WriteToFailedLog(ActionName, failedlist);
            }
        }