Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

// MainWindow.xaml.cs using Microsoft.Win32; using Newtonsoft.Json; using…

  1. User

    // MainWindow.xaml.cs using Microsoft.Win32; using Newtonsoft.Json; using ProjNet.CoordinateSystems; using ProjNet.CoordinateSystems.Transformations; using System; using System.Collections.Generic; using System.ComponentModel; // Для INotifyPropertyChanged using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives;

    namespace TxtProcessorApp { public partial class MainWindow : Window, INotifyPropertyChanged { // Реализация интерфейса INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    
        // Dictionaries to store data from files
        private Dictionary<string, List<string[]>> txtFileData = new Dictionary<string, List<string[]>>();
        private Dictionary<string, List<string[]>> magneteFileData = new Dictionary<string, List<string[]>>();
    
        // Backing fields for Combined DataTables
        private DataTable combinedTxtDataTable = new DataTable();
        private DataTable combinedMagneteDataTable = new DataTable();
    
        // Свойства для биндинга
        public DataTable CombinedTxtDataTable
        {
            get => combinedTxtDataTable;
            set
            {
                combinedTxtDataTable = value;
                OnPropertyChanged(nameof(CombinedTxtDataTable));
            }
        }
    
        public DataTable CombinedMagneteDataTable
        {
            get => combinedMagneteDataTable;
            set
            {
                combinedMagneteDataTable = value;
                OnPropertyChanged(nameof(CombinedMagneteDataTable));
            }
        }
    
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this; // Установка DataContext для биндинга
    
            // Инициализация колонок для объединённых .txt данных
            InitializeCombinedTxtDataTable();
    
            // Инициализация колонок для объединённых .magnete данных
            InitializeCombinedMagneteDataTable();
        }
    
        /// <summary>
        /// Инициализирует колонки для объединённых .txt данных.
        /// </summary>
        private void InitializeCombinedTxtDataTable()
        {
            CombinedTxtDataTable.Columns.Add("№", typeof(int));
            CombinedTxtDataTable.Columns.Add("BASE-1", typeof(string));
            CombinedTxtDataTable.Columns.Add("Noise", typeof(string));
            CombinedTxtDataTable.Columns.Add("Time", typeof(string));
            CombinedTxtDataTable.Columns.Add("Time UTC", typeof(string));
        }
    
        /// <summary>
        /// Инициализирует колонки для объединённых .magnete данных.
        /// </summary>
        private void InitializeCombinedMagneteDataTable()
        {
            CombinedMagneteDataTable.Columns.Add("DATA", typeof(string));
            CombinedMagneteDataTable.Columns.Add("DATA UTC", typeof(string));
            CombinedMagneteDataTable.Columns.Add("TIME", typeof(string));
            CombinedMagneteDataTable.Columns.Add("TIME UTC", typeof(string));
            CombinedMagneteDataTable.Columns.Add("Долгота WGS", typeof(string));
            CombinedMagneteDataTable.Columns.Add("Широта WGS", typeof(string));
            CombinedMagneteDataTable.Columns.Add("Долгота UTM", typeof(double));
            CombinedMagneteDataTable.Columns.Add("Широта UTM", typeof(double));
            CombinedMagneteDataTable.Columns.Add("№1", typeof(int));
            CombinedMagneteDataTable.Columns.Add("Альтитуда", typeof(string));
            CombinedMagneteDataTable.Columns.Add("№2", typeof(int));
            CombinedMagneteDataTable.Columns.Add("Shark", typeof(string));
        }
    
        #region File Loading Handlers
    
        // Handler for loading files
        private async void LoadFiles_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && button.Tag is string fileType)
            {
                string filter = fileType == "txt" ? "Текстовые файлы (*.txt)|*.txt" : "Magnete файлы (*.magnete)|*.magnete";
                OpenFileDialog ofd = new OpenFileDialog
                {
                    Multiselect = true,
                    Filter = filter
                };
    
                if (ofd.ShowDialog() == true)
                {
                    foreach (var file in ofd.FileNames)
                    {
                        await ProcessFileAsync(file, fileType);
                    }
    
                    // Update the respective TabControl
                    if (fileType == "txt")
                    {
                        PopulateTabControl(FilesTabControl, txtFileData, CreateTxtDataGrid);
                        CombinedTxtDataTable.Clear(); // Сброс объединённых данных
                    }
                    else
                    {
                        PopulateTabControl(MagneteFilesTabControl, magneteFileData, CreateMagneteDataGrid);
                        CombinedMagneteDataTable.Clear(); // Сброс объединённых данных
                    }
    
                    EditExportButton.IsEnabled = false;
                    StatusTextBlock.Text = $"Загружено {(fileType == "txt" ? txtFileData.Count : magneteFileData.Count)} {(fileType == "txt" ? ".txt" : ".magnete")} файлов.";
                }
            }
        }
    
        // Universal method for processing files
        private Task ProcessFileAsync(string filePath, string fileType)
        {
            return Task.Run(() =>
            {
                List<string[]> processedLines = new List<string[]>();
    
                try
                {
                    var lines = File.ReadAllLines(filePath);
                    if (fileType == "txt")
                    {
                        lines = lines.Skip(11).ToArray(); // Skip first 11 lines
                    }
    
                    foreach (var line in lines)
                    {
                        if (string.IsNullOrWhiteSpace(line))
                            continue;
    
                        var columns = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    
                        if (columns.Length == 0)
                            continue;
    
                        // Check the first column
                        if (columns[0].ToLower() == "nan" || string.IsNullOrWhiteSpace(columns[0]))
                            continue;
    
                        // Add columns based on file type
                        if (fileType == "txt")
                        {
                            // For .txt, skip the first column
                            processedLines.Add(columns.Skip(1).ToArray());
                        }
                        else
                        {
                            // For .magnete, add all columns
                            processedLines.Add(columns);
                        }
                    }
    
                    // Add processed data to the dictionary
                    string fileName = Path.GetFileName(filePath);
                    string uniqueFileName = GetUniqueFileName(fileName, fileType == "txt" ? txtFileData : magneteFileData);
                    if (fileType == "txt")
                    {
                        lock (txtFileData)
                        {
                            txtFileData[uniqueFileName] = processedLines;
                        }
                    }
                    else
                    {
                        lock (magneteFileData)
                        {
                            magneteFileData[uniqueFileName] = processedLines;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                        MessageBox.Show($"Ошибка при обработке файла {filePath}:\n{ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error));
                }
            });
        }
    
        // Method to generate unique file name
        private string GetUniqueFileName(string fileName, Dictionary<string, List<string[]>> existingData)
        {
            string originalFileName = fileName;
            int duplicateCount = 1;
            while (existingData.ContainsKey(fileName))
            {
                fileName = $"{Path.GetFileNameWithoutExtension(originalFileName)}_{duplicateCount}{Path.GetExtension(originalFileName)}";
                duplicateCount++;
            }
            return fileName;
        }
    
        // Method to populate TabControl
        private void PopulateTabControl(TabControl tabControl, Dictionary<string, List<string[]>> fileData, Func<List<string[]>, DataGrid> createGrid)
        {
            Dispatcher.Invoke(() =>
            {
                tabControl.Items.Clear();
                foreach (var kvp in fileData)
                {
                    TabItem tabItem = new TabItem
                    {
                        Header = kvp.Key,
                        Content = createGrid(kvp.Value)
                    };
                    tabControl.Items.Add(tabItem);
                }
            });
        }
    
        // Create DataGrid for .txt files (individual files)
        private DataGrid CreateTxtDataGrid(List<string[]> data)
        {
            DataGrid dataGrid = new DataGrid
            {
                AutoGenerateColumns = true,
                ItemsSource = ConvertToDataTable(data, isTxt: true).DefaultView,
                IsReadOnly = true,
                FontFamily = new System.Windows.Media.FontFamily("Consolas"),
                FontSize = 12,
                Margin = new Thickness(5)
            };
            return dataGrid;
        }
    
        // Create DataGrid for .magnete files (individual files)
        private DataGrid CreateMagneteDataGrid(List<string[]> data)
        {
            DataGrid dataGrid = new DataGrid
            {
                AutoGenerateColumns = true,
                ItemsSource = ConvertToDataTable(data, isTxt: false).DefaultView,
                IsReadOnly = true,
                FontFamily = new System.Windows.Media.FontFamily("Consolas"),
                FontSize = 12,
                Margin = new Thickness(5)
            };
            return dataGrid;
        }
    
        // Universal method to convert data to DataTable
        private DataTable ConvertToDataTable(List<string[]> data, bool isTxt)
        {
            DataTable dt = new DataTable();
            if (data == null || data.Count == 0)
                return dt;
    
            if (isTxt)
            {
                dt.Columns.Add("№", typeof(int));
                dt.Columns.Add("BASE-1", typeof(string));
                dt.Columns.Add("Noise", typeof(string));
                dt.Columns.Add("Time", typeof(string));
                dt.Columns.Add("Time UTC", typeof(string));
            }
            else
            {
                // Define columns for .magnete, assuming fixed number of columns
                dt.Columns.Add("Stan", typeof(string));
                dt.Columns.Add("Zeit", typeof(string));
                dt.Columns.Add("Noise", typeof(string));
                dt.Columns.Add("Time", typeof(string));
                dt.Columns.Add("TimeUTC", typeof(string));
            }
    
            foreach (var row in data)
            {
                DataRow dr = dt.NewRow();
                if (isTxt)
                {
                    dr["№"] = int.Parse(row[0]);
                    dr["BASE-1"] = row[1];
                    dr["Noise"] = row[2];
                    dr["Time"] = row[3];
                    dr["Time UTC"] = row[4];
                }
                else
                {
                    dr["Stan"] = row.Length > 0 ? row[0] : string.Empty;
                    dr["Zeit"] = row.Length > 1 ? row[1] : string.Empty;
                    dr["Noise"] = row.Length > 2 ? row[2] : string.Empty;
                    dr["Time"] = row.Length > 3 ? row[3] : string.Empty;
                    dr["TimeUTC"] = row.Length > 4 ? row[4] : string.Empty;
                }
                dt.Rows.Add(dr);
            }
    
            return dt;
        }
    
        #endregion
    
        #region File Combining Handler
    
        // Handler for Combine Files button
        private async void CombineFiles_Click(object sender, RoutedEventArgs e)
        {
            if (!txtFileData.Any() && !magneteFileData.Any())
            {
                MessageBox.Show("Нет загруженных файлов для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
    
            // Dialog to select file type to combine
            SelectEditTypeWindow selectWindow = new SelectEditTypeWindow("Выберите тип файлов для объединения:");
            selectWindow.Owner = this;
    
            if (selectWindow.ShowDialog() == true)
            {
                string selectedOption = selectWindow.SelectedOption;
    
                if (selectedOption == ".txt файлы" && txtFileData.Any())
                {
                    await CombineTxtFilesAsync();
                }
                else if (selectedOption == ".magnete файлы" && magneteFileData.Any())
                {
                    await CombineMagneteFilesAsync();
                }
                else
                {
                    MessageBox.Show("Выбранная опция недоступна или нет загруженных файлов данного типа.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    
        // Asynchronous method to combine .txt files
        private Task CombineTxtFilesAsync()
        {
            return Task.Run(() =>
            {
                List<string[]> combinedData = new List<string[]>();
                int lineNumber = 1;
    
                foreach (var file in txtFileData.Values)
                {
                    foreach (var row in file)
                    {
                        if (row.Length < 3)
                            continue;
    
                        string secondColumn = row[1];
                        string thirdColumn = row.Length > 1 ? row[2] : string.Empty;
                        string fourthColumn = row.Length > 2 ? row[3] : "0";
    
                        string timeString = "InvalidNumber";
                        if (double.TryParse(fourthColumn, NumberStyles.Any, CultureInfo.InvariantCulture, out double number))
                        {
                            double divided = number / 24;
                            TimeSpan time = TimeSpan.FromDays(divided);
                            timeString = time.ToString(@"hh\:mm\:ss");
                        }
    
                        combinedData.Add(new string[]
                        {
                            lineNumber.ToString(),
                            secondColumn,
                            thirdColumn,
                            fourthColumn,
                            timeString
                        });
    
                        lineNumber++;
                    }
                }
    
                // Конвертация списка в данные для существующей DataTable
                Dispatcher.Invoke(() =>
                {
                    CombinedTxtDataTable.Clear(); // Очищаем существующие данные
                    foreach (var row in combinedData)
                    {
                        CombinedTxtDataTable.Rows.Add(
                            int.Parse(row[0]),
                            row[1],
                            row[2],
                            row[3],
                            row[4]
                        );
                    }
    
                    EditExportButton.IsEnabled = true;
                    StatusTextBlock.Text = $"Объединены .txt файлы. Строк: {CombinedTxtDataTable.Rows.Count}.";
                });
            });
        }
    
        // Asynchronous method to combine .magnete files
        private Task CombineMagneteFilesAsync()
        {
            return Task.Run(() =>
            {
                if (!magneteFileData.Any())
                {
                    Dispatcher.Invoke(() =>
                        MessageBox.Show("Нет загруженных .magnete файлов для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information));
                    return;
                }
    
                DateTime fixedDate = new DateTime(1980, 1, 6, 0, 0, 0, DateTimeKind.Utc);
                DataTable combinedTable = new DataTable();
    
                Dispatcher.Invoke(() =>
                {
                    // Очищаем существующие данные
                    CombinedMagneteDataTable.Clear();
                });
    
                int sequentialNumber = 1;
                List<string> errorMessages = new List<string>();
    
                foreach (var file in magneteFileData.Values)
                {
                    foreach (var row in file)
                    {
                        DataRow newRow = CombinedMagneteDataTable.NewRow();
                        newRow["DATA UTC"] = fixedDate.ToString("dd.MM.yyyy");
                        newRow["TIME"] = row.Length > 0 ? row[0].Trim() : string.Empty;
                        newRow["Широта WGS"] = row.Length > 1 ? row[1].Trim() : string.Empty;
                        newRow["Долгота WGS"] = row.Length > 2 ? row[2].Trim() : string.Empty;
                        newRow["№1"] = sequentialNumber;
                        newRow["№2"] = sequentialNumber;
                        newRow["Альтитуда"] = row.Length > 3 ? row[3].Trim() : string.Empty;
                        newRow["Shark"] = row.Length > 4 ? row[4].Trim() : string.Empty;
                        newRow["Долгота UTM"] = 0.0;
                        newRow["Широта UTM"] = 0.0;
    
                        string stanValue = row.Length > 0 ? row[0].Trim() : string.Empty;
                        string zeitValue = row.Length > 1 ? row[1].Trim() : string.Empty;
                        string noiseValue = row.Length > 2 ? row[2].Trim() : string.Empty;
    
                        double longitude, latitude;
                        bool validCoordinates = true;
    
                        if (!double.TryParse(noiseValue, NumberStyles.Any, CultureInfo.InvariantCulture, out longitude))
                        {
                            string error = $"Не удалось распарсить Долгота WGS='{noiseValue}' в строке: {string.Join("\t", row)}.";
                            errorMessages.Add(error);
                            LogCalculation(error);
                            validCoordinates = false;
                        }
    
                        if (!double.TryParse(zeitValue, NumberStyles.Any, CultureInfo.InvariantCulture, out latitude))
                        {
                            string error = $"Не удалось распарсить Широта WGS='{zeitValue}' в строке: {string.Join("\t", row)}.";
                            errorMessages.Add(error);
                            LogCalculation(error);
                            validCoordinates = false;
                        }
    
                        if (validCoordinates)
                        {
                            try
                            {
                                int utmZone = GetUTMZone(longitude);
                                var utmCoordinates = ConvertWGS84ToUTM(longitude, latitude, utmZone);
                                newRow["Долгота UTM"] = utmCoordinates.Easting;
                                newRow["Широта UTM"] = utmCoordinates.Northing;
                            }
                            catch (Exception ex)
                            {
                                string error = $"Ошибка при преобразовании координат (Долгота WGS='{noiseValue}', Широта WGS='{zeitValue}') в строке: {string.Join("\t", row)}. Текст ошибки: {ex.Message}.";
                                errorMessages.Add(error);
                                LogCalculation(error);
                            }
                        }
    
                        // Handle "Stan" column
                        if (double.TryParse(stanValue, NumberStyles.Any, CultureInfo.InvariantCulture, out double stanSeconds))
                        {
                            if (stanSeconds < 0)
                            {
                                string warning = $"Отрицательное значение TIME='{stanSeconds}' в строке: {string.Join("\t", row)}. Установка даты как фиксированной.";
                                errorMessages.Add(warning);
                                LogCalculation(warning);
    
                                newRow["DATA"] = fixedDate.ToString("dd.MM.yyyy");
                                newRow["TIME UTC"] = fixedDate.ToString("HH:mm:ss.f");
                            }
                            else
                            {
                                try
                                {
                                    DateTime computedDate = fixedDate.AddSeconds(stanSeconds);
                                    newRow["DATA"] = computedDate.ToString("dd.MM.yyyy");
    
                                    TimeSpan offsetTime = TimeSpan.FromSeconds(18);
                                    TimeSpan computedTime = (computedDate.TimeOfDay >= offsetTime) ? computedDate.TimeOfDay - offsetTime : TimeSpan.Zero;
                                    double roundedSeconds = Math.Round(computedTime.TotalSeconds, 1, MidpointRounding.AwayFromZero);
                                    TimeSpan roundedTime = TimeSpan.FromSeconds(roundedSeconds);
                                    newRow["TIME UTC"] = roundedTime.ToString(@"hh\:mm\:ss\.f");
                                }
                                catch (Exception ex)
                                {
                                    string error = $"Ошибка при расчёте даты для TIME='{stanSeconds}' в строке: {string.Join("\t", row)}. Текст ошибки: {ex.Message}. Установка даты как фиксированной.";
                                    errorMessages.Add(error);
                                    LogCalculation(error);
    
                                    newRow["DATA"] = fixedDate.ToString("dd.MM.yyyy");
                                    newRow["TIME UTC"] = fixedDate.ToString("HH:mm:ss.f");
                                }
                            }
                        }
                        else
                        {
                            string error = $"Не удалось распарсить TIME='{stanValue}' в строке: {string.Join("\t", row)}. Установка даты как фиксированной.";
                            errorMessages.Add(error);
                            LogCalculation(error);
    
                            newRow["DATA"] = fixedDate.ToString("dd.MM.yyyy");
                            newRow["TIME UTC"] = fixedDate.ToString("HH:mm:ss.f");
                        }
    
                        CombinedMagneteDataTable.Rows.Add(newRow);
                        sequentialNumber++;
    
                        // Log calculations for each row
                        string logMessage = $"TIME: '{stanValue}', ComputedDate: '{newRow["DATA"]}', ComputedTime: '{newRow["TIME UTC"]}'";
                        LogCalculation(logMessage);
                    }
                }
    
                Dispatcher.Invoke(() =>
                {
                    EditExportButton.IsEnabled = true;
                    StatusTextBlock.Text = $"Объединены .magnete файлы. Строк: {CombinedMagneteDataTable.Rows.Count}.";
    
                    if (errorMessages.Any())
                    {
                        string allErrors = string.Join("\n", errorMessages);
                        LogCalculation($"Обнаружены следующие проблемы:\n{allErrors}");
                        MessageBox.Show($"Файлы .magnete объединены с ошибками. Подробности в файле логов.", "Внимание", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        MessageBox.Show($"Файлы .magnete успешно объединены. Строк: {CombinedMagneteDataTable.Rows.Count}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                });
            }
    
            #endregion
    
            #region Edit and Export Handler
    
            // Handler for Edit and Export button
            private void EditAndExport_Click(object sender, RoutedEventArgs e)
            {
                if (CombinedTxtDataTable == null && CombinedMagneteDataTable == null)
                {
                    MessageBox.Show("Нет объединённых данных для редактирования.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
    
                // Create and open a dialog to select the data type to edit
                SelectEditTypeWindow selectWindow = new SelectEditTypeWindow("Выберите данные для редактирования:");
                selectWindow.Owner = this;
    
                if (selectWindow.ShowDialog() == true)
                {
                    string selectedOption = selectWindow.SelectedOption;
    
                    if (selectedOption == ".txt файлы" && CombinedTxtDataTable != null)
                    {
                        OpenEditWindow(CombinedTxtDataTable, "Редактирование .txt данных");
                    }
                    else if (selectedOption == ".magnete файлы" && CombinedMagneteDataTable != null)
                    {
                        OpenEditWindow(CombinedMagneteDataTable, "Редактирование .magnete данных");
                    }
                    else
                    {
                        MessageBox.Show("Выбранная опция недоступна или данные отсутствуют.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
    
            // Method to open the edit window
            private void OpenEditWindow(DataTable dataTable, string windowTitle)
            {
                EditWindow editWindow = new EditWindow(dataTable)
                {
                    Title = windowTitle,
                    Owner = this
                };
                editWindow.ShowDialog();
    
                // После редактирования данные уже изменены в DataTable и отразятся в DataGrid благодаря биндингу
            }
    
            #endregion
    
            #region Project Handling
    
            // Handler for Save Project button
            private async void SaveProject_Click(object sender, RoutedEventArgs e)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Filter = "Magnte Project Files (*.magn)|*.magn",
                    DefaultExt = "magn",
                    FileName = "project.magn"
                };
    
                if (saveFileDialog.ShowDialog() == true)
                {
                    ProjectData project = new ProjectData
                    {
                        TxtFileData = this.txtFileData,
                        MagneteFileData = this.magneteFileData,
                        CombinedTxtDataTable = this.CombinedTxtDataTable,
                        CombinedMagneteDataTable = this.CombinedMagneteDataTable
                    };
    
                    try
                    {
                        // Asynchronously serialize the object to JSON
                        string json = await Task.Run(() => JsonConvert.SerializeObject(project, Formatting.Indented, new JsonSerializerSettings
                        {
                            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        }));
                        await File.WriteAllTextAsync(saveFileDialog.FileName, json, System.Text.Encoding.UTF8);
                        StatusTextBlock.Text = $"Проект сохранён: {saveFileDialog.FileName}";
                        MessageBox.Show("Проект успешно сохранён.", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Ошибка при сохранении проекта:\n{ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
    
            // Handler for Load Project button
            private async void LoadProject_Click(object sender, RoutedEventArgs e)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Filter = "Magnte Project Files (*.magn)|*.magn",
                    DefaultExt = "magn"
                };
    
                if (openFileDialog.ShowDialog() == true)
                {
                    try
                    {
                        string json = await File.ReadAllTextAsync(openFileDialog.FileName, System.Text.Encoding.UTF8);
                        ProjectData project = JsonConvert.DeserializeObject<ProjectData>(json);
    
                        if (project != null)
                        {
                            // Load .txt data
                            this.txtFileData = project.TxtFileData ?? new Dictionary<string, List<string[]>>();
                            PopulateTabControl(FilesTabControl, txtFileData, CreateTxtDataGrid);
    
                            // Load .magnete data
                            this.magneteFileData = project.MagneteFileData ?? new Dictionary<string, List<string[]>>();
                            PopulateTabControl(MagneteFilesTabControl, magneteFileData, CreateMagneteDataGrid);
    
                            // Load combined DataTables
                            CombinedTxtDataTable.Clear();
                            foreach (DataRow row in project.CombinedTxtDataTable.Rows)
                            {
                                CombinedTxtDataTable.ImportRow(row);
                            }
    
                            CombinedMagneteDataTable.Clear();
                            foreach (DataRow row in project.CombinedMagneteDataTable.Rows)
                            {
                                CombinedMagneteDataTable.ImportRow(row);
                            }
    
                            EditExportButton.IsEnabled = CombinedTxtDataTable.Rows.Count > 0 || CombinedMagneteDataTable.Rows.Count > 0;
    
                            StatusTextBlock.Text = $"Проект загружен: {openFileDialog.FileName}";
                            MessageBox.Show("Проект успешно загружен.", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            MessageBox.Show("Не удалось загрузить данные проекта.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Ошибка при загрузке проекта:\n{ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
    
            #endregion
    
            #region Graph Window Handler
    
            // Handler for Show Graphs button
            private void ShowGraphs_Click(object sender, RoutedEventArgs e)
            {
                if (CombinedTxtDataTable == null && CombinedMagneteDataTable == null)
                {
                    MessageBox.Show("Нет объединённых данных для построения графиков.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
    
                GraphWindow graphWindow = new GraphWindow(CombinedTxtDataTable, CombinedMagneteDataTable)
                {
                    Owner = this
                };
                graphWindow.ShowDialog();
    
                // Обновление StatusBar после закрытия GraphWindow
                StatusTextBlock.Text = $"Данные обновлены после редактирования графиков.";
            }
    
            #endregion
    
            #region Graph Combining Helper Methods
    
            // Method for logging calculations and errors
            private void LogCalculation(string message, string logFileName = "calculation_log.txt")
            {
                string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFileName);
                try
                {
                    File.AppendAllText(logFilePath, $"{DateTime.Now}: {message}{Environment.NewLine}");
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                        MessageBox.Show($"Не удалось записать лог: {ex.Message}", "Ошибка логирования", MessageBoxButton.OK, MessageBoxImage.Error));
                }
            }
    
            // Method to determine UTM zone based on longitude
            private int GetUTMZone(double longitude)
            {
                if (longitude < -180 || longitude > 180)
                    throw new ArgumentOutOfRangeException("Долгота должна быть в диапазоне от -180 до 180 градусов.");
    
                int zone = (int)Math.Floor((longitude + 180) / 6) + 1;
                return zone;
            }
    
            // Method to convert WGS84 coordinates to UTM
            private (double Easting, double Northing) ConvertWGS84ToUTM(double longitude, double latitude, int utmZone)
            {
                var wgs84 = GeographicCoordinateSystem.WGS84;
                var utmCS = ProjectedCoordinateSystem.WGS84_UTM(utmZone, latitude >= 0);
                var transformFactory = new CoordinateTransformationFactory();
                var transformation = transformFactory.CreateFromCoordinateSystems(wgs84, utmCS);
                double[] fromPoint = new double[] { longitude, latitude };
                double[] toPoint = transformation.MathTransform.Transform(fromPoint);
                return (toPoint[0], toPoint[1]);
            }
    
            #endregion
        }
    }
    

    }

    Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS1026 Требуется ")" magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 568 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS1002 Требуется ";". magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 568 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 575 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 607 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 624 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 663 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 723 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 746 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 761 Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка (активно) CS0106 Модификатор "private" недопустим для этого элемента. magn C:\Users\bonia\source\repos\magn\MainWindow.xaml.cs 771

    <Button.ContextMenu> </Button.ContextMenu>

        <!-- Строка состояния -->
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem>
                <TextBlock x:Name="StatusTextBlock" Text="Готово"/>
            </StatusBarItem>
        </StatusBar>
    
        <!-- Основная область с данными -->
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="3*"/>
                <RowDefinition Height="2*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="5"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
    
            <!-- Левая область для файлов -->
            <GroupBox Header=".txt Файлы" Grid.Row="0" Grid.Column="0" Margin="0,10,5,10">
                <TabControl x:Name="FilesTabControl"/>
            </GroupBox>
    
            <!-- Разделитель -->
            <GridSplitter Grid.Row="0" Grid.Column="1" Width="5" HorizontalAlignment="Stretch" Background="Gray"/>
    
            <!-- Правая область для файлов -->
            <GroupBox Header=".magnete Файлы" Grid.Row="0" Grid.Column="2" Margin="5,10,0,10">
                <TabControl x:Name="MagneteFilesTabControl"/>
            </GroupBox>
    
            <!-- Нижняя область для объединённых данных -->
            <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="5"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="5"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
    
                <!-- Объединённые .txt данные -->
                <GroupBox Header="Объединённые .txt Файлы" Grid.Row="0" Grid.Column="0" Margin="0,10,5,10">
                    <DataGrid x:Name="CombinedTxtDataGrid" 
                              AutoGenerateColumns="True" 
                              IsReadOnly="True" 
                              ItemsSource="{Binding CombinedTxtDataTable.DefaultView}" 
                              FontFamily="Consolas" 
                              FontSize="12" 
                              Margin="5"/>
                </GroupBox>
    
                <!-- Разделитель -->
                <GridSplitter Grid.Row="0" Grid.Column="1" Width="5" HorizontalAlignment="Stretch" Background="Gray"/>
    
                <!-- Объединённые .magnete данные -->
                <GroupBox Header="Объединённые .magnete Файлы" Grid.Row="0" Grid.Column="2" Margin="5,10,0,10">
                    <DataGrid x:Name="CombinedMagneteDataGrid" 
                              AutoGenerateColumns="True" 
                              IsReadOnly="True" 
                              ItemsSource="{Binding CombinedMagneteDataTable.DefaultView}" 
                              FontFamily="Consolas" 
                              FontSize="12" 
                              Margin="5"/>
                </GroupBox>
            </Grid>
        </Grid>
    </DockPanel>
    
  2. Assistant

    The errors you're encountering are primarily due to missing closing braces and parentheses in your CombineMagneteFilesAsync method. When braces and parentheses are not properly closed, the C# compiler gets confused, leading to a cascade of syntax errors, including unexpected modifiers like private being incorrectly placed inside other code blocks.

    Let's analyze the specific issues and provide a solution to correct them.

    Identifying the Problem

    Looking at your CombineMagneteFilesAsync method, it appears that the method's closing braces and parentheses are missing. Here's the problematic part of your code:

    private Task CombineMagneteFilesAsync()
    {
        return Task.Run(() =>
        {
            // ... [Processing Logic] ...
            Dispatcher.Invoke(() =>
            {
                // ... [UI Updates] ...
            });
        }
    
        #endregion
    
        #region Edit and Export Handler
    
        // ... [Other Methods] ...
    }
    

    Issues:

    1. Missing Closing Parentheses and Braces:

      • The Task.Run lambda expression is not properly closed. After the lambda's body ({ ... }), you need to close both the lambda and the Task.Run method call with });.
      • The CombineMagneteFilesAsync method itself is not properly closed with a }.
    2. Resulting Compiler Errors:

      • CS1026 (Expected ")"): The compiler is expecting a closing parenthesis for the Task.Run method.
      • CS1002 (Expected ";"): Due to the missing closing, the compiler gets confused about where statements end.
      • CS0106 (Modifier "private" is not valid here): Subsequent methods are mistakenly considered inside the CombineMagneteFilesAsync method, making the private access modifier invalid in that context.

    Solution

    To fix these errors, you need to properly close the lambda expression and the CombineMagneteFilesAsync method. Here's the corrected version of your method:

    // Asynchronous method to combine .magnete files
    private Task CombineMagneteFilesAsync()
    {
        return Task.Run(() =>
        {
            if (!magneteFileData.Any())
            {
                Dispatcher.Invoke(() =>
                    MessageBox.Show("Нет загруженных .magnete файлов для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information));
                return;
            }
    
            // ... [Rest of your processing logic] ...
    
            Dispatcher.Invoke(() =>
            {
                EditExportButton.IsEnabled = true;
                StatusTextBlock.Text = $"Объединены .magnete файлы. Строк: {CombinedMagneteDataTable.Rows.Count}.";
    
                if (errorMessages.Any())
                {
                    string allErrors = string.Join("\n", errorMessages);
                    LogCalculation($"Обнаружены следующие проблемы:\n{allErrors}");
                    MessageBox.Show($"Файлы .magnete объединены с ошибками. Подробности в файле логов.", "Внимание", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    MessageBox.Show($"Файлы .magnete успешно объединены. Строк: {CombinedMagneteDataTable.Rows.Count}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            });
        }); // Added closing parentheses and braces
    } // Added closing brace for the method
    

    Explanation of Fixes:

    1. Closing the Lambda Expression and Task.Run:

      • After the complete lambda body, close the lambda expression and the Task.Run method call with });. This ensures that the lambda is properly terminated and passed back to Task.Run.
    2. Closing the CombineMagneteFilesAsync Method:

      • After completing the Task.Run call, close the method with a }. This signifies the end of the method's scope.

    Revised Code Snippet

    Here’s the revised version of the problematic section in your MainWindow.xaml.cs, incorporating the necessary closing braces and parentheses:

    #region File Combining Handler
    
    // Handler for Combine Files button
    private async void CombineFiles_Click(object sender, RoutedEventArgs e)
    {
        if (!txtFileData.Any() && !magneteFileData.Any())
        {
            MessageBox.Show("Нет загруженных файлов для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }
    
        // Dialog to select file type to combine
        SelectEditTypeWindow selectWindow = new SelectEditTypeWindow("Выберите тип файлов для объединения:");
        selectWindow.Owner = this;
    
        if (selectWindow.ShowDialog() == true)
        {
            string selectedOption = selectWindow.SelectedOption;
    
            if (selectedOption == ".txt файлы" && txtFileData.Any())
            {
                await CombineTxtFilesAsync();
            }
            else if (selectedOption == ".magnete файлы" && magneteFileData.Any())
            {
                await CombineMagneteFilesAsync();
            }
            else
            {
                MessageBox.Show("Выбранная опция недоступна или нет загруженных файлов данного типа.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
    
    // Asynchronous method to combine .txt files
    private Task CombineTxtFilesAsync()
    {
        // ... [Your existing CombineTxtFilesAsync implementation] ...
    }
    
    // Asynchronous method to combine .magnete files
    private Task CombineMagneteFilesAsync()
    {
        return Task.Run(() =>
        {
            if (!magneteFileData.Any())
            {
                Dispatcher.Invoke(() =>
                    MessageBox.Show("Нет загруженных .magnete файлов для объединения.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information));
                return;
            }
    
            DateTime fixedDate = new DateTime(1980, 1, 6, 0, 0, 0, DateTimeKind.Utc);
            DataTable combinedTable = new DataTable();
    
            Dispatcher.Invoke(() =>
            {
                // Очищаем существующие данные
                CombinedMagneteDataTable.Clear();
            });
    
            int sequentialNumber = 1;
            List<string> errorMessages = new List<string>();
    
            foreach (var file in magneteFileData.Values)
            {
                foreach (var row in file)
                {
                    // ... [Your existing processing logic for .magnete files] ...
                }
            }
    
            Dispatcher.Invoke(() =>
            {
                EditExportButton.IsEnabled = true;
                StatusTextBlock.Text = $"Объединены .magnete файлы. Строк: {CombinedMagneteDataTable.Rows.Count}.";
    
                if (errorMessages.Any())
                {
                    string allErrors = string.Join("\n", errorMessages);
                    LogCalculation($"Обнаружены следующие проблемы:\n{allErrors}");
                    MessageBox.Show($"Файлы .magnete объединены с ошибками. Подробности в файле логов.", "Внимание", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    MessageBox.Show($"Файлы .magnete успешно объединены. Строк: {CombinedMagneteDataTable.Rows.Count}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            });
        });
    }
    
    #endregion
    

    Best Practices Moving Forward

    1. Proper Indentation and Formatting:

      • Ensuring that your code is well-indented makes it easier to spot missing braces and parentheses. Consider using an IDE like Visual Studio, which can automatically format your code.
    2. Brace Matching:

      • Most modern IDEs highlight matching braces. Utilize these features to ensure that every opening brace { or parenthesis ( has a corresponding closing counterpart } or ).
    3. Modular Code:

      • Breaking down your code into smaller, well-defined methods can reduce complexity and make it easier to manage braces and parentheses.
    4. Consistent Coding Style:

      • Adopt a consistent coding style, such as placing opening braces on the same line or the next line, based on your team's conventions or personal preference.
    5. Testing Incrementally:

      • Build and test your application incrementally. After writing significant blocks of code, compile to catch syntax errors early.
    6. Use Code Analysis Tools:

      • Tools like ReSharper or the built-in Code Analysis in Visual Studio can help identify and fix syntax and structural issues in your code.

    Final Thoughts

    By ensuring that all braces and parentheses are correctly paired and closed, you can eliminate the syntax errors you're experiencing. Following best practices in code formatting and structure will also help prevent similar issues in the future.

    If you encounter further errors or need additional assistance with specific parts of your code, feel free to ask!