Exemple #1
0
        private async void Intercep(object sender, FileSystemEventArgs e)
        {
            //if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                var path = e.FullPath;

                if (path.EndsWith("TMP"))
                {
                    var idx     = path.LastIndexOf('~');
                    var newPath = path.Substring(0, idx);
                    path = newPath;
                }
                else if (path.EndsWith(".xaml.g.cs")) //Handling VS2017 edit file behavior
                {
                    var compiledFileContent = FileHelper.GetFileContent(path);
                    var startStr            = "XamlFilePathAttribute";
                    var startIdx            = compiledFileContent.IndexOf(startStr);
                    var endIdx      = compiledFileContent.IndexOf(")]", startIdx);
                    var rawContent  = compiledFileContent.Substring(startIdx + startStr.Length, endIdx - (startIdx + startStr.Length));
                    var pathContent = rawContent
                                      .Replace("(", "")
                                      .Replace("\r", "")
                                      .Replace("\n", "")
                                      .Replace("+", "")
                                      .Replace("\\\\", "\\")
                                      .Replace("\"", "")
                                      .Replace(" ", "");
                    path = pathContent;
                }
                else if (path.Contains(".xaml") && path.Contains(".#"))
                {
                    var newPath = path.Replace(".#", "");
                    path = newPath;
                }
                else if (!path.EndsWith(".xaml"))
                {
                    return;
                }

                //------------------------------------------------------------
                //O evento OnChange está sendo chamado duas vezes sempre que
                //altera o arquivo. A logica abaixo, desconsidera a segunda
                //chamada caso ocorra em até 3 segundos
                //
                var dtNow = DateTime.Now;
                if (dtNow < nextProcess)
                {
                    return;
                }
                nextProcess = dtNow.AddSeconds(3);
                //---------------------------------------------


                await Task.Delay(700); //Necessário para evitar a exception "Esse arquivo está sendo usado por outro processo."

                var textContent = FileHelper.GetFileContent(path);

                if (string.IsNullOrEmpty(textContent))
                {
                    return;
                }

                var lastIdx = path.LastIndexOf('\\');
                if (lastIdx == -1)
                {
                    lastIdx = path.LastIndexOf('/');
                }
                string name = path.Substring(lastIdx + 1);

                string lsgMsg = $"{DateTime.Now}: Changes at file {name}. Sending to app...";
                Console.WriteLine(lsgMsg);
                DebugLog(lsgMsg);

                string data = $"{name}_ENDNAME_{textContent}";
                try
                {
                    await webSocketHandler.SendMessageToAllAsync(data);
                }
                catch (Exception)
                //catch (System.ObjectDisposedException ex)
                {
                    //Se der algum erro, reinicia o Socket mantendo as conexoes abertas
                    var sockets = webSocketHandler.Sockets;
                    webSocketHandler = new MyWebSocketHandler(sockets);
                    nextProcess      = DateTime.Now;

                    OnChanged(sender, e);
                }
            }
        }
        static void Main(string[] args)
        {
            var location  = Assembly.GetEntryAssembly().Location;
            var directory = Path.GetDirectoryName(location);

            try
            {
                //using (StreamWriter debugLogFile = new StreamWriter($"{directory}/Server_Debug.log"))
                {
                    PATH_TO_WATCH = GetArgsValue <string>(args, "--project-path", "").Trim();
                    var portArg        = GetArgsValue <string>(args, "--port", "9759").Trim();
                    var configFilePath = GetArgsValue <string>(args, "--config-path", "").Trim();

                    if (string.IsNullOrEmpty(PATH_TO_WATCH))
                    {
                        Console.WriteLine("Xam.Plugin.LiveSync.Server:");
                        Console.WriteLine("The argument --project-path is required. Set it to the root location where your XAML files are.");
                        Console.ReadKey();
                        return;
                    }

                    //debugLogFile.WriteLine($"{DateTime.Now}: --project-path {PATH_TO_WATCH}");
                    //debugLogFile.WriteLine($"{DateTime.Now}: --config-path {configFilePath}");

                    if (string.IsNullOrEmpty(configFilePath))
                    {
                        HOST = $"{GetIPAddress()}:{portArg}";
                    }
                    else
                    {
                        var hostText = FileHelper.GetFileContent(configFilePath);
                        HOST = hostText;
                    }

                    var hostPort = HOST.Split(":").LastOrDefault();
                    int.TryParse(hostPort, out PORT);

                    //debugLogFile.WriteLine($"{DateTime.Now}: host {HOST}");

                    Console.WriteLine($"Xam.Plugin.LiveSync.Server connected at: {HOST} watching the directory: {PATH_TO_WATCH}");

                    var host = new WebHostBuilder()
                               .UseUrls($"http://*:{PORT}")
                               .UseKestrel()
                               .UseStartup <Startup>()
                               .Build();

                    host.Run();
                }
            }
            catch (Exception ex)
            {
                using (StreamWriter writetext = new StreamWriter($"{directory}/ServerException_{DateTime.Now.Ticks}.log"))
                {
                    writetext.WriteLine(ex.Message);
                    writetext.WriteLine(ex.StackTrace);

                    if (ex.InnerException != null)
                    {
                        writetext.WriteLine(ex.InnerException.Message);
                        writetext.WriteLine(ex.InnerException.StackTrace);
                    }
                }
            }
        }