예제 #1
0
        /// <summary>
        /// Выполняет запись в таблицу MainLog действия Пользователя
        /// </summary>
        /// <param name="name">
        /// Имя пользователя
        /// </param>
        /// <param name="asWho">
        /// Принидлежность к группе BP201, NS-2 и т.д.
        /// </param>
        /// <param name="action">
        /// То, что сделал пользователь
        /// </param>
        /// <param name="addSeconds">
        /// если нужно добавить секунды ко времени действия, по умолчанию - время берётся с базы
        /// </param>
        public static void ToUpdate(string name, string action, int addSeconds = 0)
        {
            try
            {
                string tiiime = null;
                if (addSeconds == 0)
                {
                    tiiime = "GETDATE()";
                }
                else
                {
                    tiiime = "'" + Convert.ToDateTime(ToCount("SELECT GETDATE()")).AddSeconds(addSeconds).ToString() + "'";
                }

                using (SqlConnection sqlConnection = new SqlConnection(connectString))
                {
                    sqlConnection.Open();
                    using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO  MainLog ([Who], [What], [WhenItWas]) VALUES(@Who, @What, " + tiiime + ")", sqlConnection))
                    {
                        sqlCommand.Parameters.AddWithValue("@Who", name);
                        sqlCommand.Parameters.AddWithValue("@What", action);
                        sqlCommand.ExecuteNonQuery();
                    }
                    sqlConnection.Close();
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("dataBase.ToUpdate1 " + e.Message);
            }
        }
예제 #2
0
 /// <summary>
 /// Выгрузка новой версии базы в Админке
 /// </summary>
 /// <param name="st">
 /// Сами данные exe
 /// </param>
 /// <param name="ver">
 /// Версия базы
 /// </param>
 public static void ToUpdate(Stream st, string ver)
 {
     try
     {
         using (SqlConnection sqlConnection = new SqlConnection(connectString))
         {
             sqlConnection.Open();
             using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO  ProgVer ([Data], [Version]) VALUES(@Data, @Version)", sqlConnection))
             {
                 sqlCommand.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarBinary, -1)
                 {
                     Value = st
                 });
                 sqlCommand.Parameters.Add(new SqlParameter("@Version", SqlDbType.NVarChar, -1)
                 {
                     Value = ver
                 });
                 sqlCommand.ExecuteNonQuery();
             }
             sqlConnection.Close();
         }
     }
     catch (Exception e)
     {
         MessageBoxTi.Show("dataBase.ToUpdate2 " + e.Message);
     }
 }
예제 #3
0
        /// <summary>
        /// Возвращает List со значениями в строке из базы данных
        /// </summary>
        /// <param nae="action"m>
        /// Строка запроса(предпочтительно чтобы возвращал одну строку)
        /// </param>
        /// <returns></returns>
        public static List <object> SingleRow(string action)
        {
            try
            {
                List <object> columns = new List <object>();
                using (SqlConnection sqlConnection = new SqlConnection(connectString))
                {
                    sqlConnection.Open();
                    using (SqlCommand sqlCommand = new SqlCommand(action, sqlConnection))
                    {
                        var reader = sqlCommand.ExecuteReader();

                        reader.Read();
                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            columns.Add(reader.GetValue(i));
                        }
                        sqlConnection.Close();
                        return(columns);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("dataBase.SingleRow " + e.Message);
                return(null);
            }
        }
예제 #4
0
        public static void Graphics(List <DataPoint> Values, string chartName = null, string legend = null, excel.XlChartType type = excel.XlChartType.xlColumnClustered)
        {
            if (Values.Count == 0)
            {
                return;
            }

            try
            {
                Supports.GetProfileForm().ChangeState();
                word.Application app = new word.Application();
                app.Visible = true;
                Thread.Sleep(500);
                var doc = app.Documents.Add();


                word.InlineShape chartShape = doc.InlineShapes.AddOLEObject((Microsoft.Office.Core.XlChartType)type);
                chartShape.AlternativeText = "Chart1";
                word.Chart chart = chartShape.OLEFormat.Object as word.Chart;
                dynamic    book  = chart.ChartData.Workbook;
                //dynamic bookTable = book.Sheets[1].ListObjects("Table1");
                //bookTable.DataBodyRange.ClearContents();
                //Thread.Sleep(500);
                //excel.Chart chart =  exApp.Charts[0];
                //chart.SetSourceData(exApp.Cells.Range["A2", "E15"]);
                //exApp.Cells.Range["A2", "E5"].Clear();
                //sheert.ListObjects.Item[1].Resize(sheert.Range["A1", "B" + (Values.Count + 1).ToString()]);
                //sheert.Cells[1, 2] = legend;

                for (var i = 2; i < Values.Count + 2; i++)
                {
                    //exApp.Cells[i, 1] = DateTime.FromOADate(Values[i - 2].XValue);
                    //exApp.Cells[i, 2] = Values[i - 2].YValues[0];
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.Graphics " + e.Message);
                return;
            }
            finally
            {
                Supports.GetProfileForm().ChangeState(true);
            }
        }
예제 #5
0
        /// <summary>
        /// Чек-сумма нужного куска базы данных (используется для обнаружения изменений базы внесенных извне)
        /// </summary>
        /// <param name="stringForChecking">
        /// Строка запроса, для которой нужно расчитать чек-сумму
        /// </param>
        /// <returns></returns>
        public static int CheckSum(string stringForChecking, bool justRej = false)
        {
            try
            {
                string rec = null;
                if (justRej)
                {
                    rec = stringForChecking;
                }
                else
                {
                    rec = "SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM " + stringForChecking + ";";
                }

                using (SqlConnection sqlConnection = new SqlConnection(connectString))
                {
                    sqlConnection.Open();
                    using (SqlCommand sqlCommand = new SqlCommand(rec, sqlConnection))
                    {
                        sqlCommand.ExecuteNonQuery();
                        object y = sqlCommand.ExecuteScalar();

                        sqlConnection.Close();

                        if (y == DBNull.Value)
                        {
                            return(-1);
                        }
                        else
                        {
                            return(Convert.ToInt32(y));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("dataBase.CheckSum " + e.Message);
                return(0);
            }
        }
예제 #6
0
 /// <summary>
 /// Возвращает null, если поданый объект имеет нулевую длину
 /// </summary>
 /// <param name="param"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static object NullOrObjectIfEmpty(object param, Type type = null)
 {
     try
     {
         object t = DBNull.Value;
         if (param != null)
         {
             t = param.ToString().Equals("") ? DBNull.Value : param;
         }
         if (t != null && type != null)
         {
             t = Convert.ChangeType(t, type);
         }
         return(t);
     }
     catch (Exception e)
     {
         MessageBoxTi.Show("NullOrObjectIfEmpty " + e.Message);
         return(DBNull.Value);
     }
 }
예제 #7
0
        static void Main()
        {
            if ((int)dataBase.ToCount("SELECT count(*) FROM [dbo].[ProgVer]") != 0)
            {
                if (Convert.ToInt64(dataBase.ToCount("SELECT TOP 1 [Version] FROM [dbo].[ProgVer] ORDER BY [dbo].[ProgVer].[Version] DESC").ToString().Replace(".", string.Empty)) > Convert.ToInt64(Application.ProductVersion.Replace(".", string.Empty)))
                {
                    if (MessageBoxTi.Show("Ваша версия БД - " + Application.ProductVersion + ", акуальная версия - " + (string)dataBase.ToCount("SELECT TOP 1 [Version] FROM [dbo].[ProgVer] ORDER BY [dbo].[ProgVer].[Version] DESC") + ". Обновить?", "Обновление") == MessageResult.Yes)
                    {
                        int num = 0;

                        while (!Path.HasExtension(Application.ExecutablePath + num))
                        {
                            num++;
                        }

                        DataTable  ProgVer = dataBase.SimpleData("ProgVer");
                        byte[]     my      = (byte[])ProgVer.Rows.Cast <DataRow>().OrderByDescending(x => x["Version"]).FirstOrDefault()["Data"];
                        FileStream fs      = new FileStream(Application.ExecutablePath + num, FileMode.Create);
                        fs.Write(my, 0, my.Length);
                        fs.Close();
                        Application.Exit();

                        ProcessStartInfo info = new ProcessStartInfo();
                        info.Arguments      = "/C choice /C Y /N /D Y /T 3 & Del \"" + Application.ExecutablePath + "\" && ren \"" + Application.ExecutablePath + num + "\" \"" + AppDomain.CurrentDomain.FriendlyName + "\" && \"" + AppDomain.CurrentDomain.FriendlyName + "\"";
                        info.WindowStyle    = ProcessWindowStyle.Hidden;
                        info.CreateNoWindow = true;
                        info.FileName       = "cmd.exe";
                        Process.Start(info);

                        return;
                    }
                }
            }


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new LoginForm());
        }
예제 #8
0
        public static void Graphics1(List <DataPoint> Values, string chartName = null, string legend = null, excel.XlChartType type = excel.XlChartType.xlColumnClustered)
        {
            if (Values.Count == 0)
            {
                return;
            }

            try
            {
                Supports.GetProfileForm().ChangeState();
                word.Application app = new word.Application();
                app.Visible = true;
                Thread.Sleep(500);
                var doc = app.Documents.Add();
                word.InlineShape chartShape = doc.InlineShapes.AddChart2(212);
                chartShape.Chart.ChartTitle.Text = chartName;
                chartShape.Chart.ChartType       = (Microsoft.Office.Core.XlChartType)type;
                excel.Workbook  workbook = chartShape.Chart.ChartData.Workbook;
                excel.Worksheet sheert   = workbook.Worksheets[1];
                sheert.Cells.Range["A2", "E5"].Clear();
                sheert.ListObjects.Item[1].Resize(sheert.Range["A1", "B" + (Values.Count + 1).ToString()]);
                sheert.Cells[1, 2] = legend;

                for (var i = 2; i < Values.Count + 2; i++)
                {
                    sheert.Cells[i, 1] = DateTime.FromOADate(Values[i - 2].XValue);
                    sheert.Cells[i, 2] = Values[i - 2].YValues[0];
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.Graphics " + e.Message);
                return;
            }
            finally
            {
                Supports.GetProfileForm().ChangeState(true);
            }
        }
예제 #9
0
 /// <summary>
 /// Возвращает сухой Datatable.
 /// </summary>
 /// <param name="tableName">
 /// Строка апроса
 /// </param>
 /// <returns></returns>
 public static DataTable SimpleData(string tableName)
 {
     try
     {
         DataTable dt = new DataTable();
         using (SqlConnection sqlConnection = new SqlConnection(connectString))
         {
             sqlConnection.Open();
             using (SqlCommand sqlCommand = new SqlCommand("SELECT * FROM " + tableName + ";", sqlConnection))
             {
                 SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
                 da.Fill(dt);
                 sqlConnection.Close();
                 da.Dispose();
                 return(dt);
             }
         }
     }
     catch (Exception e)
     {
         MessageBoxTi.Show("database.SimpleData " + e.Message);
         return(null);
     }
 }
예제 #10
0
        private void NS2Controls()
        {
            Controls.Add(new Panel()
            {
                Name   = "NS2DocumentationPanel",
                Dock   = DockStyle.Top,
                Height = 500,
            });

            Controls.Add(new Panel()
            {
                Name   = "logPanel",
                Dock   = DockStyle.Top,
                Height = 600,
            });

            Controls.Add(new Panel()
            {
                Name   = "NS2WorkPlacePanel",
                Dock   = DockStyle.Top,
                Height = 700,
            });

            CurrentUserCard = new Panel()
            {
                Dock = DockStyle.Right, Width = 600
            };
            Panel Report202 = new Panel()
            {
                Dock = DockStyle.Left, Width = 400
            };

            Users = new DataGridView()
            {
                Dock = DockStyle.Fill,
                RowHeadersVisible         = false,
                SelectionMode             = DataGridViewSelectionMode.FullRowSelect,
                EditMode                  = DataGridViewEditMode.EditProgrammatically,
                AllowUserToOrderColumns   = false,
                AllowUserToResizeRows     = false,
                ScrollBars                = ScrollBars.Both,
                EnableHeadersVisualStyles = false,
                RowHeadersWidth           = 55,
                Height = 500,
                ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None,
                AllowUserToAddRows       = false,
            };

            Users.CellMouseDoubleClick += (s, e) =>
            {
                if (MessageBoxTi.Show("Блокировка прав доступа", Convert.ToBoolean(Users["Allowed", e.RowIndex].Value).Equals(true) ? "Заблокировать пользователя?" : "Разблокировать пользователя?") == MessageResult.Yes)
                {
                    dataBase.SimpleRequest("UPDATE [dbo].[Login] SET [Allowed] = " + Convert.ToInt32(!Convert.ToBoolean(Users["Allowed", e.RowIndex].Value)) + " WHERE [Login] = '" + Users["Login", e.RowIndex].Value + "'");
                }
            };

            (Controls.Find("NS2WorkPlacePanel", true).FirstOrDefault() as Panel).Controls.Add(Users);
            (Controls.Find("NS2WorkPlacePanel", true).FirstOrDefault() as Panel).Controls.Add(CurrentUserCard);


            (Controls.Find("logPanel", true).FirstOrDefault() as Panel).Controls.Add(new DataGridView()
            {
                Name = "logDataGridView",
                Dock = DockStyle.Fill,
                RowHeadersVisible         = false,
                SelectionMode             = DataGridViewSelectionMode.FullRowSelect,
                EditMode                  = DataGridViewEditMode.EditProgrammatically,
                AllowUserToOrderColumns   = false,
                AllowUserToResizeRows     = false,
                ScrollBars                = ScrollBars.Both,
                EnableHeadersVisualStyles = false,
                RowHeadersWidth           = 55,
                Height = 500,
                ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None,
                AllowUserToAddRows       = false,
            });

            (Controls.Find("logPanel", true).FirstOrDefault() as Panel).Controls.Add(new TableLayoutPanel()
            {
                Name  = "logHeadTableLayoutPanel",
                Width = 600,
                Dock  = DockStyle.Right,
            });

            (Controls.Find("logPanel", true).FirstOrDefault() as Panel).Controls.Add(new Label()
            {
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text      = "Хронология действий пользователей",
                Height    = 50,
                Dock      = DockStyle.Top,
            });

            (Controls.Find("NS2WorkPlacePanel", true).FirstOrDefault() as Panel).Controls.Add(new Label()
            {
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text      = "О пользователях",
                Height    = 50,
                Dock      = DockStyle.Top,
            });


            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 10f));
            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 90f));



            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "logHeadMenGroupBox",
                Text = "Для кого",
                Dock = DockStyle.Fill,
            }, 0, 1);

            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "logHeadWhatGroupBox",
                Text = "Для каких действий",
                Dock = DockStyle.Fill,
            }, 1, 1);

            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "logHeadTime1GroupBox",
                Text = "От",
                Dock = DockStyle.Fill,
            }, 0, 0);

            (Controls.Find("logHeadTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "logHeadTime2GroupBox",
                Text = "До",
                Dock = DockStyle.Fill,
            }, 1, 0);

            (Controls.Find("logHeadMenGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new CheckedListBox()
            {
                Name = "logHeadMenCheckedListBox",
                Dock = DockStyle.Fill,
            });

            (Controls.Find("logHeadTime1GroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new DateTimePicker()
            {
                Name  = "logHeadTime1DateTimePicker",
                Value = DateTime.Today.AddDays(-7),
                Dock  = DockStyle.Fill,
            });

            (Controls.Find("logHeadTime2GroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new DateTimePicker()
            {
                Name  = "logHeadTime2DateTimePicker",
                Value = DateTime.Today,
                Dock  = DockStyle.Fill,
            });

            (Controls.Find("logHeadWhatGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new CheckedListBox()
            {
                Name = "logHeadWhatCheckedListBox",
                Dock = DockStyle.Fill,
            });

            (Controls.Find("NS2DocumentationPanel", true).FirstOrDefault() as Panel).Controls.Add(Report202);

            Report202.Controls.Add(new Button()
            {
                Name  = "NS2DocumentationButton",
                Dock  = DockStyle.Top,
                Width = 37,
                Text  = "Сохранить изменения",
            });
            Report202.Controls.Add(new GroupBox()
            {
                Name   = "NS2DocumentationGroupBox2",
                Dock   = DockStyle.Top,
                Height = 52,
            });
            (Controls.Find("NS2DocumentationGroupBox2", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name = "NS2DocumentationTextBox2",
                Dock = DockStyle.Fill,
            });
            Report202.Controls.Add(new CheckedListBox()
            {
                Name  = "NS2DocumentationCheckedListBox1",
                Dock  = DockStyle.Top,
                Width = 150,
            });
            Report202.Controls.Add(new GroupBox()
            {
                Name   = "NS2DocumentationGroupBox1",
                Dock   = DockStyle.Top,
                Height = 52,
            });
            (Controls.Find("NS2DocumentationGroupBox1", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name = "NS2DocumentationTextBox1",
                Dock = DockStyle.Fill,
            });
            Report202.Controls.Add(new CheckedListBox()
            {
                Name  = "NS2DocumentationCheckedListBox",
                Dock  = DockStyle.Top,
                Width = 150,
            });
            Report202.Controls.Add(new GroupBox()
            {
                Name   = "NS2DocumentationGroupBox",
                Dock   = DockStyle.Top,
                Height = 52,
            });
            (Controls.Find("NS2DocumentationGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name = "NS2DocumentationTextBox",
                Dock = DockStyle.Fill,
            });
            Report202.Controls.Add(new Label()
            {
                Name      = "NS2DocumentationLabel",
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text      = "Отчет 202 поста",
                Dock      = DockStyle.Top,
                Width     = 37,
            });
            (Controls.Find("NS2DocumentationPanel", true).FirstOrDefault() as Panel).Controls.Add(new Label()
            {
                Name      = "NS2DocumentationLabel",
                TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
                Text      = "Отчеты",
                Dock      = DockStyle.Top,
                Width     = 50,
            });


            CurrentUserCard.Controls.Add(new TableLayoutPanel()
            {
                Name = "CurrentUserCardTableLayoutPanel",
                Dock = DockStyle.Fill,
            });

            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 25f));
            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 20f));
            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 55f));

            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new TableLayoutPanel()
            {
                Name = "CurrentUserCardTableLayoutPanel1",
                Dock = DockStyle.Fill,
            }, 0, 0);
            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20f));
            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40f));
            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40f));

            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new TableLayoutPanel()
            {
                Name = "CurrentUserCardTableLayoutPanel2",
                Dock = DockStyle.Fill,
            }, 1, 0);

            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 33f));
            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 33f));
            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Add(new RowStyle(SizeType.Percent, 33f));

            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new Panel()
            {
                Name = "CurrentUserCardPanel",
                Dock = DockStyle.Fill,
            }, 0, 2);

            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "UserGroupBox",
                Text = "Пользователь",
                Dock = DockStyle.Fill,
            }, 0, 0);

            (Controls.Find("CurrentUserCardTableLayoutPanel2", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "LoginGroupBox",
                Text = "Логин",
                Dock = DockStyle.Fill,
            }, 0, 1);


            (Controls.Find("CurrentUserCardPanel", true).FirstOrDefault() as Panel).Controls.Add(new GroupBox()
            {
                Name  = "RankGroupBox",
                Text  = "Звание",
                Width = 150,
                Dock  = DockStyle.Left,
            });

            (Controls.Find("CurrentUserCardPanel", true).FirstOrDefault() as Panel).Controls.Add(new GroupBox()
            {
                Name  = "DepartmentGroupBox",
                Text  = "Отдел",
                Width = 70,
                Dock  = DockStyle.Right,
            });



            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new PictureBox()
            {
                Name     = "CurrentUserCardPictureBox",
                Dock     = DockStyle.Fill,
                SizeMode = PictureBoxSizeMode.Zoom,
            }, 0, 0);

            (Controls.Find("RankGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name    = "RankTextBox",
                Dock    = DockStyle.Fill,
                Enabled = false,
            });

            (Controls.Find("DepartmentGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name    = "DepartmentTextBox",
                Enabled = false,
                Dock    = DockStyle.Fill,
            });

            (Controls.Find("LoginGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name    = "LoginTextBox",
                Enabled = false,
                Dock    = DockStyle.Fill,
            });
            (Controls.Find("UserGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name    = "UserTextBox",
                Enabled = false,
                Dock    = DockStyle.Fill,
            });


            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new DataGridView()
            {
                Name = "CurrentUserCardDataGridView",
                Dock = DockStyle.Fill,
                RowHeadersVisible         = false,
                SelectionMode             = DataGridViewSelectionMode.FullRowSelect,
                EditMode                  = DataGridViewEditMode.EditProgrammatically,
                AllowUserToOrderColumns   = false,
                AllowUserToResizeRows     = false,
                ScrollBars                = ScrollBars.Both,
                EnableHeadersVisualStyles = false,
                ColumnHeadersBorderStyle  = DataGridViewHeaderBorderStyle.None,
                AllowUserToAddRows        = false,
            }, 0, 2);

            (Controls.Find("CurrentUserCardTableLayoutPanel1", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new GroupBox()
            {
                Name = "StatisticGroupBox",
                Text = "Статистика",
                Dock = DockStyle.Fill,
            }, 2, 0);

            (Controls.Find("CurrentUserCardTableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new Panel()
            {
                Name = "CurrentUserCardPanel1",
                Dock = DockStyle.Fill,
            }, 0, 1);

            (Controls.Find("CurrentUserCardPanel1", true).FirstOrDefault() as Panel).Controls.Add(new GroupBox()
            {
                Name = "NoteGroupBox",
                Dock = DockStyle.Fill,
                Text = "Сообщение от НС",
            });
            (Controls.Find("NoteGroupBox", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
            {
                Name      = "NoteTextBox",
                Multiline = true,
                Dock      = DockStyle.Fill,
            });

            (Controls.Find("CurrentUserCardPanel1", true).FirstOrDefault() as Panel).Controls.Add(new Button()
            {
                Name  = "NoteButton",
                Dock  = DockStyle.Right,
                Width = 50,
                Image = Resources.add,
            });

            (Controls.Find("NoteButton", true).FirstOrDefault() as Button).Click += (s, e) =>
            {
                dataBase.SimpleRequest("UPDATE [dbo].[Login] SET [NSNote] = '" + (CurrentUserCard.Controls.Find("NoteTextBox", true).FirstOrDefault() as TextBox).Text + "' WHERE Login = '******'");
                dataBase.dataset.Tables["LoginNS"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals((CurrentUserCard.Controls.Find("LoginTextBox", true).FirstOrDefault() as TextBox).Text)).FirstOrDefault()["NSNote"] = (CurrentUserCard.Controls.Find("NoteTextBox", true).FirstOrDefault() as TextBox).Text;
            };
        }
예제 #11
0
        public static void WorkingHistoryMinMax(string satellite, string beam, string polarization, DateTime firstDateSet, DateTime secondDateSet)
        {
            string   path       = null;
            DateTime firstDate  = new DateTime(firstDateSet.Year, firstDateSet.Month, 1);
            DateTime secondDate = new DateTime(secondDateSet.Year, secondDateSet.Month, 1);

            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter   = "Word files (*.docx)|*.docx";
                saveFileDialog1.Title    = "Отчёт за период от " + firstDate.ToShortDateString() + " до " + secondDate.ToShortDateString();
                saveFileDialog1.FileName = firstDate.ToShortDateString() + " - " + secondDate.ToShortDateString() + ".docx";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = saveFileDialog1.FileName;
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.WorkingHistory " + e.Message);
                return;
            }

            Thread t = new Thread(delegate()
            {
                try
                {
                    Supports.GetProfileForm().ChangeState();
                    object miss          = System.Reflection.Missing.Value;
                    word.Application app = null;

                    app = new word.Application();

                    Thread.Sleep(1000);
                    var doc = app.Documents.Add();

                    app.Visible = false;
                    Thread.Sleep(1000);
                    doc.PageSetup.TopMargin    = 80;
                    doc.PageSetup.BottomMargin = 50;
                    doc.PageSetup.LeftMargin   = 60;
                    doc.PageSetup.RightMargin  = 60;
                    var par             = doc.Paragraphs.Add();
                    par                 = doc.Paragraphs.Add();
                    par.Alignment       = word.WdParagraphAlignment.wdAlignParagraphCenter;
                    par.Range.Font.Name = "Times New Roman";
                    par.Range.Font.Size = 12;


                    par.Range.Text = "История включений Спутника " + satellite + ", " + beam + " - диапазона, " + polarization + " - поляризации";
                    par            = doc.Paragraphs.Add();

                    word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 2, 3, DefaultTableBehavior: miss, AutoFitBehavior: miss);
                    fTable.Borders.InsideLineStyle  = word.WdLineStyle.wdLineStyleSingle;
                    fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;

                    fTable.Cell(1, 1).Range.Text = "Минимум";
                    fTable.Cell(1, 2).Range.Text = "Максимум";
                    fTable.Cell(1, 3).Range.Text = "Месяц";

                    fTable.Range.Font.Size = 10;

                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();

                    fTable.Range.Bold = 0;

                    par.Range.Font.Bold = 0;
                    par            = doc.Paragraphs.Add();
                    par            = doc.Paragraphs.Add();
                    par.Range.Text = firstDate.ToString("dd/MM/yyyy");
                    par.Alignment  = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    List <int> oneMonth = new List <int>();
                    int prevMonth       = firstDate.Month;

                    for (var i = 0; i < (secondDate.AddMonths(1) - firstDate).TotalDays; i++)
                    {
                        if (prevMonth == firstDate.AddDays(i).Month)
                        {
                            oneMonth.Add(Convert.ToInt32(dataBase.ToCount("SELECT ((SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 0 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) - " +
                                                                          "(SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) + " +
                                                                          "(SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1)) as [ALL]")));
                        }
                        else
                        {
                            fTable.Cell(fTable.Rows.Count, 1).Range.Text = oneMonth.Min().ToString();
                            fTable.Cell(fTable.Rows.Count, 2).Range.Text = oneMonth.Max().ToString();
                            fTable.Cell(fTable.Rows.Count, 3).Range.Text = firstDate.AddDays(i).ToString("MM/yyyy");
                            fTable.Range.Rows.Add();
                            oneMonth.Clear();
                            oneMonth.Add(Convert.ToInt32(dataBase.ToCount("SELECT ((SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 0 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) - " +
                                                                          "(SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) + " +
                                                                          "(SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1)) as [ALL]")));
                        }
                        prevMonth = firstDate.AddDays(i).Month;
                    }

                    fTable.Range.Rows[fTable.Range.Rows.Count].Delete();

                    fTable.Range.Paragraphs.SpaceAfter = 0;

                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;

                    fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow);
                    fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault);

                    doc.Close();

                    MessageBoxTi.Show("Отчёт готов");

                    if (app != null)
                    {
                        app.Quit();
                        Marshal.FinalReleaseComObject(app);

                        Thread.CurrentThread.Abort();
                    }
                    Thread.CurrentThread.Abort();
                }
                catch (Exception e)
                {
                    if (e.GetType() != typeof(ThreadAbortException))
                    {
                        MessageBoxTi.Show("Documentation.WorkingHistory.Thread " + e.Message);
                    }
                    return;
                }
                finally
                {
                    Supports.GetProfileForm().ChangeState(true);
                }
            });

            t.Start();
        }
예제 #12
0
        public Admin()
        {
            try
            {
                BorderStyle = BorderStyle.None;
                Name        = "tabPageAdmin";
                Text        = "Админ";
                BackColor   = Supports.headGrey;
                ForeColor   = Supports.headGrey;

                Controls.Add(new FlowLayoutPanel()
                {
                    BorderStyle = BorderStyle.None,
                    Name        = "FlowLayoutPanelAdmin",
                    Dock        = DockStyle.Fill,
                    AutoScroll  = true,
                });

                Controls.Add(new Panel()
                {
                    Name  = "foreignPanelAdmin",
                    Dock  = DockStyle.Right,
                    Width = 440,
                });

                (Controls.Find("foreignPanelAdmin", true).FirstOrDefault() as Panel).Controls.Add(foreignPeople);

                (Controls.Find("foreignPanelAdmin", true).FirstOrDefault() as Panel).Controls.Add(new Label()
                {
                    Font      = new Font("Times New Roman", 12, FontStyle.Bold),
                    TextAlign = ContentAlignment.MiddleCenter,
                    Dock      = DockStyle.Top,
                    Text      = "Грингос",
                });

                Controls.Add(new FlowLayoutPanel()
                {
                    BorderStyle = BorderStyle.None,
                    Name        = "FlowLayoutPanelData",
                    Dock        = DockStyle.Top,
                    Height      = 30,
                    Padding     = new Padding(3),
                    BackColor   = Supports.backBlack,
                });

                bool adminFirst = false;

                Enter += (se, e) =>
                {
                    try
                    {
                        dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login", onlyAdapter: true);

                        if (adminFirst == true)
                        {
                            return;
                        }

                        foreach (DataRow dr in dataBase.dataset.Tables["Login"].Rows.Cast <DataRow>().Where(x => Convert.ToInt32(x["Department"]) == 2))
                        {
                            (Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(UserCard(dr["Login"].ToString()));
                        }


                        (Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Panel()
                        {
                            Name      = "AddPanel",
                            Width     = 200,
                            Height    = 410,
                            BackColor = Supports.backBlack,
                            Padding   = new Padding(3),
                        });


                        (Controls.Find("FlowLayoutPanelData", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Label()
                        {
                            Name     = "DataLabel",
                            AutoSize = true,
                            Text     = "Текущая версия программы:",
                            Padding  = new Padding(0, 9, 0, 0),
                        });

                        (Controls.Find("FlowLayoutPanelData", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Label()
                        {
                            Name     = "DataLabel1",
                            Text     = (string)dataBase.ToCount("SELECT TOP 1 [Version] FROM [dbo].[ProgVer] ORDER BY [dbo].[ProgVer].[Version] DESC"),
                            AutoSize = true,
                            Padding  = new Padding(0, 9, 0, 0),
                        });



                        (Controls.Find("FlowLayoutPanelData", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Button()
                        {
                            Name      = "DataButton",
                            Text      = "Добавить новую версию",
                            Width     = 160,
                            FlatStyle = FlatStyle.Flat,
                        });

                        (Controls.Find("DataButton", true).FirstOrDefault() as Button).Click += (s, arg) =>
                        {
                            OpenFileDialog openFileDialog1 = new OpenFileDialog();
                            openFileDialog1.Filter = "EXECUTE files|*.exe;";
                            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                            {
                                dataBase.ToUpdate(openFileDialog1.OpenFile(), Application.ProductVersion);
                            }

                            (Controls.Find("DataLabel1", true).FirstOrDefault() as Label).Text = (string)dataBase.ToCount("SELECT TOP 1 [Version] FROM [dbo].[ProgVer] ORDER BY [dbo].[ProgVer].[Version] DESC");
                        };

                        (Controls.Find("AddPanel", true).FirstOrDefault() as Panel).Controls.Add(new Button()
                        {
                            Name      = "AddPanelButton",
                            Image     = Resources.plus,
                            Dock      = DockStyle.Fill,
                            FlatStyle = FlatStyle.Flat,
                            ForeColor = Supports.textBlack,
                            BackColor = Supports.headGrey
                        });

                        (Controls.Find("AddPanelButton", true).FirstOrDefault() as Button).Click += (s, arg) =>
                        {
                            string log = MessageBoxTi.Show("Логин", "Придумайте логин", HorizontalAlignment.Left);
                            while (log.Length > 15)
                            {
                                log = MessageBoxTi.Show("Логин", "Пользователь с таким ологином уже существует. Придумайте другой логин!", HorizontalAlignment.Left);
                                if (log == null || log == "")
                                {
                                    return;
                                }
                            }

                            if (dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(log)).Count() == 0 && log != "")
                            {
                                (Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(UserCard(log, true));
                                (Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.SetChildIndex((Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.Find("AddPanel", false).FirstOrDefault(), (Controls.Find("FlowLayoutPanelAdmin", true).FirstOrDefault() as FlowLayoutPanel).Controls.Count);
                                return;
                            }
                            else if (log == null || log == "")
                            {
                                return;
                            }
                            else
                            {
                                MessageBoxTi.Show("Такой логин уже существует");
                                return;
                            }
                        };
                        Controls.Find("AddPanelButton", true).FirstOrDefault().Focus();
                        adminFirst = true;



                        foreach (DataRow dr in dataBase.dataset.Tables["Login"].Rows.Cast <DataRow>().Where(x => Convert.ToInt32(x["Department"]) != 2))
                        {
                            foreignPeople.Controls.Add(UserCard(dr["Login"].ToString()));
                        }

                        foreignPeople.Controls.Add(new Panel()
                        {
                            Name      = "AddPanel",
                            Width     = 200,
                            Height    = 410,
                            BackColor = Supports.backBlack,
                            Padding   = new Padding(3),
                        });

                        (foreignPeople.Controls.Find("AddPanel", true).FirstOrDefault() as Panel).Controls.Add(new Button()
                        {
                            Name      = "AddPanelButton",
                            Image     = Resources.plus,
                            Dock      = DockStyle.Fill,
                            FlatStyle = FlatStyle.Flat,
                            ForeColor = Supports.textBlack,
                            BackColor = Supports.headGrey
                        });

                        (foreignPeople.Controls.Find("AddPanelButton", true).FirstOrDefault() as Button).Click += (s, arg) =>
                        {
                            string log = MessageBoxTi.Show("Логин", "Придумайте логин", HorizontalAlignment.Left);
                            while (log.Length > 15)
                            {
                                log = MessageBoxTi.Show("Логин", "Пользователь с таким ологином уже существует. Придумайте другой логин!", HorizontalAlignment.Left);
                                if (log == null || log == "")
                                {
                                    return;
                                }
                            }

                            if (dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(log)).Count() == 0 && log != "")
                            {
                                foreignPeople.Controls.Add(UserCard(log, true));
                                foreignPeople.Controls.SetChildIndex(foreignPeople.Controls.Find("AddPanel", false).FirstOrDefault(), foreignPeople.Controls.Count);
                                return;
                            }
                            else if (log == null || log == "")
                            {
                                return;
                            }
                            else
                            {
                                MessageBoxTi.Show("Такой логин уже существует");
                                return;
                            }
                        };


                        Supports.GangeGroup(this);
                    }
                    catch (Exception ex)
                    {
                        MessageBoxTi.Show("Admin.Enter " + ex.Message);
                    }
                };

                dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login");
                dataBase.ToDisplay("Appointment");
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Admin " + e.Message);
            }
        }
예제 #13
0
        /// <summary>
        /// Отчёт для 203 поста
        /// </summary>
        /// <param name="date">
        /// Дата, для которой нужно расчитать
        /// </param>
        /// <param name="days">
        /// Если не 0, то расчитывается для периода с той даты которая указана + это количество дней
        /// </param>
        public static void TillCalledFor203Report(DateTime date, int days = 0)
        {
            string path = null;

            System.Data.DataTable dt = dataBase.SimpleData("Loading WHERE [Спутник] = 'Кореасат-5' AND [Состояние] = 'true' AND [Диапазон] = 'Ku' AND [Примечание] LIKE '%AIS%'");
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter   = "Word files (*.docx)|*.docx";
                saveFileDialog1.Title    = days == 0 ? "Отчёт за " + date.ToShortDateString() : "Отчёт за период от " + date.ToShortDateString() + " до " + date.AddDays(days).ToShortDateString();
                saveFileDialog1.FileName = days == 0 ? date.ToShortDateString() + ".docx" : date.ToShortDateString() + " - " + date.AddDays(days).ToShortDateString() + ".docx";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = saveFileDialog1.FileName;
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.TillCalledFor203Report " + e.Message);
                return;
            }

            Thread t = new Thread(delegate()
            {
                try
                {
                    Supports.GetProfileForm().ChangeState();
                    object miss          = System.Reflection.Missing.Value;
                    word.Application app = null;

                    app = new word.Application();

                    Thread.Sleep(1000);
                    var doc = app.Documents.Add();

                    app.Visible = false;
                    Thread.Sleep(1000);
                    doc.PageSetup.TopMargin    = 80;
                    doc.PageSetup.BottomMargin = 50;
                    doc.PageSetup.LeftMargin   = 60;
                    doc.PageSetup.RightMargin  = 60;
                    var par             = doc.Paragraphs.Add();
                    par.Range.Text      = "Доклад 203 БП";
                    par.Alignment       = word.WdParagraphAlignment.wdAlignParagraphCenter;
                    par.Range.Font.Name = "Times New Roman";
                    par.Range.Font.Size = 12;
                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();

                    par.Range.Text = "1.    Статистика:";

                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();

                    string firDate = days == 0 ? (date.AddDays(-1) + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).ToString();
                    string secDate = days == 0 ? (date + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).AddDays(days).ToString();

                    par.Range.Text = "Включилось:" + dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = 'Кореасат-5' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1' AND [Диапазон] = 'Ku'").ToString();
                    par.Alignment  = word.WdParagraphAlignment.wdAlignParagraphLeft;
                    par            = doc.Paragraphs.Add();
                    par            = doc.Paragraphs.Add();

                    par.Range.Text = "Выключилось:" + dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = 'Кореасат-5' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0' AND [Диапазон] = 'Ku'").ToString();
                    par.Alignment  = word.WdParagraphAlignment.wdAlignParagraphLeft;
                    par            = doc.Paragraphs.Add();
                    par            = doc.Paragraphs.Add();

                    par.Range.Text = "2.    Номиналы включённых излучений:";
                    par            = doc.Paragraphs.Add();

                    word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 2, 4, DefaultTableBehavior: miss, AutoFitBehavior: miss);
                    fTable.Borders.InsideLineStyle  = word.WdLineStyle.wdLineStyleSingle;
                    fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;

                    fTable.Cell(1, 1).Range.Text = "Частота";
                    fTable.Cell(1, 2).Range.Text = "Стек протоков";
                    fTable.Cell(1, 3).Range.Text = "Время";
                    fTable.Cell(1, 4).Range.Text = "Примечание";

                    fTable.Range.Font.Size = 10;

                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();

                    fTable.Range.Bold = 0;

                    par.Range.Font.Bold = 0;
                    par            = doc.Paragraphs.Add();
                    par            = doc.Paragraphs.Add();
                    par.Range.Text = date.ToString("dd/MM/yyyy");
                    par.Alignment  = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    foreach (DataRow dr in dt.Rows.Cast <DataRow>())
                    {
                        fTable.Cell(fTable.Rows.Count, 1).Range.Text = dr["Частота"].ToString();
                        fTable.Cell(fTable.Rows.Count, 2).Range.Text = dr["СтекПрот"].ToString();
                        fTable.Cell(fTable.Rows.Count, 3).Range.Text = dr["ВремяДоб"].ToString();
                        fTable.Cell(fTable.Rows.Count, 4).Range.Text = dr["Примечание"].ToString();
                        fTable.Range.Rows.Add();
                    }

                    fTable.Range.Rows[fTable.Range.Rows.Count].Delete();

                    fTable.Range.Paragraphs.SpaceAfter = 0;

                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;
                    fTable.Columns[1].Width = 60;

                    fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow);
                    fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault);

                    doc.Close();

                    MessageBoxTi.Show("Отчёт готов");

                    if (app != null)
                    {
                        app.Quit();
                        Marshal.FinalReleaseComObject(app);

                        Thread.CurrentThread.Abort();
                    }
                    Thread.CurrentThread.Abort();
                }
                catch (Exception e)
                {
                    if (e.GetType() != typeof(ThreadAbortException))
                    {
                        MessageBoxTi.Show("Documentation.TillCalledFor203Report.Thread " + e.Message);
                    }
                    return;
                }
                finally
                {
                    Supports.GetProfileForm().ChangeState(true);
                }
            });

            t.Start();
        }
예제 #14
0
        /// <summary>
        /// Ежедневный отчёт для 202 поста, выгружается в Word
        /// </summary>
        /// <param name="date">
        /// Дата, для которой нужно расчитать
        /// </param>
        /// <param name="days">
        /// Если не 0, то расчитывается для периода с той даты которая указана + это количество дней
        /// </param>
        public static void Daily202Report(DateTime date, int days = 0)
        {
            string path = null;

            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter   = "Word files (*.docx)|*.docx";
                saveFileDialog1.Title    = days == 0 ? "Отчёт за " + date.ToShortDateString() : "Отчёт за период от " + date.ToShortDateString() + " до " + date.AddDays(days).ToShortDateString();
                saveFileDialog1.FileName = days == 0 ? date.ToShortDateString() + ".docx" : date.ToShortDateString() + " - " + date.AddDays(days).ToShortDateString() + ".docx";

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    path = saveFileDialog1.FileName;
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.Daily202Report " + e.Message);
                return;
            }

            Thread t = new Thread(delegate()
            {
                try
                {
                    Supports.GetProfileForm().ChangeState();

                    object miss          = System.Reflection.Missing.Value;
                    word.Application app = null;

                    System.Data.DataTable dt = dataBase.SimpleData("[dbo].[MainSettings] left join [dbo].[SatelliteList] ON [dbo].[MainSettings].[Content] = [dbo].[SatelliteList].[НаименованиеИСЗ] WHERE [dbo].[MainSettings].[What] = 'NS2DocumentationCheckedListBox' OR [dbo].[MainSettings].[What] = 'NS2DocumentationCheckedListBox1'");

                    if (dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").Count() == 0)
                    {
                        MessageBoxTi.Show("Упс, не выбран ни один спутник, сообщите НС о данной ошибке");
                        return;
                    }

                    app = new word.Application();

                    Thread.Sleep(1000);
                    var doc = app.Documents.Add();

                    app.Visible = false;
                    Thread.Sleep(1000);
                    doc.PageSetup.Orientation  = word.WdOrientation.wdOrientLandscape;
                    doc.PageSetup.TopMargin    = 80;
                    doc.PageSetup.BottomMargin = 50;
                    doc.PageSetup.LeftMargin   = 60;
                    doc.PageSetup.RightMargin  = 60;
                    var par             = doc.Paragraphs.Add();
                    par.Range.Text      = "Доклад 202 БП";
                    par.Alignment       = word.WdParagraphAlignment.wdAlignParagraphCenter;
                    par.Range.Font.Name = "Times New Roman";
                    par.Range.Font.Size = 12;
                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();
                    System.Data.DataTable MainSettings = dataBase.SimpleData("MainSettings");
                    if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0)
                    {
                        par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString();
                    }
                    else
                    {
                        par.Range.Text = "1.    Изменения в ВЧ загрузке ССС МО США ДСЦС и ВГС, ССС МО Великобритании СКАЙНЕТ:";
                    }
                    par.Alignment       = word.WdParagraphAlignment.wdAlignParagraphLeft;
                    par.Range.Font.Bold = 1;
                    par = doc.Paragraphs.Add();

                    word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 4, 13, DefaultTableBehavior: miss, AutoFitBehavior: miss);
                    fTable.Borders.InsideLineStyle  = word.WdLineStyle.wdLineStyleSingle;
                    fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;

                    fTable.Cell(1, 1).Merge(fTable.Cell(3, 1));
                    fTable.Cell(1, 2).Merge(fTable.Cell(3, 2));
                    fTable.Cell(1, 3).Merge(fTable.Cell(3, 3));
                    fTable.Cell(1, 4).Merge(fTable.Cell(1, 8));
                    fTable.Cell(1, 5).Merge(fTable.Cell(1, 9));
                    fTable.Cell(2, 4).Merge(fTable.Cell(3, 4));
                    fTable.Cell(2, 5).Merge(fTable.Cell(3, 5));
                    fTable.Cell(2, 6).Merge(fTable.Cell(2, 8));
                    fTable.Cell(2, 7).Merge(fTable.Cell(2, 8));
                    fTable.Cell(2, 8).Merge(fTable.Cell(2, 9));
                    fTable.Cell(2, 9).Merge(fTable.Cell(3, 13));

                    fTable.Cell(1, 1).Range.Text  = "Наименование ИСЗ";
                    fTable.Cell(1, 2).Range.Text  = "Межд. Номер";
                    fTable.Cell(1, 3).Range.Text  = "ПСТ";
                    fTable.Cell(1, 4).Range.Text  = "Излучений";
                    fTable.Cell(1, 5).Range.Text  = "Излучений по системам";
                    fTable.Cell(2, 4).Range.Text  = "вкл.";
                    fTable.Cell(2, 5).Range.Text  = "выкл.";
                    fTable.Cell(2, 6).Range.Text  = "Всего";
                    fTable.Cell(2, 7).Range.Text  = "ОКС";
                    fTable.Cell(2, 8).Range.Text  = "Вин-Т";
                    fTable.Cell(2, 9).Range.Text  = "ГБС";
                    fTable.Cell(3, 6).Range.Text  = "X";
                    fTable.Cell(3, 7).Range.Text  = "Ka";
                    fTable.Cell(3, 8).Range.Text  = "∑";
                    fTable.Cell(3, 9).Range.Text  = "ПДКП";
                    fTable.Cell(3, 10).Range.Text = "ДТС";
                    fTable.Cell(3, 11).Range.Text = "МДЧР";
                    fTable.Cell(3, 12).Range.Text = "МДВР";
                    fTable.Range.Font.Size        = 10;

                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();
                    if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox1").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0)
                    {
                        par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox1").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString();
                    }
                    else
                    {
                        par.Range.Text = "2.    Изменения в ВЧ загрузке геостационарных ИСЗ связи:";
                    }
                    par = doc.Paragraphs.Add();
                    word.Table sTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 3, 6, DefaultTableBehavior: miss, AutoFitBehavior: miss);

                    sTable.Cell(1, 1).Merge(sTable.Cell(2, 1));
                    sTable.Cell(1, 2).Merge(sTable.Cell(2, 2));
                    sTable.Cell(1, 3).Merge(sTable.Cell(2, 3));
                    sTable.Cell(1, 4).Merge(sTable.Cell(1, 6));

                    sTable.Cell(1, 1).Range.Text = "Наименование ИСЗ";
                    sTable.Cell(1, 2).Range.Text = "Межд. Номер";
                    sTable.Cell(1, 3).Range.Text = "ПСТ";
                    sTable.Cell(1, 4).Range.Text = "Излучений";
                    sTable.Cell(2, 4).Range.Text = "вкл.";
                    sTable.Cell(2, 5).Range.Text = "выкл.";
                    sTable.Cell(2, 6).Range.Text = "Всего";
                    sTable.Range.Font.Size       = 10;

                    sTable.Borders.InsideLineStyle  = word.WdLineStyle.wdLineStyleSingle;
                    sTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;
                    par = doc.Paragraphs.Add();
                    par = doc.Paragraphs.Add();
                    if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox2").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0)
                    {
                        par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox2").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString();
                    }
                    else
                    {
                        par.Range.Text = "3.    Причины изменений в ВЧ загрузке ССС МО США ВГС  не отмечено";
                    }
                    par                 = doc.Paragraphs.Add();
                    par                 = doc.Paragraphs.Add();
                    par.Range.Text      = "Оператор:  " + Profile.userName;
                    par.Range.Font.Bold = 0;
                    par                 = doc.Paragraphs.Add();
                    par                 = doc.Paragraphs.Add();
                    par.Range.Text      = date.ToString("dd/MM/yyyy");
                    par.Alignment       = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    var j             = 0;
                    string firDate    = days == 0 ? (date.AddDays(-1) + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).ToString();
                    string secDate    = days == 0 ? (date + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).AddDays(days).ToString();
                    fTable.Range.Bold = 0;
                    var n             = dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").Count();
                    foreach (DataRow dr in dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").OrderBy(x => x["НаименованиеИСЗ"]))
                    {
                        fTable.Cell(fTable.Rows.Count, 1).Range.Text  = dr["НаименованиеИСЗ"].ToString();
                        fTable.Cell(fTable.Rows.Count, 2).Range.Text  = dr["МеждНомер"].ToString();
                        fTable.Cell(fTable.Rows.Count, 3).Range.Text  = dr["ПСТ"].ToString();
                        fTable.Cell(fTable.Rows.Count, 4).Range.Text  = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1'").ToString();
                        fTable.Cell(fTable.Rows.Count, 5).Range.Text  = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0'").ToString();
                        fTable.Cell(fTable.Rows.Count, 6).Range.Text  = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'X' AND [Состояние] = 'true'").ToString();
                        fTable.Cell(fTable.Rows.Count, 7).Range.Text  = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true'").ToString();
                        fTable.Cell(fTable.Rows.Count, 8).Range.Text  = (Convert.ToInt32(fTable.Cell(fTable.Rows.Count, 6).Range.Text.Replace("\r\a", string.Empty)) + Convert.ToInt32(fTable.Cell(fTable.Rows.Count, 7).Range.Text.Replace("\r\a", string.Empty))).ToString();
                        fTable.Cell(fTable.Rows.Count, 9).Range.Text  = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] != 'WIN-T' AND [ТипДанных] = 'ПДКП' AND [Состояние] = 1").ToString();
                        fTable.Cell(fTable.Rows.Count, 10).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] = 'DTS' AND [Состояние] = 1").ToString();
                        fTable.Cell(fTable.Rows.Count, 11).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true' AND (([Тактовая] > '2729' AND [Тактовая] < '2731') OR ([Тактовая] > '3071' AND [Тактовая] < '3073'))").ToString();
                        fTable.Cell(fTable.Rows.Count, 12).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true' AND[ВидДоступа] = 'МДВР'").ToString();
                        fTable.Cell(fTable.Rows.Count, 13).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] = 'GBS'").ToString();
                        j++;

                        if (j < n)
                        {
                            fTable.Rows.Add();
                        }
                    }

                    j = 0;
                    n = dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").Count();
                    if (dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").Count() != 0)
                    {
                        foreach (DataRow dr in dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").OrderBy(x => x["НаименованиеИСЗ"]))
                        {
                            sTable.Cell(sTable.Rows.Count, 1).Range.Text = dr["НаименованиеИСЗ"].ToString();
                            sTable.Cell(sTable.Rows.Count, 2).Range.Text = dr["МеждНомер"].ToString();
                            sTable.Cell(sTable.Rows.Count, 3).Range.Text = dr["ПСТ"].ToString();
                            sTable.Cell(sTable.Rows.Count, 4).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X')").ToString();
                            sTable.Cell(sTable.Rows.Count, 5).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X')").ToString();
                            sTable.Cell(sTable.Rows.Count, 6).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Состояние] = 'true' AND ([Диапазон] = 'X' OR [Диапазон] = 'Ka')").ToString();
                            j++;
                            if (j < n)
                            {
                                sTable.Rows.Add();
                            }
                        }
                    }

                    fTable.Range.Paragraphs.SpaceAfter = 0;
                    sTable.Range.Paragraphs.SpaceAfter = 0;

                    fTable.Cell(1, 3).Width = 60;

                    for (var i = 4; i <= fTable.Rows.Count; i++)
                    {
                        fTable.Cell(i, 3).Width = 60;
                    }

                    fTable.Cell(1, 2).Width = 50;

                    for (var i = 4; i <= fTable.Rows.Count; i++)
                    {
                        fTable.Cell(i, 2).Width = 50;
                    }

                    fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow);
                    sTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow);

                    fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                    sTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;

                    app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault);

                    doc.Close();

                    MessageBoxTi.Show("Отчёт готов");

                    if (app != null)
                    {
                        app.Quit();
                        Marshal.FinalReleaseComObject(app);
                        Thread.CurrentThread.Abort();
                    }
                }
                catch (Exception e)
                {
                    if (e.GetType() != typeof(ThreadAbortException))
                    {
                        MessageBoxTi.Show("Documentation.Daily202Report.Thread " + e.Message);
                    }
                    return;
                }
                finally
                {
                    Supports.GetProfileForm().ChangeState(true);
                }
            });

            t.Start();
        }
예제 #15
0
            public MessageBox(string headText = null, int height = 150, int width = 500, bool headVasible = true)
            {
                try
                {
                    Padding         = new Padding(2);
                    BackColor       = Supports.headBlue;
                    TopMost         = true;
                    Width           = width;
                    Height          = height;
                    ShowIcon        = false;
                    StartPosition   = FormStartPosition.CenterScreen;
                    FormBorderStyle = FormBorderStyle.None;

                    Controls.Add(new Panel()
                    {
                        Name      = "Body",
                        Dock      = DockStyle.Fill,
                        BackColor = Supports.liteTextGray,
                    });

                    Controls.Add(new TransPanel()
                    {
                        Name      = "Head",
                        Visible   = headVasible,
                        Dock      = DockStyle.Top,
                        Height    = 27,
                        BackColor = Supports.headBlue,
                    });

                    Controls.Find("Head", false).FirstOrDefault().Controls.Add(new PictureBox()
                    {
                        Name      = "Closer",
                        Dock      = DockStyle.Right,
                        Width     = 35,
                        BackColor = Supports.Red,
                        Image     = Properties.Resources.x1tw,
                    });

                    Controls.Find("Head", false).FirstOrDefault().Controls.Add(new TransLabel()
                    {
                        Text      = headText,
                        Name      = "HeadTransLabel",
                        Dock      = DockStyle.Fill,
                        Padding   = new Padding(4, 6, 0, 0),
                        ForeColor = Supports.textWhite,
                    });

                    Controls.Find("Closer", true).FirstOrDefault().MouseUp += (s, e) =>
                    {
                        if (Controls.Find("Closer", true).FirstOrDefault().ClientRectangle.Contains(Controls.Find("Closer", true).FirstOrDefault().PointToClient(MousePosition)))
                        {
                            Dispose();
                        }
                        else
                        {
                            Controls.Find("Closer", true).FirstOrDefault().BackColor = Supports.Red;
                        }
                    };


                    Controls.Find("Closer", true).FirstOrDefault().MouseDown += (s, e) =>
                                                                                Controls.Find("Closer", true).FirstOrDefault().BackColor = Color.OrangeRed;

                    Controls.Find("Closer", true).FirstOrDefault().MouseEnter += (s, e) =>
                                                                                 Controls.Find("Closer", true).FirstOrDefault().BackColor = Color.IndianRed;

                    Controls.Find("Closer", true).FirstOrDefault().MouseLeave += (s, e) =>
                                                                                 Controls.Find("Closer", true).FirstOrDefault().BackColor = Supports.Red;
                }
                catch (Exception e)
                {
                    MessageBoxTi.Show("MessageBoxTi " + e.Message);
                }
            }
예제 #16
0
        public SSALoading()
        {
            Name = "tabPageSSALoading";
            Text = "ССА";

            SSALoadingControls();
            FillBottomControls();
            AddFreeSpase(Controls.Find("SSALoadingPanel0", false).FirstOrDefault());
            Supports.GangeGroup(this);

            dgv.DataBindingComplete += (s, e) =>
            {
                RefreshDGV();

                if (firstBind)
                {
                    return;
                }

                dgv.Columns["ID"].Visible        = false;
                dgv.Columns["Состояние"].Visible = false;

                firstBind = true;

                filter                  = new SQLRequestFilter(dgv, new string[] { "Примечание" });
                filter.Dock             = DockStyle.Left;
                filter.OnFilterChanged += (se, ar) => dataBase.ToDisplay("SSALoading WHERE [ВремяВкл] > '" + dtp.Value + "' AND [ВремяВкл] < '" + dtp.Value.AddDays(1) + "'" + filter.CurrentFilter, dataTableName: "SSALoading");
                Controls.Add(filter);
            };
            dgv.SelectionChanged += UpdateBottomControls;
            Enter += (s, e) =>
            {
                if (firstBind)
                {
                    dataBase.ToDisplay("SSALoading WHERE [ВремяВкл] > '" + dtp.Value + "' AND [ВремяВкл] < '" + dtp.Value.AddDays(1) + "'" + filter.CurrentFilter, dataTableName: "SSALoading", onlyAdapter: true);
                }
            };

            dgv.UserDeletedRow += (sender, e) => dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SSALoading"]);
            dgv.CellMouseClick += (sender, e) =>
            {
                if (dgv != null)
                {
                    if (e.Button == MouseButtons.Right)
                    {
                        Supports.MenuPanel(dgv, e.RowIndex, e.ColumnIndex, typeof(SSALoading));
                    }
                    if (e.Button == MouseButtons.Left)
                    {
                    }
                }
            };
            dgv.MouseMove += (s, e) =>
            {
                if (dgv.ContextMenuStrip != null)
                {
                    dgv.ContextMenuStrip.Dispose();
                }
            };

            dgv.KeyUp += (se, e) =>
            {
                if (e.KeyData == Keys.Left)
                {
                    dtp.Value = dtp.Value.AddDays(-1);
                }
                if (e.KeyData == Keys.Right)
                {
                    dtp.Value = dtp.Value.AddDays(1);
                }
                if (e.KeyData == Keys.Tab || e.KeyData == Keys.Enter)
                {
                    e.Handled = true;
                }
            };
            subtractTimeButton.Click += (sender, e) => dtp.Value = dtp.Value.AddDays(-1);
            addTimeButton.Click      += (sender, e) => dtp.Value = dtp.Value.AddDays(1);
            dtp.ValueChanged         += (se, e) =>
            {
                dataBase.ToDisplay("SSALoading WHERE [ВремяВкл] > '" + dtp.Value + "' AND [ВремяВкл] < '" + dtp.Value.AddDays(1) + "'" + filter.CurrentFilter, dataTableName: "SSALoading");
                filter.RefreshNodes(dgv);
            };

            editButton.Click += (s, e) =>
            {
                if (MessageBoxTi.Show("Редактировать?", "Редактирование излучения") == MessageResult.Yes && dgv.RowCount != 0)
                {
                    bool red = false;

                    if (!dgv.SelectedRows[0].Cells["Спутник"].Value.Equals(Спутник.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Спутник"] = Спутник.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Диапазон"].Value.Equals(Диапазон.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Диапазон"] = Диапазон.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Поляризация"].Value.Equals(Поляризация.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Поляризация"] = Поляризация.SelectedItem;
                        red = true;
                    }

                    if (!Convert.ToDecimal(dgv.SelectedRows[0].Cells["Частота"].Value).Equals(Частота.Value))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Частота"] = Частота.Value;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ВремяВкл"].Value.Equals(ВремяВкл.Value))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ВремяВкл"] = ВремяВкл.Value;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ВидДоступа"].Value.Equals(ВидДоступа.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ВидДоступа"] = ВидДоступа.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Модуляция"].Value.Equals(Модуляция.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Модуляция"] = Модуляция.SelectedItem;
                        red = true;
                    }

                    if (!Convert.ToDecimal(dgv.SelectedRows[0].Cells["Тактовая"].Value).Equals(Тактовая.Value))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Тактовая"] = Тактовая.Value;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["RПУК"].Value.Equals(RПУК.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["RПУК"] = RПУК.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ПУК"].Value.Equals(ПУК.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ПУК"] = ПУК.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Скремб"].Value.Equals(Скремб.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Скремб"] = Скремб.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["СистемаСвязи"].Value.Equals(СистемаСвязи.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["СистемаСвязи"] = СистемаСвязи.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Протоколы"].Value.Equals(Протоколы.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Протоколы"] = Протоколы.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ХарактерИнфо"].Value.Equals(ХарактерИнфо.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ХарактерИнфо"] = ХарактерИнфо.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Принадлежность"].Value.Equals(Принадлежность.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Принадлежность"] = Принадлежность.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ВидИсточника"].Value.Equals(ВидИсточника.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ВидИсточника"] = ВидИсточника.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ВидОбъекта"].Value.Equals(ВидОбъекта.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ВидОбъекта"] = ВидОбъекта.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ХарРаботы"].Value.Equals(ХарРаботы.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ХарРаботы"] = ХарРаботы.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ВозмСобытие"].Value.Equals(ВозмСобытие.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["ВозмСобытие"] = ВозмСобытие.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["СостДеятельности"].Value.Equals(СостДеятельности.SelectedItem))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["СостДеятельности"] = СостДеятельности.SelectedItem;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Примечание"].Value.ToString().Equals(Примечание.Text))
                    {
                        dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Примечание"] = Примечание.Text;
                        red = true;
                    }



                    if (red == false)
                    {
                        return;
                    }

                    dataBase.dataset.Tables["SSALoading"].Select().Where(x => x["ID"].Equals(dgv.SelectedRows[0].Cells["ID"].Value)).FirstOrDefault()["Пользователь"] = Profile.userName;

                    dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SSALoading"]);
                }
            };
            addButton.Click += (s, e) =>
            {
                if (MessageBoxTi.Show("Добавить?", "Добавление излучения") == MessageResult.Yes && dgv.RowCount != 0)
                {
                    DataRow p = (dgv.DataSource as DataTable).NewRow();

                    p["Спутник"]          = Supports.NullOrObjectIfEmpty(Спутник.SelectedItem);
                    p["Диапазон"]         = Supports.NullOrObjectIfEmpty(Диапазон.SelectedItem);
                    p["Поляризация"]      = Supports.NullOrObjectIfEmpty(Поляризация.SelectedItem);
                    p["Частота"]          = Частота.Value;
                    p["ВремяВкл"]         = ВремяВкл.Value;
                    p["Состояние"]        = MessageBoxTi.Show("Состояние", "Излучение включилось или выключилось", new string[] { "Включилось", "Выключилось" }) == MessageResult.Btn0 ? true : false;
                    p["ВидДоступа"]       = Supports.NullOrObjectIfEmpty(ВидДоступа.SelectedItem);
                    p["Модуляция"]        = Supports.NullOrObjectIfEmpty(Модуляция.SelectedItem);
                    p["Тактовая"]         = Тактовая.Value;
                    p["RПУК"]             = Supports.NullOrObjectIfEmpty(RПУК.SelectedItem);
                    p["ПУК"]              = Supports.NullOrObjectIfEmpty(ПУК.SelectedItem);
                    p["Скремб"]           = Supports.NullOrObjectIfEmpty(Скремб.SelectedItem);
                    p["СистемаСвязи"]     = Supports.NullOrObjectIfEmpty(СистемаСвязи.SelectedItem);
                    p["Протоколы"]        = Supports.NullOrObjectIfEmpty(Протоколы.SelectedItem);
                    p["ХарактерИнфо"]     = Supports.NullOrObjectIfEmpty(ХарактерИнфо.SelectedItem);
                    p["Принадлежность"]   = Supports.NullOrObjectIfEmpty(Принадлежность.SelectedItem);
                    p["ВидИсточника"]     = Supports.NullOrObjectIfEmpty(ВидИсточника.SelectedItem);
                    p["ВидОбъекта"]       = Supports.NullOrObjectIfEmpty(ВидОбъекта.SelectedItem);
                    p["ХарРаботы"]        = Supports.NullOrObjectIfEmpty(ХарРаботы.SelectedItem);
                    p["ВозмСобытие"]      = Supports.NullOrObjectIfEmpty(ВозмСобытие.SelectedItem);
                    p["СостДеятельности"] = Supports.NullOrObjectIfEmpty(СостДеятельности.SelectedItem);
                    p["Примечание"]       = Supports.NullOrObjectIfEmpty(Примечание.Text);
                    p["Пользователь"]     = Profile.userName;

                    decimal fer = Частота.Value;
                    dataBase.dataset.Tables["SSALoading"].Rows.Add(p);
                    dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SSALoading"]);
                    dataBase.ToDisplay("SSALoading WHERE [ВремяВкл] > '" + dtp.Value + "' AND [ВремяВкл] < '" + dtp.Value.AddDays(1) + "'" + filter.CurrentFilter, dataTableName: "SSALoading");

                    dgv.CurrentCell = dgv.Rows.Cast <DataGridViewRow>().Where(x => Convert.ToDecimal(x.Cells["Частота"].Value).Equals(fer) && x.Cells["Пользователь"].Value.ToString().Equals(Profile.userName)).FirstOrDefault().Cells["Частота"];
                }
            };

            dataBase.ToDisplay("SSALoading WHERE [ВремяВкл] > '" + dtp.Value + "' AND [ВремяВкл] < '" + dtp.Value.AddDays(1) + "'", dataTableName: "SSALoading");
            dgv.DataSource = dataBase.dataset.Tables["SSALoading"];
        }
예제 #17
0
        public Profile(string login, Image face = null)
        {
            try
            {
                string name = dataBase.ToCount("SELECT [Пользователь] FROM [Login] WHERE [Login].[Login] = '" + login + "'").ToString();
                userDepartment = Convert.ToInt32(dataBase.ToCount("SELECT [Department] FROM [Login] WHERE [Login].[Login] = '" + login + "'"));
                InitializeComponent();
                Name              = "Department2Base";
                Text              = name;
                userName          = name;
                userLogin         = login;
                pictureBox4.Image = face;
                prepare();
                Supports.GangeGroup(this);

                dataBase.ToUpdate(login, "Вошел в систему");

                new ToolTip().SetToolTip(pictureBox4, userName);

                Supports.GangeGroup(this);
                panel2.BackColor = Supports.headBlue;

                tabControl1.TabPages.Add(new SatelliteList());
                tabControl1.TabPages["tabPageSatelliteList"].Select();

                foreach (string appointment in dataBase.SimpleData("[Appointment] WHERE Login = '******'").Rows.Cast <DataRow>().Select(x => x["Occupation"].ToString()))
                {
                    switch (appointment)
                    {
                    case "ССА":
                        tabControl1.TabPages.Add(new SSALoading());
                        break;

                    case "Администратор":
                        tabControl1.TabPages.Add(new Admin());
                        break;

                    case "Графики":
                        графикToolStripMenuItem.Enabled = true;
                        break;

                    case "НС":
                        tabControl1.TabPages.Add(new NS2());
                        break;

                    case "Документация":
                        splitContainer1.Panel1.Controls.Add(new SidePanel("Документация")
                        {
                            Name = "Report"
                        });
                        splitContainer1.Panel1.Controls.Find("Report", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new RaportsForOperators());
                        break;
                    }
                }

                splitContainer1.Panel2.Controls.Add(new SidePanel("Документация")
                {
                    Name = "Chat"
                });
                splitContainer1.Panel2.Controls.Find("Chat", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new NoteForOperators());


                foreach (TabPage tp in tabControl1.TabPages)
                {
                    окнаToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem {
                        Name = tp.Name, Text = tp.Text
                    });
                }
                foreach (ToolStripItem tp in окнаToolStripMenuItem.DropDownItems)
                {
                    tp.Click += (s, e) =>
                    {
                        if (tabControl1.TabPages.IndexOfKey(tp.Name) != -1)
                        {
                            tabControl1.SelectTab(tp.Name);
                        }
                        else
                        {
                            switch (tp.Name)
                            {
                            case "tabPageSatelliteList":
                                tabControl1.TabPages.Add(new SatelliteList());
                                tabControl1.TabPages["tabPageSatelliteList"].Select();
                                break;

                            case "tabPageNS2":
                                tabControl1.TabPages.Add(new NS2());
                                tabControl1.TabPages["tabPageNS2"].Select();

                                break;

                            case "tabPageSSALoading":
                                tabControl1.TabPages.Add(new SSALoading());
                                tabControl1.TabPages["tabPageSSALoading"].Select();
                                break;
                            }
                        }
                    };
                }

                пенелиToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem {
                    Name = "Report", Text = "Отчёты"
                });
                пенелиToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem {
                    Name = "Chat", Text = "Записи пользователя"
                });

                foreach (ToolStripItem tp in пенелиToolStripMenuItem.DropDownItems)
                {
                    tp.Click += (s, e) =>
                    {
                        switch (tp.Name)
                        {
                        case "Report":
                            if (splitContainer1.Panel1.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Report").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer1.Panel1.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Report"
                                });
                                splitContainer1.Panel1.Controls.Find("Report", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new RaportsForOperators());
                            }
                            else if (splitContainer1.Panel2.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Report").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer1.Panel2.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Report"
                                });
                                splitContainer1.Panel2.Controls.Find("Report", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new RaportsForOperators());
                            }
                            else if (splitContainer2.Panel1.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Report").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer2.Panel1.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Report"
                                });
                                splitContainer2.Panel1.Controls.Find("Report", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new RaportsForOperators());
                            }
                            else if (splitContainer2.Panel2.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Report").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Report").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer2.Panel2.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Report"
                                });
                                splitContainer2.Panel2.Controls.Find("Report", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new RaportsForOperators());
                            }
                            break;

                        case "Chat":

                            if (splitContainer1.Panel1.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Chat").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer1.Panel1.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Chat"
                                });
                                splitContainer1.Panel1.Controls.Find("Chat", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new NoteForOperators());
                            }
                            else if (splitContainer1.Panel2.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Chat").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer1.Panel2.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Chat"
                                });
                                splitContainer1.Panel2.Controls.Find("Chat", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new NoteForOperators());
                            }
                            else if (splitContainer2.Panel1.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Chat").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer2.Panel1.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Chat"
                                });
                                splitContainer2.Panel1.Controls.Find("Chat", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new NoteForOperators());
                            }
                            else if (splitContainer2.Panel2.Controls.Count == 0)
                            {
                                if (!splitContainer1.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer1.Panel2.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel1.Controls.IndexOfKey("Chat").Equals(-1) || !splitContainer2.Panel2.Controls.IndexOfKey("Chat").Equals(-1))
                                {
                                    return;
                                }
                                splitContainer2.Panel2.Controls.Add(new SidePanel("Документация")
                                {
                                    Name = "Chat"
                                });
                                splitContainer2.Panel2.Controls.Find("Chat", false).FirstOrDefault().Controls.Find("Body", false).FirstOrDefault().Controls.Add(new NoteForOperators());
                            }
                            break;
                        }
                    };
                }

                Supports.WorkActivity.Start();
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Profile " + e.Message);
            }
        }
예제 #18
0
        public LoginForm()
        {
            try
            {
                Opacity = 0;
                InitializeComponent();
                imageLoca   = pictureBox2.Location;
                imageWidth  = pictureBox2.Width;
                label2.Text = Application.ProductVersion;

                t       = new Timer();
                t.Tick += (s, e) =>
                {
                    if ((Opacity += 0.05d) >= 1)
                    {
                        t.Stop();
                    }
                };
                t.Interval = 16;
                t.Start();


                ThisControl(this);

                pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;

                pictureBox1.BackColor = Color.Transparent;
                pictureBox1.Image     = button1.BackColor.R > 122 ? Resources.x1tb : Resources.x1tw;


                textBox1.TextChanged += (s, e) =>
                {
                    login = textBox1.Text;
                };

                textBox2.Enter += (s, e) =>
                {
                    if (login == textBox1.Text)
                    {
                        login = null;
                    }
                    else
                    {
                        return;
                    }


                    DataRow da = dataBase.SimpleData("Login").Select().Where(x => x["Login"].Equals(textBox1.Text)).FirstOrDefault();
                    if (da != null)
                    {
                        pictureBox2.Location = imageLoca;
                        pictureBox2.Width    = imageWidth;
                        pictureBox2.Height   = imageWidth;

                        if (da["Face"] != null)
                        {
                            pictureBox2.Image = (Bitmap)Image.FromStream(new MemoryStream((byte[])da["Face"]));
                        }
                        int picX = pictureBox2.Location.X;

                        int   picWidth = pictureBox2.Width;
                        Point po       = new Point(pictureBox2.Location.X, pictureBox2.Location.Y);

                        t = new Timer();
                        bool bigOrSmall = false;
                        int  i          = 0;


                        t.Tick += (se, a) =>
                        {
                            if (pictureBox2.Height >= 135 && pictureBox2.Width >= 135)
                            {
                                if (pictureBox2.Height > pictureBox2.Width)
                                {
                                    pictureBox2.Width += 4;
                                    po.X -= 2;
                                    pictureBox2.Location = po;
                                    return;
                                }


                                t.Stop();
                                button1.Enabled  = true;
                                textBox1.Enabled = true;
                                textBox2.Enabled = true;
                                return;
                            }

                            picWidth           += 2 + i;
                            pictureBox2.Height += 2 + i;

                            if (t.Interval > 1)
                            {
                                t.Interval -= 1;
                            }



                            if (!bigOrSmall)
                            {
                                pictureBox2.Width -= 4 + i;
                                po.X += 2 + i / 2;
                                pictureBox2.Location = po;
                                if (pictureBox2.Width == 0)
                                {
                                    bigOrSmall = true;
                                    pictureBox2.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                                    i += 2;
                                }
                            }
                            if (bigOrSmall)
                            {
                                pictureBox2.Width += 4 + i;
                                po.X -= 2 + i / 2;
                                pictureBox2.Location = po;
                                if (picWidth <= pictureBox2.Width)
                                {
                                    bigOrSmall = false;
                                }
                            }
                        };
                        t.Interval = 50;
                        t.Start();
                    }
                    else
                    {
                        pictureBox2.Image = null;
                    }
                };

                button1.Click += (s, e) =>
                {
                    t.Stop();
                    pictureBox2.Width    = 156;
                    pictureBox2.Height   = 156;
                    pictureBox2.Location = new Point(153, 133);

                    GetIn();
                };

                textBox2.KeyUp += (s, e) =>
                {
                    if (e.KeyCode == Keys.Enter && textBox2.Focused)
                    {
                        button1.PerformClick();
                    }
                };

                textBox1.KeyUp += (s, e) =>
                {
                    if (e.KeyCode == Keys.Enter && textBox1.Focused)
                    {
                        button1.PerformClick();
                        Focus();
                    }
                };

                pictureBox1.MouseEnter += (s, e) =>
                {
                    pictureBox1.BackColor = Supports.liteTextGray;
                };

                pictureBox1.MouseLeave += (s, e) =>
                {
                    pictureBox1.BackColor = Color.Transparent;
                };

                pictureBox1.Click += (s, e) =>
                {
                    Application.Exit();
                };

                pictureBox1.MouseDown += (s, e) =>
                {
                    pictureBox1.BackColor = Supports.headBlue;
                };

                pictureBox1.MouseUp += (s, e) =>
                {
                    pictureBox1.BackColor = Color.Transparent;
                };
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("LoginForm " + e.Message);
            }
        }
예제 #19
0
        public SidePanel(string name)
        {
            try
            {
                BackColor = Supports.backBlack;

                Dock = DockStyle.Fill;

                Controls.Add(new Panel()
                {
                    Name = "Body",
                    Dock = DockStyle.Fill,
                });

                (Controls.Find("Body", false).FirstOrDefault() as Panel).ControlAdded += (s, e) =>
                {
                    Supports.GangeGroup(this);
                };


                Controls.Add(new Panel()
                {
                    Name = "Head",

                    Dock      = DockStyle.Top,
                    Height    = 20,
                    BackColor = Supports.groupGrey,
                });

                (Controls.Find("Head", false).FirstOrDefault() as Panel).Controls.Add(new Label
                {
                    TextAlign = System.Drawing.ContentAlignment.BottomLeft,
                    Dock      = DockStyle.Fill,
                    AutoSize  = true,
                    Text      = name,
                });

                (Controls.Find("Head", false).FirstOrDefault() as Panel).Controls.Add(new PictureBox()
                {
                    Name     = "HeadCloser",
                    Dock     = DockStyle.Right,
                    Width    = 20,
                    Image    = Resources.ex,
                    SizeMode = PictureBoxSizeMode.StretchImage,
                    Padding  = new Padding(2),
                });

                (Controls.Find("HeadCloser", true).FirstOrDefault() as PictureBox).MouseEnter += (s, e) => (s as PictureBox).BackColor = Supports.LiteHeadBlue;

                (Controls.Find("HeadCloser", true).FirstOrDefault() as PictureBox).MouseLeave += (s, e) => (s as PictureBox).BackColor = Color.Transparent;

                (Controls.Find("HeadCloser", true).FirstOrDefault() as PictureBox).MouseDown += (s, e) =>
                {
                    if (MouseButtons.Left == e.Button)
                    {
                        (Controls.Find("HeadCloser", true).FirstOrDefault() as PictureBox).BackColor = Supports.darkBlue;
                    }
                };

                (Controls.Find("HeadCloser", true).FirstOrDefault() as PictureBox).MouseUp += (s, e) =>
                {
                    if (MouseButtons.Left == e.Button && (s as PictureBox).ClientRectangle.Contains((s as PictureBox).PointToClient(MousePosition)))
                    {
                        Dispose();
                    }
                };
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("SidePanel " + e.Message);
            }
        }
예제 #20
0
        /// <summary>
        /// Преобразование Всех дочерних элементов в соответствии с выбранной цветовой темой.
        /// </summary>
        /// <param name="parent">
        /// Верхний контрол, все дочерние элементы будут преобразованны
        /// </param>
        public static void GangeGroup(Control parent)
        {
            try
            {
                foreach (Control gro in parent.Controls)
                {
                    if (!gro.Name.Contains("NotDraw"))
                    {
                        if (gro.GetType() == typeof(GroupBox))
                        {
                            ((GroupBox)gro).BackColor = textGray;
                            ((GroupBox)gro).ForeColor = textWhite;
                            gro.Paint += (s, args) =>
                            {
                                GroupBox box = (GroupBox)s;
                                args.Graphics.Clear(headGrey);
                                args.Graphics.DrawString(box.Text, box.Font, new SolidBrush(textWhite), 0, 0);
                            };
                        }
                        else if (gro.GetType() == typeof(ListBox))
                        {
                            ((ListBox)gro).Dock        = DockStyle.Fill;
                            ((ListBox)gro).BackColor   = textGray;
                            ((ListBox)gro).BorderStyle = BorderStyle.FixedSingle;
                            ((ListBox)gro).ForeColor   = textWhite;
                            ((ListBox)gro).Enter      += (s, args) =>
                            {
                                ((ListBox)gro).BackColor = liteTextGray;
                            };
                            ((ListBox)gro).Leave += (s, args) =>
                            {
                                ((ListBox)gro).BackColor = textGray;
                            };
                            ((ListBox)gro).MouseEnter += (s, args) =>
                            {
                                ((ListBox)gro).BackColor = liteTextGray;
                            };
                            ((ListBox)gro).MouseLeave += (s, args) =>
                            {
                                ((ListBox)gro).BackColor = textGray;
                            };
                        }
                        else if (gro.GetType() == typeof(TextBox))
                        {
                            ((TextBox)gro).ScrollBars  = ScrollBars.Vertical;
                            ((TextBox)gro).BackColor   = textGray;
                            ((TextBox)gro).BorderStyle = BorderStyle.FixedSingle;
                            ((TextBox)gro).ForeColor   = textWhite;
                            ((TextBox)gro).Enter      += (s, args) =>
                            {
                                ((TextBox)gro).BackColor = liteTextGray;
                            };
                            ((TextBox)gro).Leave += (s, args) =>
                            {
                                ((TextBox)gro).BackColor = textGray;
                            };
                            ((TextBox)gro).MouseEnter += (s, args) =>
                            {
                                ((TextBox)gro).BackColor = liteTextGray;
                            };
                            ((TextBox)gro).MouseLeave += (s, args) =>
                            {
                                ((TextBox)gro).BackColor = textGray;
                            };
                        }
                        else if (gro.GetType() == typeof(TextBoxTi))
                        {
                            ((TextBoxTi)gro).ScrollBars  = ScrollBars.Vertical;
                            ((TextBoxTi)gro).BackColor   = textGray;
                            ((TextBoxTi)gro).BorderStyle = BorderStyle.FixedSingle;
                            ((TextBoxTi)gro).ForeColor   = textWhite;
                            ((TextBoxTi)gro).Enter      += (s, args) =>
                            {
                                ((TextBoxTi)gro).BackColor = liteTextGray;
                            };
                            ((TextBoxTi)gro).Leave += (s, args) =>
                            {
                                ((TextBoxTi)gro).BackColor = textGray;
                            };
                            ((TextBoxTi)gro).MouseEnter += (s, args) =>
                            {
                                ((TextBoxTi)gro).BackColor = liteTextGray;
                            };
                            ((TextBoxTi)gro).MouseLeave += (s, args) =>
                            {
                                ((TextBoxTi)gro).BackColor = textGray;
                            };
                        }
                        else if (gro.GetType() == typeof(ComboBox))
                        {
                            ((ComboBox)gro).BackColor     = textGray;
                            ((ComboBox)gro).ForeColor     = textWhite;
                            ((ComboBox)gro).FlatStyle     = FlatStyle.Flat;
                            ((ComboBox)gro).DropDownStyle = ComboBoxStyle.DropDownList;
                            ((ComboBox)gro).Enter        += (s, args) =>
                            {
                                ((ComboBox)gro).BackColor = liteTextGray;
                            };
                            ((ComboBox)gro).Leave += (s, args) =>
                            {
                                ((ComboBox)gro).BackColor = textGray;
                            };
                            ((ComboBox)gro).MouseEnter += (s, args) =>
                            {
                                ((ComboBox)gro).BackColor = liteTextGray;
                            };
                            ((ComboBox)gro).MouseLeave += (s, args) =>
                            {
                                ((ComboBox)gro).BackColor = textGray;
                            };
                        }
                        else if (gro.GetType() == typeof(Button))
                        {
                            ((Button)gro).ForeColor = textWhite;
                            ((Button)gro).BackColor = headGrey;
                            ((Button)gro).FlatStyle = FlatStyle.Flat;
                        }
                        else if (gro.GetType() == typeof(NumericUpDown))
                        {
                            ((NumericUpDown)gro).ForeColor = textWhite;
                            ((NumericUpDown)gro).BackColor = textBlack;
                        }
                        else if (gro.GetType() == typeof(DataGridView))
                        {
                            ((DataGridView)gro).AlternatingRowsDefaultCellStyle.BackColor = textBlack;
                            ((DataGridView)gro).AlternatingRowsDefaultCellStyle.ForeColor = textWhite;
                            ((DataGridView)gro).RowHeadersDefaultCellStyle.BackColor      = textBlack;
                            ((DataGridView)gro).RowHeadersDefaultCellStyle.ForeColor      = textWhite;
                            ((DataGridView)gro).DefaultCellStyle.BackColor = textGray;
                            ((DataGridView)gro).DefaultCellStyle.ForeColor = textWhite;
                            ((DataGridView)gro).GridColor = headBlue;
                            ((DataGridView)gro).ColumnHeadersDefaultCellStyle.BackColor = textBlack;
                            ((DataGridView)gro).ColumnHeadersDefaultCellStyle.ForeColor = textWhite;
                            ((DataGridView)gro).BackgroundColor = textBlack;
                            ((DataGridView)gro).MouseEnter     += (s, e) =>
                            {
                                ((DataGridView)gro).Focus();
                            };
                        }
                        else if (gro.GetType() == typeof(FlowLayoutPanel) || gro.GetType() == typeof(TableLayoutPanel) || gro.GetType() == typeof(Panel) || gro.GetType() == typeof(TransPanel))
                        {
                            gro.BackColor = headGrey;
                        }
                        else if (gro.GetType() == typeof(Label))
                        {
                            gro.ForeColor = textWhite;
                        }
                        else if (gro.GetType() == typeof(MenuStrip))
                        {
                            gro.ForeColor = textWhite;
                            gro.BackColor = headGrey;
                            //foreach(MenuItem mi in ((MenuStrip)gro).Items)
                            // {

                            // }
                        }
                        else if (gro.GetType() == typeof(CheckedListBox))
                        {
                            gro.ForeColor = textWhite;
                            gro.BackColor = headGrey;
                        }
                        else if (gro.GetType() == typeof(SplitContainer))
                        {
                            ((SplitContainer)gro).BackColor        = headGrey;
                            ((SplitContainer)gro).Panel1.BackColor = headGrey;
                            ((SplitContainer)gro).Panel2.BackColor = headGrey;
                        }
                        else if (gro.GetType() == typeof(CheckBox))
                        {
                            gro.BackColor = headGrey;
                            gro.ForeColor = textWhite;
                        }
                        else if (gro.GetType() == typeof(PictureBox))
                        {
                            gro.BackColor = headGrey;
                        }
                        else if (gro.GetType() == typeof(ToolStrip))
                        {
                            ((ToolStrip)gro).BackColor  = headGrey;
                            ((ToolStrip)gro).RenderMode = ToolStripRenderMode.System;
                            ((ToolStrip)gro).ForeColor  = textWhite;
                        }
                        else if (gro.GetType() == typeof(TreeView))
                        {
                            ((TreeView)gro).BackColor = headGrey;
                            ((TreeView)gro).ForeColor = textWhite;
                        }
                        else if (gro.GetType() == typeof(Splitter))
                        {
                            ((Splitter)gro).BackColor = headliteGrey;
                            ((Splitter)gro).Width     = 5;
                        }
                        else if (gro.GetType() == typeof(ChartTi))
                        {
                            ((ChartTi)gro).BackColor                            = headGrey;
                            ((ChartTi)gro).ForeColor                            = textBlack;
                            ((ChartTi)gro).chartArea.BackColor                  = headGrey;
                            ((ChartTi)gro).chartArea.AxisX.LineColor            = textBlack;
                            ((ChartTi)gro).chartArea.AxisY.LineColor            = textBlack;
                            ((ChartTi)gro).chartArea.AxisX.MajorGrid.LineColor  = textBlack;
                            ((ChartTi)gro).chartArea.AxisY.MajorGrid.LineColor  = textBlack;
                            ((ChartTi)gro).chartArea.AxisX.LabelStyle.ForeColor = textWhite;
                            ((ChartTi)gro).chartArea.AxisY.LabelStyle.ForeColor = textWhite;
                            ((ChartTi)gro).chartArea.AxisY.MajorGrid.LineColor  = textBlack;
                            ((ChartTi)gro).chartArea.AxisX.InterlacedColor      = textBlack;
                            ((ChartTi)gro).chartArea.AxisY.InterlacedColor      = textBlack;
                            ((ChartTi)gro).chartArea.AxisX.TitleForeColor       = textWhite;
                            ((ChartTi)gro).chartArea.AxisY.TitleForeColor       = textWhite;
                            ((ChartTi)gro).legend.BackColor                     = headGrey;
                            ((ChartTi)gro).legend.ForeColor                     = textWhite;
                            ((ChartTi)gro).legend.TitleForeColor                = textWhite;
                        }
                    }
                    else
                    {
                    }
                    GangeGroup(gro);
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("GangeGroup " + e.Message);
            }
        }
예제 #21
0
        /// <summary>
        /// Меню при щелчке правой клавишей на DGV
        /// </summary>
        /// <param name="dgv">
        /// Тот DGV, где нужно показать менюшку
        /// </param>
        /// <param name="rowIndex">
        /// Индекс строки
        /// </param>
        /// <param name="columnIndex">
        /// Индекс столбца
        /// </param>
        /// <param name="mode">
        /// Тип DGV
        /// </param>
        public static void MenuPanel(DataGridView dgv, int rowIndex, int columnIndex, Type mode, Loading sender = null)
        {
            try
            {
                ContextMenuStrip cm = new ContextMenuStrip();

                if (rowIndex != -1 && mode == typeof(SatelliteList))
                {
                    ToolStripMenuItem[] ToolStripMenuItem1 = { new ToolStripMenuItem("&Удалить"), new ToolStripMenuItem("&Переименовать"), new ToolStripMenuItem("&Скопировать текст") };

                    cm.Items.Add(ToolStripMenuItem1[0]);
                    cm.Items.Add(ToolStripMenuItem1[1]);
                    cm.Items.Add(ToolStripMenuItem1[2]);

                    dgv.ContextMenuStrip         = cm;
                    ToolStripMenuItem1[0].Click += (s1, eArg) =>
                    {
                        dgv.CurrentCell = dgv[columnIndex, rowIndex];
                        string n = dgv.Rows[rowIndex].Cells["НаименованиеИСЗ"].Value.ToString();
                        dgv.Rows.RemoveAt(rowIndex);
                        dataBase.ToDisplay("SatelliteList", onlyAdapter: true);
                        dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SatelliteList"]);
                        dataBase.ToUpdate(Profile.userLogin, "Удалил запись о спутнике \"" + n + "\"");
                    };
                    ToolStripMenuItem1[1].Click += (s1, eArg) =>
                    {
                        dgv.CurrentCell = dgv[columnIndex, rowIndex];
                        string log = MessageBoxTi.Show("Переименование спутника", "Введите новое название спутника", HorizontalAlignment.Left);
                        if (log == "" || log == null)
                        {
                            return;
                        }
                        while (dataBase.dataset.Tables["SatelliteList"].Rows.Cast <DataRow>().Where(x => x["НаименованиеИСЗ"].Equals(log)).Count() != 0)
                        {
                            log = MessageBoxTi.Show("Переименование спутника", "Такой спутник уже есть. Введите другое название спутника!", HorizontalAlignment.Left);
                            if (log == "" || log == null)
                            {
                                return;
                            }
                        }

                        if (log != "" || log == null)
                        {
                            dataBase.ToUpdate(Profile.userLogin, "Переименовал спутник " + dgv.SelectedRows[0].Cells["НаименованиеИСЗ"].Value.ToString() + " в " + log);
                            dataBase.SimpleRequest("UPDATE Loading SET Спутник = '" + log + "' WHERE Спутник = '" + dgv.SelectedRows[0].Cells["НаименованиеИСЗ"].Value.ToString() + "' UPDATE SatelliteList SET [НаименованиеИСЗ] = '" + log + "' WHERE ID = '" + dgv.SelectedRows[0].Cells["ID"].Value.ToString() + "'" + " UPDATE SSALoading SET [Спутник] = '" + log + "' WHERE [Спутник] = '" + dgv.SelectedRows[0].Cells["НаименованиеИСЗ"].Value.ToString() + "'");
                            dataBase.dataset.Tables["SatelliteList"].Clear();
                            dataBase.ToDisplay("SatelliteList", onlyAdapter: true);
                            dataBase.sqlAdapter.Fill(dataBase.dataset.Tables["SatelliteList"]);
                        }
                    };
                    ToolStripMenuItem1[2].Click += (s1, eArg) =>
                    {
                        string per = dgv[columnIndex, rowIndex].Value.ToString();
                        if (per != "")
                        {
                            Clipboard.SetText(per);
                        }
                    };
                    dgv.ContextMenuStrip.Show(dgv, new Point(Cursor.Position.X - dgv.PointToScreen(new Point(0, 0)).X, Cursor.Position.Y - dgv.PointToScreen(new Point(0, 0)).Y));
                }
                else if (rowIndex != -1 && mode == typeof(Loading))
                {
                    ToolStripMenuItem[] ToolStripMenuItem1 = { new ToolStripMenuItem("&Скопировать текст"), new ToolStripMenuItem("&Добавить новое значение"), new ToolStripMenuItem("&Удалить строку") };

                    cm.Items.Add(ToolStripMenuItem1[0]);
                    cm.Items.Add(ToolStripMenuItem1[1]);
                    cm.Items.Add(ToolStripMenuItem1[2]);

                    dgv.ContextMenuStrip = cm;

                    ToolStripMenuItem1[0].Click += (s1, eArg) =>
                    {
                        string per = dgv[columnIndex, rowIndex].Value.ToString();
                        if (per != "")
                        {
                            Clipboard.SetText(per);
                        }
                    };

                    ToolStripMenuItem1[1].Click += (s1, eArg) =>
                    {
                        if (MessageBoxTi.Show(textAlign: HorizontalAlignment.Center))
                        {
                            string newVal = MessageBoxTi.Show("Новое значение", "Введите новое значение", textAlign: HorizontalAlignment.Center);
                            if (newVal == null || newVal == "")
                            {
                                return;
                            }
                            else
                            {
                                dataBase.dataset.Tables["Loading " + sender.keys].Select().Where(x => x["ID"].Equals(dgv["ID", rowIndex].Value)).FirstOrDefault()[dgv.Columns[columnIndex].Name] = newVal;
                                dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Loading " + sender.keys]);
                                sender.FillBottomControls();
                                sender.AddFreeSpase(sender.mainPanel);
                                sender.UpdateBottomControls(sender, new EventArgs());
                                dgv.CurrentCell = dgv[columnIndex, rowIndex];
                            }
                        }
                    };

                    ToolStripMenuItem1[2].Click += (s1, eArg) =>
                    {
                        if (MessageBoxTi.Show("Удаление излучения", "Удалить данное излучение?") == MessageResult.Yes)
                        {
                            DataRow dr = dataBase.dataset.Tables["Loading " + sender.keys].Select().Where(x => x["ID"].Equals(dgv["ID", rowIndex].Value)).FirstOrDefault();

                            dataBase.SimpleRequest("INSERT INTO [dbo].[Deleted] ([Спутник],[Диапазон],[Поляризация],[Частота],[Состояние]," +
                                                   "[ОтношениеСШ],[ВидДоступа],[Модуляция],[Тактовая],[RПУК],[ПУК],[СкрембВнеш],[ПУККаскад],[СкрембВнутр]," +
                                                   "[Скорость],[СистемаСвязи],[Оборудование],[ДлинаКадра],[ТипДанных],[СтекПрот],[Примечание],[СостояниеАн],[Ценность]," +
                                                   "[Наблюдение],[ВремяДоб],[Пользователь],[Загруженность], [ВремяРедакт]) VALUES ('" + dr["Спутник"] + "', '" + dr["Диапазон"] + "', '" + dr["Поляризация"] + "', '" +
                                                   dr["Частота"] + "', '" + dr["Состояние"] + "', '" + dr["ОтношениеСШ"] + "', '" + dr["ВидДоступа"] + "', '" + dr["Модуляция"] + "', '" +
                                                   dr["Тактовая"].ToString().Replace(',', '.') + "', '" + dr["RПУК"] + "', '" + dr["ПУК"] + "', '" + dr["СкрембВнеш"] + "', '" +
                                                   dr["ПУККаскад"] + "', '" + dr["СкрембВнутр"] + "', '" + dr["Скорость"].ToString().Replace(',', '.') + "', '" + dr["СистемаСвязи"] + "', '" + dr["Оборудование"] + "', '" +
                                                   dr["ДлинаКадра"] + "', '" + dr["ТипДанных"] + "', '" + dr["СтекПрот"] + "', '" + dr["Примечание"] + "', '" + dr["СостояниеАн"] + "', '" +
                                                   dr["Ценность"] + "', '" + dr["Наблюдение"] + "', GETDATE(), '" + dr["Пользователь"] + "', '" + dr["Загруженность"] + "', '" + dr["ВремяРедакт"] + "')");

                            dataBase.ToUpdate(Profile.userLogin, "Удалил излучение спутника " + '"' + dr["Спутник"].ToString() + '"' + " с частотой: \"" + dr["Частота"].ToString() + "\". (запись перенесена в таблицу \"Удалённые\")");

                            dr.Delete();
                            dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Loading " + sender.keys]);
                            sender.checkSum = dataBase.CheckSum("Loading " + sender.keys);
                        }
                    };

                    dgv.ContextMenuStrip.Show(dgv, new Point(Cursor.Position.X - dgv.PointToScreen(new Point(0, 0)).X, Cursor.Position.Y - dgv.PointToScreen(new Point(0, 0)).Y));
                }
                else if (rowIndex != -1 && mode == typeof(SSALoading))
                {
                }
                else
                {
                    ToolStripMenuItem columns = new ToolStripMenuItem("&Столбцы");
                    columns.DropDown.AutoClose   = false;
                    columns.DropDown.MouseLeave += (s, e) => columns.DropDown.Close();

                    columns.DropDown.MouseLeave += (s, e) =>
                    {
                        columns.DropDown.Close();
                    };
                    ToolStripMenuItem[] ToolStripMenuItem2 = { new ToolStripMenuItem("&Свойства"), new ToolStripMenuItem("&Скрыть"), columns };
                    foreach (DataGridViewColumn col in dgv.Columns)
                    {
                        if (col.Name == "Частота")
                        {
                            continue;
                        }
                        columns.DropDownItems.Add("&" + col.Name);
                    }
                    foreach (ToolStripMenuItem it in columns.DropDownItems)
                    {
                        it.Click += (s, args) =>
                        {
                            if ((s as ToolStripMenuItem).Checked == true)
                            {
                                (s as ToolStripMenuItem).Checked = false;
                                dgv.Columns[(s as ToolStripMenuItem).Text.Replace("&", string.Empty)].Visible = false;
                                dataBase.SimpleRequest("INSERT INTO [MainSettings] ([Who], [What], [Content]) VALUES ('LoadingColumnsVisibility' , '" + Profile.userLogin + "', '" + (s as ToolStripMenuItem).Text.Replace("&", string.Empty) + "')");
                            }
                            else
                            {
                                (s as ToolStripMenuItem).Checked = true;
                                dgv.Columns[(s as ToolStripMenuItem).Text.Replace("&", string.Empty)].Visible = true;
                                dataBase.SimpleRequest("DELETE FROM [MainSettings] WHERE [Who] = 'LoadingColumnsVisibility' AND [What] = '" + Profile.userLogin + "' AND [Content] = '" + (s as ToolStripMenuItem).Text.Replace("&", string.Empty) + "'");
                            }
                        };
                        if (dgv.Columns[it.Text.Replace("&", string.Empty)].Visible == true)
                        {
                            it.Checked = true;
                        }
                    }

                    cm.Items.Add(ToolStripMenuItem2[0]);
                    cm.Items.Add(ToolStripMenuItem2[1]);
                    cm.Items.Add(ToolStripMenuItem2[2]);
                    ToolStripMenuItem2[1].Click += (s, e) =>
                    {
                        if (dgv.Columns[columnIndex].Name != "Частота")
                        {
                            dgv.Columns[columnIndex].Visible = false;
                            if (mode == typeof(Loading))
                            {
                                dataBase.SimpleRequest("INSERT INTO [MainSettings] ([Who], [What], [Content]) VALUES ('LoadingColumnsVisibility' , '" + Profile.userLogin + "', '" + dgv.Columns[columnIndex].Name + "')");
                            }
                        }
                    };

                    dgv.ContextMenuStrip = cm;
                    dgv.ContextMenuStrip.Show(dgv, new Point(Cursor.Position.X - dgv.PointToScreen(new Point(0, 0)).X, Cursor.Position.Y - dgv.PointToScreen(new Point(0, 0)).Y));
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("MenuPanel " + e.Message);
            }
        }
예제 #22
0
        public Panel UserCard(string Login, bool add = false)
        {
            try
            {
                Bitmap    im             = Resources.person;
                string    satellitesType = null;
                string    password       = null;
                string    name           = null;
                string    department     = null;
                int       rank           = -1;
                DataTable occupation     = null;

                if (!add)
                {
                    DataTable person = dataBase.SimpleData("[Login] WHERE [Login].[Login] = '" + Login + "'");
                    occupation     = dataBase.SimpleData("[Appointment] WHERE [Appointment].[Login] = '" + Login + "'");
                    satellitesType = person.Rows[0]["SatellitesType"].ToString();
                    password       = person.Rows[0]["Password"].ToString();
                    name           = person.Rows[0]["Пользователь"].ToString();
                    department     = person.Rows[0]["Department"].ToString();
                    im             = (Bitmap)Image.FromStream(new MemoryStream((byte[])person.Rows[0]["Face"]));
                    rank           = Convert.ToInt32(person.Rows[0]["Rank"]);
                }

                Panel myCard = new Panel()
                {
                    Name      = Login,
                    Width     = 200,
                    Height    = 500,
                    BackColor = Supports.backBlack,
                    Padding   = new Padding(3),
                };

                myCard.Controls.Add(new FlowLayoutPanel()
                {
                    Dock = DockStyle.Fill,

                    BorderStyle = BorderStyle.None,
                    Name        = "FlowLayoutPanel",
                    Width       = 200,
                    Height      = 300,
                    BackColor   = Supports.headGrey,
                });

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new PictureBox()
                {
                    Name     = "Picture",
                    Image    = im,
                    SizeMode = PictureBoxSizeMode.Zoom,
                    Width    = 200,
                    Height   = 100,
                });

                (myCard.Controls.Find("Picture", true).FirstOrDefault() as PictureBox).Click += (s, args) =>
                {
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.Filter = "Image files|*.jpeg;*.jpg;*.png;*.gif;*.bmp;*.tiff;*.tif;*.jfif;*.jpe;*.dib;";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        (myCard.Controls.Find("Picture", true).FirstOrDefault() as PictureBox).Image = Image.FromStream(openFileDialog1.OpenFile());
                    }
                };

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new GroupBox()
                {
                    Name   = "GroupBoxAppointment",
                    Text   = "Тип спутника",
                    Width  = 188,
                    Height = 40,
                });

                (myCard.Controls.Find("GroupBoxAppointment", true).FirstOrDefault() as GroupBox).Controls.Add(new ComboBox()
                {
                    Name          = "SatellitesTypeComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Panel()
                {
                    Name   = "PanelRankAndDep",
                    Width  = 188,
                    Height = 40,
                });

                (myCard.Controls.Find("PanelRankAndDep", true).FirstOrDefault() as Panel).Controls.Add(new GroupBox()
                {
                    Name  = "GroupBoxDepartment",
                    Text  = "Отдел",
                    Width = 60,
                    Dock  = DockStyle.Left
                });

                (myCard.Controls.Find("PanelRankAndDep", true).FirstOrDefault() as Panel).Controls.Add(new GroupBox()
                {
                    Name  = "GroupBoxRank",
                    Text  = "Звание",
                    Width = 126,
                    Dock  = DockStyle.Right
                });

                (myCard.Controls.Find("GroupBoxDepartment", true).FirstOrDefault() as GroupBox).Controls.Add(new ComboBox()
                {
                    Name          = "DepartmentComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });

                (myCard.Controls.Find("GroupBoxRank", true).FirstOrDefault() as GroupBox).Controls.Add(new ComboBox()
                {
                    Name          = "RankComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });

                for (var i = 1; i < 9; i++)
                {
                    (myCard.Controls.Find("DepartmentComboBox", true).FirstOrDefault() as ComboBox).Items.Add(i.ToString());
                }

                foreach (var ranks in Enum.GetValues(typeof(Supports.Ranks)))
                {
                    (myCard.Controls.Find("RankComboBox", true).FirstOrDefault() as ComboBox).Items.Add(ranks.ToString());
                }

                if (rank != -1)
                {
                    (myCard.Controls.Find("RankComboBox", true).FirstOrDefault() as ComboBox).SelectedItem = ((Supports.Ranks)rank).ToString();
                }

                if (department != null)
                {
                    (myCard.Controls.Find("DepartmentComboBox", true).FirstOrDefault() as ComboBox).SelectedItem = department;
                }
                else
                {
                    (myCard.Controls.Find("DepartmentComboBox", true).FirstOrDefault() as ComboBox).SelectedItem = 2;
                }

                (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).Items.Add("MIL");
                (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).Items.Add("CIV");
                (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).Items.Add("TWO");

                if (satellitesType != null)
                {
                    (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).SelectedItem = satellitesType;
                }
                else
                {
                    (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).SelectedIndex = 1;
                }

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new GroupBox()
                {
                    Name   = "GroupBoxName",
                    Text   = "Пользователь",
                    Width  = 188,
                    Height = 40,
                });

                (myCard.Controls.Find("GroupBoxName", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
                {
                    Name      = "Name",
                    Text      = name ?? "",
                    Dock      = DockStyle.Fill,
                    MaxLength = 50,
                });

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new GroupBox()
                {
                    Name   = "GroupBoxLogin",
                    Text   = "Логин",
                    Width  = 188,
                    Height = 40,
                });

                (myCard.Controls.Find("GroupBoxLogin", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
                {
                    Name      = "Login",
                    Text      = Login ?? "",
                    Dock      = DockStyle.Fill,
                    Enabled   = false,
                    MaxLength = 15
                });

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new GroupBox()
                {
                    Name   = "GroupBoxPassword",
                    Text   = "Пароль",
                    Width  = 188,
                    Height = 40,
                });

                (myCard.Controls.Find("GroupBoxPassword", true).FirstOrDefault() as GroupBox).Controls.Add(new TextBox()
                {
                    Name         = "Password",
                    Text         = password ?? "",
                    Dock         = DockStyle.Fill,
                    PasswordChar = '*',
                    MaxLength    = 15,
                });

                (myCard.Controls.Find("Password", true).FirstOrDefault() as TextBox).Click += (s, a) =>
                {
                    (myCard.Controls.Find("Password", true).FirstOrDefault() as TextBox).PasswordChar = '\0';
                };

                (myCard.Controls.Find("Password", true).FirstOrDefault() as TextBox).LostFocus += (s, a) =>
                {
                    (myCard.Controls.Find("Password", true).FirstOrDefault() as TextBox).PasswordChar = '*';
                };

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new GroupBox()
                {
                    Name   = "GroupBoxOccupation",
                    Text   = "Права",
                    Width  = 188,
                    Height = 120,
                });

                (myCard.Controls.Find("GroupBoxOccupation", true).FirstOrDefault() as GroupBox).Controls.Add(new CheckedListBox()
                {
                    Name        = "Occupation",
                    Dock        = DockStyle.Fill,
                    BorderStyle = BorderStyle.None,
                    BackColor   = Supports.headGrey,
                    ForeColor   = Supports.textWhite,
                });

                CheckedListBox OccupationCheckedListBox = (myCard.Controls.Find("Occupation", true).FirstOrDefault() as CheckedListBox);

                OccupationCheckedListBox.MouseLeave += (sen, arg) =>
                {
                    (sen as CheckedListBox).ClearSelected();
                };

                (myCard.Controls.Find("FlowLayoutPanel", true).FirstOrDefault() as FlowLayoutPanel).Controls.Add(new Panel()
                {
                    Name   = "Panel1",
                    Width  = 188,
                    Height = 20
                });

                (myCard.Controls.Find("Panel1", true).FirstOrDefault() as Panel).Controls.Add(new Button()
                {
                    Name      = "editButton",
                    Image     = add == false ? Resources.edit : Resources.add,
                    Dock      = DockStyle.Left,
                    Width     = 90,
                    FlatStyle = FlatStyle.Flat,
                    ForeColor = Supports.textBlack,
                });

                (myCard.Controls.Find("Panel1", true).FirstOrDefault() as Panel).Controls.Add(new Button()
                {
                    Name      = "eraseButton",
                    Image     = Resources.erase,
                    Dock      = DockStyle.Right,
                    Width     = 90,
                    FlatStyle = FlatStyle.Flat,
                    ForeColor = Supports.textBlack,
                });

                new ToolTip().SetToolTip((myCard.Controls.Find("editButton", true).FirstOrDefault() as Button), "Внести изменения");
                new ToolTip().SetToolTip((myCard.Controls.Find("eraseButton", true).FirstOrDefault() as Button), "Удалить пользователя");

                (myCard.Controls.Find("editButton", true).FirstOrDefault() as Button).Click += (sen, arg) =>
                {
                    if (MessageBoxTi.Show("Вы действительно хотите изменить данные пользователя?", "Редактирование") == MessageResult.Yes)
                    {
                        if (dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).Count() != 0)
                        {
                            List <object> delID = new List <object>();
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Password"]       = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Password", true).FirstOrDefault() as TextBox).Text;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Face"]           = sup.ImToBy(((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Picture", true).FirstOrDefault() as PictureBox).Image);
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Пользователь"]   = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Name", true).FirstOrDefault() as TextBox).Text;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Login"]          = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Login", true).FirstOrDefault() as TextBox).Text;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["SatellitesType"] = (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).SelectedItem;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Department"]     = (myCard.Controls.Find("DepartmentComboBox", true).FirstOrDefault() as ComboBox).SelectedItem;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Allowed"]        = 1;
                            dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault()["Rank"]           = (int)Enum.Parse(typeof(Supports.Ranks), (myCard.Controls.Find("RankComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString());


                            for (int j = 0; j < OccupationCheckedListBox.Items.Count; j++)
                            {
                                if (OccupationCheckedListBox.GetItemChecked(j) && dataBase.dataset.Tables["Appointment"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login)).Where(x => x["Occupation"].ToString().Equals(OccupationCheckedListBox.Items[j].ToString())).Count() == 0)
                                {
                                    DataRow dr = dataBase.dataset.Tables["Appointment"].NewRow();
                                    dr["Login"]      = Login;
                                    dr["Occupation"] = OccupationCheckedListBox.Items[j].ToString();
                                    dataBase.dataset.Tables["Appointment"].Rows.Add(dr);
                                }

                                if (!OccupationCheckedListBox.GetItemChecked(j) && dataBase.dataset.Tables["Appointment"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login)).Where(x => x["Occupation"].ToString().Equals(OccupationCheckedListBox.Items[j].ToString())).Count() != 0)
                                {
                                    delID.Add(dataBase.dataset.Tables["Appointment"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login)).Where(x => x["Occupation"].ToString().Equals(OccupationCheckedListBox.Items[j].ToString())).FirstOrDefault()[0]);
                                }
                            }

                            if (delID.Count != 0)
                            {
                                dataBase.ToDisplay("Appointment", onlyAdapter: true);
                            }

                            foreach (var del in delID)
                            {
                                string k = dataBase.dataset.Tables["Appointment"].Select().Where(x => x["Occupation"].ToString().Equals("Admin")).FirstOrDefault()[0].ToString();

                                if (dataBase.dataset.Tables["Appointment"].Select().Where(x => x["Occupation"].ToString().Equals("Admin")).Count() == 1 && dataBase.dataset.Tables["Appointment"].Select().Where(x => x["Occupation"].ToString().Equals("Admin")).FirstOrDefault()[0].ToString().Equals(del.ToString()))
                                {
                                    OccupationCheckedListBox.SetItemChecked(3, true);
                                    continue;
                                }
                                dataBase.dataset.Tables["Appointment"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login)).Where(x => x["ID"].Equals(del)).FirstOrDefault().Delete();
                                dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Appointment"]);
                                dataBase.dataset.Tables["Appointment"].Clear();
                                dataBase.sqlAdapter.Fill(dataBase.dataset.Tables["Appointment"]);
                            }

                            dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login", onlyAdapter: true);
                            dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Login"]);
                            dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login");
                            dataBase.ToDisplay("Appointment", onlyAdapter: true);
                            dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Appointment"]);
                            dataBase.ToDisplay("Appointment");

                            return;
                        }
                        else
                        {
                            DataRow dr1 = dataBase.dataset.Tables["Login"].NewRow();
                            dr1["Password"]       = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Password", true).FirstOrDefault() as TextBox).Text;
                            dr1["Face"]           = sup.ImToBy(((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Picture", true).FirstOrDefault() as PictureBox).Image);
                            dr1["Пользователь"]   = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Name", true).FirstOrDefault() as TextBox).Text;
                            dr1["Login"]          = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Login", true).FirstOrDefault() as TextBox).Text;
                            dr1["SatellitesType"] = (myCard.Controls.Find("SatellitesTypeComboBox", true).FirstOrDefault() as ComboBox).SelectedItem;
                            dr1["Department"]     = (myCard.Controls.Find("DepartmentComboBox", true).FirstOrDefault() as ComboBox).SelectedItem;
                            dr1["Allowed"]        = 1;
                            dr1["Rank"]           = (int)Enum.Parse(typeof(Supports.Ranks), (myCard.Controls.Find("RankComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString());

                            dataBase.dataset.Tables["Login"].Rows.Add(dr1);

                            for (int j = 0; j < OccupationCheckedListBox.Items.Count; j++)
                            {
                                if (OccupationCheckedListBox.GetItemChecked(j) && dataBase.dataset.Tables["Appointment"].Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login) && x["Occupation"].ToString().Equals(OccupationCheckedListBox.Items[j].ToString())).Count() == 0)
                                {
                                    DataRow dr = dataBase.dataset.Tables["Appointment"].NewRow();
                                    dr["Login"]      = ((Controls.Find(Login, true).FirstOrDefault() as Panel).Controls.Find("Login", true).FirstOrDefault() as TextBox).Text;
                                    dr["Occupation"] = OccupationCheckedListBox.Items[j].ToString();
                                    dataBase.dataset.Tables["Appointment"].Rows.Add(dr);
                                }
                            }

                            dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login", onlyAdapter: true);
                            dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Login"]);
                            dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login");
                            dataBase.ToDisplay("Appointment", onlyAdapter: true);
                            dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Appointment"]);
                            dataBase.ToDisplay("Appointment");


                            (myCard.Controls.Find("editButton", true).FirstOrDefault() as Button).Image = Resources.edit;
                            return;
                        }
                    }
                };

                (myCard.Controls.Find("eraseButton", true).FirstOrDefault() as Button).Click += (sen, arg) =>
                {
                    if (dataBase.dataset.Tables["Appointment"].Select().Where(x => x["Occupation"].ToString().Equals("Admin")).Count() == 1 && OccupationCheckedListBox.GetItemChecked(3))
                    {
                        MessageBoxTi.Show("Невозможно удалить последнего администратора");
                        return;
                    }
                    if (dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).Count() != 0)
                    {
                        dataBase.dataset.Tables["Login"].Select().Where(x => x["Login"].ToString().Equals(Login)).FirstOrDefault().Delete();
                        foreach (DataRow dr in dataBase.dataset.Tables["Appointment"].Select().Where(x => x["Login"].ToString().Equals(Login)))
                        {
                            dr.Delete();
                        }
                        dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login", onlyAdapter: true);
                        dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Login"]);
                        dataBase.ToDisplay("SELECT [ID], [Department], [Login], [Password], [Face], [Пользователь], [Rank], [Allowed], [SatellitesType] FROM Login", requestJustByMyself: true, dataTableName: "Login");
                        dataBase.ToDisplay("Appointment", onlyAdapter: true);
                        dataBase.sqlAdapter.Update(dataBase.dataset.Tables["Appointment"]);
                        dataBase.ToDisplay("Appointment");
                        Controls.Remove(Controls.Find(Login, true).FirstOrDefault());
                    }
                    else
                    {
                        Controls.Remove(Controls.Find(Login, true).FirstOrDefault());
                    }
                };

                OccupationCheckedListBox.Items.Add("Администратор");
                OccupationCheckedListBox.Items.Add("ССА");
                OccupationCheckedListBox.Items.Add("Графики");
                OccupationCheckedListBox.Items.Add("НС");
                OccupationCheckedListBox.Items.Add("Документация");

                if (occupation != null)
                {
                    for (int j = 0; j < OccupationCheckedListBox.Items.Count; j++)
                    {
                        if ((occupation.Rows.Cast <DataRow>().Where(x => x["Login"].ToString().Equals(Login)).Where(x => x["Occupation"].ToString().Equals(OccupationCheckedListBox.Items[j].ToString()))).ToList().Count != 0)
                        {
                            OccupationCheckedListBox.SetItemChecked(j, true);
                        }
                    }
                }

                Supports.GangeGroup(myCard);
                return(myCard);
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Admin.UserCard " + e.Message);
                return(null);
            }
        }
예제 #23
0
        public RaportsForOperators()
        {
            try
            {
                RowStyles.Clear();
                ColumnStyles.Clear();
                RowStyles.Add(new RowStyle(SizeType.Absolute, 120f));
                RowStyles.Add(new RowStyle(SizeType.Absolute, 120f));
                RowStyles.Add(new RowStyle(SizeType.Absolute, 200f));
                RowStyles.Add(new RowStyle(SizeType.Absolute, 150f));

                Dock = DockStyle.Fill;

                Controls.Add(new GroupBox()
                {
                    Name = "202ReportGroupBox",
                    Dock = DockStyle.Fill,
                    Text = "Отчёт для 202",
                }, 0, 0);

                Controls.Add(new GroupBox()
                {
                    Name = "203ReportGroupBox",
                    Dock = DockStyle.Fill,
                    Text = "Отчёт для 203",
                }, 0, 1);

                Controls.Add(new GroupBox()
                {
                    Name = "HistoryGroupBox",
                    Dock = DockStyle.Fill,
                    Text = "История включений",
                }, 0, 2);

                Controls.Add(new Panel()
                {
                    Dock = DockStyle.Fill,
                }, 0, 3);

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new Panel()
                {
                    Name   = "HistoryPanel",
                    Dock   = DockStyle.Top,
                    Text   = "Получить историю",
                    Height = 25,
                });

                Controls.Find("HistoryPanel", true).FirstOrDefault().Controls.Add(new Button()
                {
                    Name = "HistoryButton",
                    Dock = DockStyle.Fill,
                    Text = "Получить историю",
                });

                Controls.Find("HistoryPanel", true).FirstOrDefault().Controls.Add(new Button()
                {
                    Name  = "HistoryButton1",
                    Dock  = DockStyle.Right,
                    Text  = "Получить min/max",
                    Width = 120,
                });

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                {
                    Name = "HistoryDateTimePicker2",
                    Dock = DockStyle.Top,
                });

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                {
                    Top  = 5,
                    Name = "HistoryDateTimePicker1",
                    Dock = DockStyle.Top,
                });

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new GroupBox()
                {
                    Name   = "HistoryPolarizationGroupBox",
                    Dock   = DockStyle.Top,
                    Text   = "Поляризация",
                    Height = 37,
                });

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new GroupBox()
                {
                    Name   = "HistoryBeamGroupBox",
                    Dock   = DockStyle.Top,
                    Text   = "Диапазон",
                    Height = 37,
                });

                Controls.Find("HistoryGroupBox", true).FirstOrDefault().Controls.Add(new GroupBox()
                {
                    Name   = "HistorySatelliteGroupBox",
                    Dock   = DockStyle.Top,
                    Text   = "Спутник",
                    Height = 37,
                });

                Controls.Find("HistoryPolarizationGroupBox", true).FirstOrDefault().Controls.Add(new ComboBox()
                {
                    Name          = "HistoryPolarizationComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });
                Controls.Find("HistoryBeamGroupBox", true).FirstOrDefault().Controls.Add(new ComboBox()
                {
                    Name          = "HistoryBeamComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });
                Controls.Find("HistorySatelliteGroupBox", true).FirstOrDefault().Controls.Add(new ComboBox()
                {
                    Name          = "HistorySatelliteComboBox",
                    Dock          = DockStyle.Fill,
                    DropDownStyle = ComboBoxStyle.DropDownList,
                });


                (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).Items.Add("L");
                (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).Items.Add("R");
                (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).Items.Add("V");
                (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).Items.Add("H");

                foreach (string be in dataBase.SimpleData("FrequencyBand").Rows.Cast <DataRow>().Select(x => x["Наименование диапазона"].ToString()).OrderBy(x => x).ToList())
                {
                    (Controls.Find("HistoryBeamComboBox", true).FirstOrDefault() as ComboBox).Items.Add(be);
                }

                foreach (string be in dataBase.SimpleData("SatelliteList").Rows.Cast <DataRow>().Select(x => x["НаименованиеИСЗ"].ToString()).OrderBy(x => x).ToList())
                {
                    (Controls.Find("HistorySatelliteComboBox", true).FirstOrDefault() as ComboBox).Items.Add(be);
                }


                (Controls.Find("HistoryButton", true).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    Documentation.WorkingHistory((Controls.Find("HistorySatelliteComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                 (Controls.Find("HistoryBeamComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                 (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                 (Controls.Find("HistoryDateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value,
                                                 Convert.ToInt32(((Controls.Find("HistoryDateTimePicker2", true).FirstOrDefault() as DateTimePicker).Value -
                                                                  (Controls.Find("HistoryDateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value).TotalDays));
                };

                (Controls.Find("HistoryButton1", true).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    Documentation.WorkingHistoryMinMax((Controls.Find("HistorySatelliteComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                       (Controls.Find("HistoryBeamComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                       (Controls.Find("HistoryPolarizationComboBox", true).FirstOrDefault() as ComboBox).SelectedItem.ToString(),
                                                       (Controls.Find("HistoryDateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value,
                                                       (Controls.Find("HistoryDateTimePicker2", true).FirstOrDefault() as DateTimePicker).Value);
                };

                Controls.Find("202ReportGroupBox", true).FirstOrDefault().Controls.Add(new FlowLayoutPanel()
                {
                    Name = "202ReportGroupBoxFlowLayoutPanel",
                    Dock = DockStyle.Fill,
                });

                Controls.Find("202ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new TableLayoutPanel()
                {
                    Name   = "DailyRaport202TableLayoutPanel",
                    Height = 30,
                });

                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 90f));
                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10f));

                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new DateTimePicker()
                {
                    Name = "DailyRaport202DateTimePicker1",
                }, 0, 0);

                (Controls.Find("DailyRaport202TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new CheckBox()
                {
                    Name = "DailyRaport202CheckBox",
                }, 1, 0);

                Controls.Find("202ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                {
                    Name    = "DailyRaport202DateTimePicker2",
                    Enabled = false,
                });

                (Controls.Find("DailyRaport202CheckBox", true).FirstOrDefault() as CheckBox).CheckedChanged += (s, e) =>
                {
                    try
                    {
                        if ((Controls.Find("DailyRaport202CheckBox", true).FirstOrDefault() as CheckBox).Checked)
                        {
                            (Controls.Find("DailyRaport202DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Enabled = true;
                            (Controls.Find("TodayReport", true).FirstOrDefault() as Button).Text = "Отчёт за период";
                        }
                        else
                        {
                            (Controls.Find("DailyRaport202DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Enabled = false;
                            (Controls.Find("TodayReport", true).FirstOrDefault() as Button).Text = "Ежедневный отчёт";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBoxTi.Show("RaportsForOperators.DailyRaport202CheckBox " + ex.Message);
                    }
                };

                Controls.Find("202ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new Button()
                {
                    Name      = "TodayReport",
                    Text      = "Ежедневный отчёт",
                    AutoSize  = true,
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Supports.headGrey,
                    Width     = 200,
                });

                (Controls.Find("TodayReport", true).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    try
                    {
                        if (!(Controls.Find("DailyRaport202CheckBox", true).FirstOrDefault() as CheckBox).Checked)
                        {
                            Documentation.Daily202Report((Controls.Find("DailyRaport202DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date);
                        }
                        else
                        {
                            int days = Convert.ToInt32(((Controls.Find("DailyRaport202DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Value.Date - (Controls.Find("DailyRaport202DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date).TotalDays);
                            if (days < 0)
                            {
                                MessageBoxTi.Show("Неверно введён период");
                                return;
                            }
                            Documentation.Daily202Report((Controls.Find("DailyRaport202DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date, days);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBoxTi.Show("RaportsForOperators.TodayReport " + ex.Message);
                    }
                };

                Controls.Find("203ReportGroupBox", true).FirstOrDefault().Controls.Add(new FlowLayoutPanel()
                {
                    Name = "203ReportGroupBoxFlowLayoutPanel",
                    Dock = DockStyle.Fill,
                });

                Controls.Find("203ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new TableLayoutPanel()
                {
                    Name   = "Raport203TableLayoutPanel",
                    Height = 30,
                });

                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Clear();
                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).RowStyles.Clear();
                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 90f));
                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10f));

                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new DateTimePicker()
                {
                    Name = "Raport203DateTimePicker1",
                }, 0, 0);

                (Controls.Find("Raport203TableLayoutPanel", true).FirstOrDefault() as TableLayoutPanel).Controls.Add(new CheckBox()
                {
                    Name = "Raport203CheckBox",
                }, 1, 0);

                Controls.Find("203ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                {
                    Name    = "Raport203DateTimePicker2",
                    Enabled = false,
                });

                (Controls.Find("Raport203CheckBox", true).FirstOrDefault() as CheckBox).CheckedChanged += (s, e) =>
                {
                    try
                    {
                        if ((Controls.Find("Raport203CheckBox", true).FirstOrDefault() as CheckBox).Checked)
                        {
                            (Controls.Find("Raport203DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Enabled = true;
                            (Controls.Find("Report203", true).FirstOrDefault() as Button).Text = "Отчёт за период";
                        }
                        else
                        {
                            (Controls.Find("Raport203DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Enabled = false;
                            (Controls.Find("Report203", true).FirstOrDefault() as Button).Text = "Отчёт";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBoxTi.Show("RaportsForOperators.Raport203CheckBox " + ex.Message);
                    }
                };

                Controls.Find("203ReportGroupBoxFlowLayoutPanel", true).FirstOrDefault().Controls.Add(new Button()
                {
                    Name      = "Report203",
                    Text      = "Отчёт",
                    AutoSize  = true,
                    FlatStyle = FlatStyle.Flat,
                    BackColor = Supports.headGrey,
                    Width     = 200,
                });

                (Controls.Find("Report203", true).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    try
                    {
                        if (!(Controls.Find("Raport203CheckBox", true).FirstOrDefault() as CheckBox).Checked)
                        {
                            Documentation.TillCalledFor203Report((Controls.Find("Raport203DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date);
                        }
                        else
                        {
                            int days = Convert.ToInt32(((Controls.Find("Raport203DateTimePicker2", true).FirstOrDefault() as DateTimePicker).Value.Date - (Controls.Find("Raport203DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date).TotalDays);
                            if (days < 0)
                            {
                                MessageBoxTi.Show("Неверно введён период");
                                return;
                            }
                            Documentation.TillCalledFor203Report((Controls.Find("Raport203DateTimePicker1", true).FirstOrDefault() as DateTimePicker).Value.Date, days);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBoxTi.Show("RaportsForOperators.Report203Button " + ex.Message);
                    }
                };
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("RaportsForOperators " + e.Message);
            }
        }
예제 #24
0
        public SQLRequestFilter(DataGridView dataGridView, string[] columnsToFilter)
        {
            try
            {
                if (dataGridView == null)
                {
                    return;
                }

                columnsFilter = columnsToFilter;
                Width         = 200;
                lastWidth     = Width;
                Name          = "filterPanel";
                Padding       = new Padding(0, 0, 5, 0);

                Controls.Add(new TreeView()
                {
                    CheckBoxes = true,
                    Dock       = DockStyle.Fill,
                    Scrollable = true,
                    Name       = "filterTreeView",
                });

                Controls.Add(new Button()
                {
                    Dock  = DockStyle.Top,
                    Width = 37,
                    Name  = "filterButton",
                    Text  = "Сбросить все фильтры",
                });

                Controls.Add(new Panel()
                {
                    Dock       = DockStyle.Bottom,
                    Height     = 600,
                    Name       = "Panel",
                    AutoScroll = true,
                });

                Controls.Add(new Button()
                {
                    Dock  = DockStyle.Right,
                    Name  = "hideFilterButton",
                    Width = 15,
                    Image = Resources.left,
                });

                (Controls.Find("hideFilterButton", false).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    if (Controls.Find("filterTreeView", false).FirstOrDefault().Visible)
                    {
                        Controls.Find("filterTreeView", false).FirstOrDefault().Visible = false;
                        Controls.Find("filterButton", false).FirstOrDefault().Visible   = false;
                        Controls.Find("Panel", false).FirstOrDefault().Visible          = false;
                        lastWidth = Width;
                        Width     = 20;
                        (Controls.Find("hideFilterButton", false).FirstOrDefault() as Button).Image = Resources.right;
                        if (Parent.Controls.Find("filterSplitter", false).Count() != 0)
                        {
                            (Parent.Controls.Find("filterSplitter", false).FirstOrDefault() as Splitter).Visible = false;
                        }
                    }
                    else
                    {
                        Controls.Find("filterTreeView", false).FirstOrDefault().Visible = true;
                        Controls.Find("filterButton", false).FirstOrDefault().Visible   = true;
                        Controls.Find("Panel", false).FirstOrDefault().Visible          = true;
                        Width = lastWidth;
                        (Controls.Find("hideFilterButton", false).FirstOrDefault() as Button).Image = Resources.left;
                        if (Parent.Controls.Find("filterSplitter", false).Count() != 0)
                        {
                            (Parent.Controls.Find("filterSplitter", false).FirstOrDefault() as Splitter).Visible = true;
                        }
                    }
                };

                (Controls.Find("filterButton", false).FirstOrDefault() as Button).Click += (s, e) =>
                {
                    resetOn = true;
                    ResetAllNodes();
                    ResetAllText(this);
                    textBoxesFilter            = null;
                    checkBoxesFilter           = null;
                    rangeTextBoxesFilter       = null;
                    rangeDateTimePickersFilter = null;
                    OnFilterChanged?.Invoke(this, new EventArgs());
                    resetOn = false;
                };

                tree = (Controls.Find("filterTreeView", false).FirstOrDefault() as TreeView);

                tree.BeforeCheck += (s, e) =>
                {
                    if (e.Node.Parent == null)
                    {
                        e.Cancel = true;
                    }
                };

                tree.AfterCheck += (s, e) =>
                {
                    if (resetOn)
                    {
                        return;
                    }

                    if (e.Node.Parent != null)
                    {
                        bool checkedCol = false;
                        checkBoxesFilter = null;
                        foreach (TreeNode node in tree.Nodes)
                        {
                            foreach (TreeNode nod in node.Nodes)
                            {
                                if (nod.Checked)
                                {
                                    checkBoxesFilter += '(';
                                    checkedCol        = true;
                                    break;
                                }
                            }
                            if (checkedCol)
                            {
                                foreach (TreeNode nod in node.Nodes)
                                {
                                    if (nod.Checked)
                                    {
                                        checkBoxesFilter += "[" + node.Name + "] = '" + nod.Name + "' OR ";
                                    }
                                }
                                checkedCol        = false;
                                checkBoxesFilter  = checkBoxesFilter.Remove(checkBoxesFilter.Length - 4, 4);
                                checkBoxesFilter += ") AND ";
                            }
                        }
                        if (checkBoxesFilter != null)
                        {
                            checkBoxesFilter  = checkBoxesFilter.Remove(checkBoxesFilter.Length - 6, 6);
                            checkBoxesFilter += ')';
                        }


                        OnFilterChanged?.Invoke(this, new EventArgs());
                    }
                };


                foreach (DataGridViewColumn col in dataGridView.Columns)
                {
                    if (col.Name == "ID")
                    {
                        continue;
                    }
                    if ((col.ValueType == typeof(string) || col.ValueType == typeof(bool)) && !columnsFilter.Contains(col.Name))
                    {
                        List <string> distinctConditions = dataGridView.Rows.Cast <DataGridViewRow>().Select(x => x.Cells[col.Name].Value.ToString()).Where(x => x != "").OrderBy(x => x).Distinct().ToList();

                        Type k = col.ValueType;

                        if (distinctConditions.Count < 2)
                        {
                            continue;
                        }

                        tree.Nodes.Add(col.Name, col.HeaderText);

                        foreach (string str in distinctConditions)
                        {
                            if (col.ValueType != typeof(bool))
                            {
                                tree.Nodes.Find(col.Name, false).FirstOrDefault().Nodes.Add(str.ToString(), str.ToString());
                            }
                            else
                            {
                                if (str == "True")
                                {
                                    tree.Nodes.Find(col.Name, false).FirstOrDefault().Nodes.Add(str.ToString(), "Вкл.");
                                }
                                else
                                {
                                    tree.Nodes.Find(col.Name, false).FirstOrDefault().Nodes.Add(str.ToString(), "Выкл.");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (col.ValueType == typeof(string))
                        {
                            Controls.Find("Panel", true).FirstOrDefault().Controls.Add(new GroupBox()
                            {
                                Text   = col.Name,
                                Name   = col.Name + "GroupBox",
                                Dock   = DockStyle.Top,
                                Height = 37,
                            });

                            Controls.Find(col.Name + "GroupBox", true).FirstOrDefault().Controls.Add(new TextBox()
                            {
                                Dock = DockStyle.Fill,
                                Name = col.Name + "TextBox",
                            });
                            (Controls.Find(col.Name + "TextBox", true).FirstOrDefault() as TextBox).TextChanged += (s, e) =>
                            {
                                if (resetOn)
                                {
                                    return;
                                }


                                textBoxesFilter = null;
                                foreach (string text in columnsToFilter)
                                {
                                    if ((Controls.Find(text + "TextBox", true).FirstOrDefault() as TextBox).Text == "")
                                    {
                                        continue;
                                    }
                                    textBoxesFilter += '[' + text + "] LIKE '%" + (Controls.Find(text + "TextBox", true).FirstOrDefault() as TextBox).Text + "%' AND ";
                                }
                                if (textBoxesFilter != null)
                                {
                                    textBoxesFilter = textBoxesFilter.Remove(textBoxesFilter.Length - 4, 4);
                                }

                                OnFilterChanged?.Invoke(this, new EventArgs());
                            };
                        }
                        else if (col.ValueType == typeof(DateTime))
                        {
                            rangeDateTimePickers.Add(col.Name);
                            Controls.Find("Panel", true).FirstOrDefault().Controls.Add(new GroupBox()
                            {
                                Text   = col.Name,
                                Name   = col.Name + "GroupBox",
                                Dock   = DockStyle.Top,
                                Height = 65,
                            });

                            Controls.Find(col.Name + "GroupBox", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                            {
                                Name = col.Name + "1",
                                Dock = DockStyle.Top,
                            });

                            Controls.Find(col.Name + "GroupBox", true).FirstOrDefault().Controls.Add(new DateTimePicker()
                            {
                                Name = col.Name + "2",
                                Dock = DockStyle.Bottom,
                            });

                            Controls.Find(col.Name + "1", true).FirstOrDefault().TextChanged += (s, e) =>
                            {
                                if (resetOn)
                                {
                                    return;
                                }

                                string old = rangeDateTimePickersFilter;
                                rangeDateTimePickersFilter = null;



                                foreach (string text in rangeDateTimePickers)
                                {
                                    if ((Controls.Find(text + "1", true).FirstOrDefault() as DateTimePicker).Value >= (Controls.Find(text + "2", true).FirstOrDefault() as DateTimePicker).Value)
                                    {
                                        continue;
                                    }

                                    rangeDateTimePickersFilter += "([" + text + "] > '" + (Controls.Find(text + "1", true).FirstOrDefault() as DateTimePicker).Value.Date + "' AND [" + text + "] < '" + (Controls.Find(text + "2", true).FirstOrDefault() as DateTimePicker).Value.Date + "') AND ";
                                }
                                if (rangeDateTimePickersFilter != null)
                                {
                                    rangeDateTimePickersFilter = rangeDateTimePickersFilter.Remove(rangeDateTimePickersFilter.Length - 4, 4);
                                }

                                if (rangeDateTimePickersFilter != null)
                                {
                                    if (!rangeDateTimePickersFilter.Equals(old))
                                    {
                                        OnFilterChanged?.Invoke(this, new EventArgs());
                                    }
                                }
                            };

                            Controls.Find(col.Name + "2", true).FirstOrDefault().TextChanged += (s, e) =>
                            {
                                if (resetOn)
                                {
                                    return;
                                }

                                string old = rangeDateTimePickersFilter;
                                rangeDateTimePickersFilter = null;

                                foreach (string text in rangeDateTimePickers)
                                {
                                    if ((Controls.Find(text + "1", true).FirstOrDefault() as DateTimePicker).Value >= (Controls.Find(text + "2", true).FirstOrDefault() as DateTimePicker).Value)
                                    {
                                        continue;
                                    }

                                    rangeDateTimePickersFilter += "([" + text + "] > '" + (Controls.Find(text + "1", true).FirstOrDefault() as DateTimePicker).Value + "' AND [" + text + "] < '" + (Controls.Find(text + "2", true).FirstOrDefault() as DateTimePicker).Value + "') AND ";
                                }
                                if (rangeDateTimePickersFilter != null)
                                {
                                    rangeDateTimePickersFilter = rangeDateTimePickersFilter.Remove(rangeDateTimePickersFilter.Length - 4, 4);
                                }

                                if (rangeDateTimePickersFilter != null)
                                {
                                    if (!rangeDateTimePickersFilter.Equals(old))
                                    {
                                        OnFilterChanged?.Invoke(this, new EventArgs());
                                    }
                                }
                            };
                        }
                        else
                        {
                            rangeTextBoxes.Add(col.Name);
                            Controls.Find("Panel", true).FirstOrDefault().Controls.Add(new GroupBox()
                            {
                                Text   = col.Name,
                                Name   = col.Name + "GroupBox",
                                Dock   = DockStyle.Top,
                                Height = 65,
                            });

                            Controls.Find(col.Name + "GroupBox", true).FirstOrDefault().Controls.Add(new TextBoxTi()
                            {
                                Name        = col.Name + "1",
                                Dock        = DockStyle.Top,
                                OnlyNumbers = true,
                                MaxLength   = 9,
                            });

                            Controls.Find(col.Name + "GroupBox", true).FirstOrDefault().Controls.Add(new TextBoxTi()
                            {
                                Name        = col.Name + "2",
                                Dock        = DockStyle.Bottom,
                                OnlyNumbers = true,
                                MaxLength   = 9,
                            });

                            Controls.Find(col.Name + "1", true).FirstOrDefault().TextChanged += (s, e) =>
                            {
                                if (resetOn)
                                {
                                    return;
                                }

                                string old = rangeTextBoxesFilter;
                                rangeTextBoxesFilter = null;

                                foreach (string text in rangeTextBoxes)
                                {
                                    if (Controls.Find(text + "1", true).FirstOrDefault().Text == "" || Controls.Find(text + "2", true).FirstOrDefault().Text == "")
                                    {
                                        continue;
                                    }
                                    if (Convert.ToInt32(Controls.Find(text + "1", true).FirstOrDefault().Text) - Convert.ToInt32(Controls.Find(text + "2", true).FirstOrDefault().Text) > 0)
                                    {
                                        continue;
                                    }

                                    rangeTextBoxesFilter += "([" + text + "] > '" + Controls.Find(text + "1", true).FirstOrDefault().Text + "' AND [" + text + "] < '" + Controls.Find(text + "2", true).FirstOrDefault().Text + "') AND ";
                                }
                                if (rangeTextBoxesFilter != null)
                                {
                                    rangeTextBoxesFilter = rangeTextBoxesFilter.Remove(rangeTextBoxesFilter.Length - 4, 4);
                                }

                                if (rangeTextBoxesFilter != null)
                                {
                                    if (!rangeTextBoxesFilter.Equals(old))
                                    {
                                        OnFilterChanged?.Invoke(this, new EventArgs());
                                    }
                                }
                            };

                            Controls.Find(col.Name + "2", true).FirstOrDefault().TextChanged += (s, e) =>
                            {
                                if (resetOn)
                                {
                                    return;
                                }

                                string old = rangeTextBoxesFilter;
                                rangeTextBoxesFilter = null;

                                foreach (string text in rangeTextBoxes)
                                {
                                    if (Controls.Find(text + "1", true).FirstOrDefault().Text == "" || Controls.Find(text + "2", true).FirstOrDefault().Text == "")
                                    {
                                        continue;
                                    }
                                    if (Convert.ToInt32(Controls.Find(text + "1", true).FirstOrDefault().Text) - Convert.ToInt32(Controls.Find(text + "2", true).FirstOrDefault().Text) > 0)
                                    {
                                        continue;
                                    }

                                    rangeTextBoxesFilter += "([" + text + "] > '" + Controls.Find(text + "1", true).FirstOrDefault().Text + "' AND [" + text + "] < '" + Controls.Find(text + "2", true).FirstOrDefault().Text + "') AND ";
                                }
                                if (rangeTextBoxesFilter != null)
                                {
                                    rangeTextBoxesFilter = rangeTextBoxesFilter.Remove(rangeTextBoxesFilter.Length - 4, 4);
                                }

                                if (rangeTextBoxesFilter != null)
                                {
                                    if (!rangeTextBoxesFilter.Equals(old))
                                    {
                                        OnFilterChanged?.Invoke(this, new EventArgs());
                                    }
                                }
                            };
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("SQLRequestFilter " + e.Message);
            }

            Supports.GangeGroup(this);
        }
예제 #25
0
        public SatelliteList()
        {
            Name = "tabPageSatelliteList";
            Text = "ИСЗ";

            SatelliteListControls();
            LoadComboUp();
            Supports.GangeGroup(this);

            switch (dataBase.ToCount("SELECT [SatellitesType] FROM [Login] WHERE [Login].[Login] = '" + Profile.userLogin + "'").ToString())
            {
            case "CIV":
                membership                = " WHERE Принадлежность = 'CIV' OR Принадлежность IS NULL OR Принадлежность = 'TWO'";
                Диапазон.SelectedIndex    = 5;
                Поляризация.SelectedIndex = 3;
                break;

            case "MIL":
                membership                = " WHERE Принадлежность = 'MIL' OR Принадлежность IS NULL OR Принадлежность = 'TWO'";
                Диапазон.SelectedIndex    = 4;
                Поляризация.SelectedIndex = 0;
                break;

            default:
                Диапазон.SelectedIndex    = 3;
                Поляризация.SelectedIndex = 3;
                break;
            }



            Enter += (s, e) =>
            {
                if (binded)
                {
                    dataBase.ToDisplay(addCount + membership + " ORDER BY [НаименованиеИСЗ]", dataTableName: "SatelliteList", requestJustByMyself: true);
                    dgv.CurrentCell = dgv["НаименованиеИСЗ", currentRow];
                }
            };
            Leave += (s, e) =>
            {
                currentRow = dgv.CurrentCell.RowIndex;
            };

            dgv.DataBindingComplete += (s, args) =>
            {
                foreach (DataGridViewRow r in dgv.Rows)
                {
                    r.HeaderCell.Value = String.Format("{0}", r.Index + 1);
                }

                if (binded)
                {
                    return;
                }
                binded = true;

                dgv.Columns["ID"].Visible             = false;
                dgv.Columns["Примечание"].Visible     = false;
                dgv.Columns["Описание"].Visible       = false;
                dgv.Columns["Принадлежность"].Visible = false;
                dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

                dgv.SelectionChanged += DownControlsUpdate;

                Диапазон.SelectedValueChanged    += (es, e) => DownSignUpdate();
                Поляризация.SelectedValueChanged += (se, e) => DownSignUpdate();
            };

            dgv.UserDeletedRow  += (s, e) => dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SSALoading"]);
            dgv.UserDeletingRow += (sender, e) =>
            {
                dataBase.ToUpdate(Profile.userLogin, "Удалил запись о спутнике " + '"' + e.Row.Cells["НаименованиеИСЗ"].Value.ToString() + '"' + "\"");
                e.Cancel = false;
            };

            dgv.CellMouseClick += (sender, e) =>
            {
                if (dgv != null)
                {
                    if (e.Button == MouseButtons.Right)
                    {
                        Supports.MenuPanel(dgv, e.RowIndex, e.ColumnIndex, typeof(SatelliteList));
                    }
                    if (e.Button == MouseButtons.Left)
                    {
                    }
                }
            };
            dgv.MouseMove += (se, arg) =>
            {
                if (dgv.ContextMenuStrip != null)
                {
                    dgv.ContextMenuStrip.Dispose();
                }
            };
            dgv.KeyDown += (s, e) =>
            {
                if (e.KeyData == Keys.Delete)
                {
                    e.Handled = true;
                }
            };

            editSatellite.Click += (s, e) =>
            {
                if (dgv.SelectedCells.Count == 0)
                {
                    return;
                }

                bool red = false;

                dgv.CurrentCell = dgv.Rows.Cast <DataGridViewRow>().Where(x => x.Cells["НаименованиеИСЗ"].Value.ToString() == НаименованиеИСЗ.Text).FirstOrDefault().Cells["НаименованиеИСЗ"];

                if (MessageBoxTi.Show("Вы действительно хотите редактировать данные этого спутника?", "Редактирование") == MessageResult.Yes)
                {
                    var ind = dgv.SelectedRows[0].Index;

                    if (!dgv.SelectedRows[0].Cells["МеждНомер"].Value.ToString().Equals(МеждНомер.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"МеждНомер\" с \"" + МеждНомер.Text + "\" на \"" + МеждНомер.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["МеждНомер"] = МеждНомер.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["ПСТ"].Value.ToString().Equals(ПСТ.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"ПСТ\" с \"" + ПСТ.Text + "\" на \"" + ПСТ.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["ПСТ"] = ПСТ.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Производитель"].Value.ToString().Equals(Производитель.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"Производитель\" с \"" + Производитель.Text + "\" на \"" + Производитель.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Производитель"] = Производитель.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Описание"].Value.ToString().Equals(Описание.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"Описание\" с \"" + Описание.Text + "\" на \"" + Описание.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Описание"] = Описание.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Состояние"].Value.ToString().Equals(Состояние.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"Состояние\" с \"" + Состояние.Text + "\" на \"" + Состояние.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Состояние"] = Состояние.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Примечание"].Value.ToString().Equals(Примечание.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"Примечание\" с \"" + Примечание.Text + "\" на \"" + Примечание.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Примечание"] = Примечание.Text;
                        red = true;
                    }

                    if (!dgv.SelectedRows[0].Cells["Принадлежность"].Value.ToString().Equals(Принадлежность.Text))
                    {
                        dataBase.ToUpdate(Profile.userLogin, "Изменил запись о спутнике \"" + НаименованиеИСЗ.Text + "\" в графе \"Принадлежность\" с \"" + Принадлежность.Text + "\" на \"" + Принадлежность.Text + "\"");
                        dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Принадлежность"] = Принадлежность.Text;
                        red = true;
                    }

                    if (red == false)
                    {
                        return;
                    }
                    dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["ID"].ToString().Equals(dgv["ID", ind].Value.ToString())).FirstOrDefault()["Тредакт"] = dataBase.ToCount("SELECT GETDATE()");
                    dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SatelliteList"]);
                    LoadComboUp();
                }
            };
            addSatellite.Click += (s, e) =>
            {
                string h = MessageBoxTi.Show("Добавление спутника", "Введите название спутника", HorizontalAlignment.Left);
                while ((int)dataBase.ToCount("SELECT COUNT(*) FROM[dbo].[SatelliteList] WHERE[dbo].[SatelliteList].[НаименованиеИСЗ] = '" + h + "'") != 0)
                {
                    h = MessageBoxTi.Show("Добавление спутника", "Такой спутник уже есть! Введите другое название спутника", HorizontalAlignment.Left);
                }
                if (h == null || h == "")
                {
                    return;
                }
                DataRow p = dataBase.dataset.Tables["SatelliteList"].NewRow();
                p["НаименованиеИСЗ"] = h;
                p["МеждНомер"]       = МеждНомер.Text;
                p["ПСТ"]             = ПСТ.Text;
                p["Производитель"]   = Производитель.Text;
                p["Описание"]        = Описание.Text;
                p["Состояние"]       = Состояние.Text;
                p["Примечание"]      = Примечание.Text;
                p["Тредакт"]         = dataBase.ToCount("SELECT GETDATE()");
                p["Принадлежность"]  = Принадлежность.Text;

                if (p["НаименованиеИСЗ"].ToString() != "")
                {
                    if (dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["НаименованиеИСЗ"].Equals(p["НаименованиеИСЗ"])).Count() == 0)
                    {
                        dataBase.dataset.Tables["SatelliteList"].Rows.Add(p);
                        dataBase.ToUpdate(Profile.userLogin, "Добавил спутник \"" + p["НаименованиеИСЗ"] + "\"");
                        dataBase.sqlAdapter.Update(dataBase.dataset.Tables["SatelliteList"]);
                        dataBase.ToDisplay(addCount + membership + " ORDER BY [НаименованиеИСЗ]", dataTableName: "SatelliteList", requestJustByMyself: true);
                        dgv.CurrentCell = dgv.Rows.Cast <DataGridViewRow>().Where(x => x.Cells["НаименованиеИСЗ"].Value.ToString() == h).FirstOrDefault().Cells[1];
                    }
                    else
                    {
                        MessageBoxTi.Show("Спутник с таким названием уже есть");
                    }
                }
            };
            goToBand.Click += (s, e) =>
            {
                if (Profile.tabControl1.TabPages.IndexOfKey("WHERE Спутник = \'" + НаименованиеИСЗ.Text + "\' AND Диапазон = \'" + Диапазон.Text + "\' AND Поляризация = \'" + Поляризация.Text + "\'") == -1)
                {
                    if (НаименованиеИСЗ.Text == "")
                    {
                        MessageBoxTi.Show("Введите название спутника");
                    }
                    else
                    {
                        if (dataBase.dataset.Tables["SatelliteList"].Select().Where(x => x["НаименованиеИСЗ"].Equals(НаименованиеИСЗ.Text)).Count() != 0)
                        {
                            if (Convert.ToInt32(Излучения.Text) != 0)
                            {
                                Profile.tabControl1.TabPages.Add(new Loading(НаименованиеИСЗ.Text, Диапазон.Text, Поляризация.Text));
                                Profile.tabControl1.SelectedTab = Profile.tabControl1.TabPages["WHERE Спутник = \'" + НаименованиеИСЗ.Text + "\' AND Диапазон = \'" + Диапазон.Text + "\' AND Поляризация = \'" + Поляризация.Text + "\'"];
                            }
                            else
                            {
                                if (MessageBoxTi.Show("Нет такого типа излучений", "Добавить новое излучение?") == MessageResult.Yes)
                                {
                                    Profile.tabControl1.TabPages.Add(new Loading(НаименованиеИСЗ.Text, Диапазон.Text, Поляризация.Text));
                                    Profile.tabControl1.SelectedTab = Profile.tabControl1.TabPages["WHERE Спутник = \'" + НаименованиеИСЗ.Text + "\' AND Диапазон = \'" + Диапазон.Text + "\' AND Поляризация = \'" + Поляризация.Text + "\'"];
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }
                        else
                        {
                            MessageBoxTi.Show("Спутника с таким названием не существует");
                        }
                    }
                }
                else
                {
                    Profile.tabControl1.SelectedTab = Profile.tabControl1.TabPages["WHERE Спутник = \'" + НаименованиеИСЗ.Text + "\' AND Диапазон = \'" + Диапазон.Text + "\' AND Поляризация = \'" + Поляризация.Text + "\'"];
                    return;
                }
            };

            dataBase.ToDisplay(addCount + membership + " ORDER BY [НаименованиеИСЗ]", dataTableName: "SatelliteList", requestJustByMyself: true);
            dgv.DataSource = dataBase.dataset.Tables["SatelliteList"];
        }
예제 #26
0
        private void prepare()
        {
            try
            {
                MaximizedBounds = Screen.FromHandle(Handle).WorkingArea;

                if (Environment.OSVersion.Version.Build < 4000)
                {
                    BackColor = Supports.headBlue;
                }

                bool lite = false;

                if (panel4.BackColor.R < 122)
                {
                    lite = true;
                }
                if (lite)
                {
                    x1 = Resources.x1tw;
                    x2 = Resources.x2tw;
                    x3 = Resources.x3tw;
                    x4 = Resources.x7tw;
                }
                else
                {
                    x1 = Resources.x1tb;
                    x2 = Resources.x2tb;
                    x3 = Resources.x3tb;
                    x4 = Resources.x7tb;
                }

                pictureBox1.Image = x1;
                pictureBox2.Image = x2;
                pictureBox3.Image = x3;

                FormWindowState prevState = WindowState;
                MouseUp += (s, arg) =>
                {
                    if (Location.Y < 0 && Cursor.Position.Y == 0)
                    {
                        WindowState       = FormWindowState.Maximized;
                        pictureBox2.Image = x2;
                        ChangePadd();
                        return;
                    }
                    else if (Location.X < 0 && Cursor.Position.X == 0)
                    {
                        Height = Screen.FromControl(this).Bounds.Height;
                        Width  = Screen.FromControl(this).Bounds.Width / 2;
                    }

                    if (Location.Y < 0)
                    {
                        Location = new Point(Location.X, 0);
                        return;
                    }
                };
                Deactivate += (s, arg) =>
                {
                    BackColor = Color.Gray;
                };
                Activated += (s, arg) =>
                {
                    BackColor = Supports.headBlue;
                };
                Resize += (s, arg) =>
                {
                    if (prevState != WindowState)
                    {
                        prevState = WindowState;
                        ChangePadd();
                        if (WindowState == FormWindowState.Maximized)
                        {
                            pictureBox2.Image = x2;
                        }
                        else
                        {
                            pictureBox2.Image = x4;
                        }
                    }
                };

                pictureBox1.MouseEnter += (s, arg) => pictureBox1.BackColor = Supports.liteTextGray;
                pictureBox1.MouseUp    += (s, arg) => pictureBox1.BackColor = Supports.headGrey;
                pictureBox1.MouseDown  += (s, arg) => pictureBox1.BackColor = Supports.headBlue;
                pictureBox1.MouseLeave += (s, arg) => pictureBox1.BackColor = Supports.headGrey;
                pictureBox1.MouseClick += (s, arg) =>
                {
                    if (MessageBoxTi.Show("Завершение работы", "Точно выйти?") != MessageResult.Yes)
                    {
                        return;
                    }
                    Supports.WorkActivity.Stop();
                    Close();
                };
                pictureBox2.MouseEnter += (s, arg) => pictureBox2.BackColor = Supports.liteTextGray;
                pictureBox2.MouseLeave += (s, arg) => pictureBox2.BackColor = Supports.headGrey;
                pictureBox2.MouseUp    += (s, arg) => pictureBox2.BackColor = Supports.headGrey;
                pictureBox2.MouseDown  += (s, arg) => pictureBox2.BackColor = Supports.headBlue;

                pictureBox2.MouseClick += (s, arg) =>
                {
                    if (WindowState == FormWindowState.Maximized)
                    {
                        WindowState = FormWindowState.Normal;
                    }
                    else
                    {
                        WindowState = FormWindowState.Maximized;
                    }
                };

                pictureBox3.MouseEnter += (s, arg) => pictureBox3.BackColor = Supports.liteTextGray;
                pictureBox3.MouseLeave += (s, arg) => pictureBox3.BackColor = Supports.headGrey;
                pictureBox3.MouseUp    += (s, arg) => pictureBox3.BackColor = Supports.headGrey;
                pictureBox3.MouseDown  += (s, arg) => pictureBox3.BackColor = Supports.headBlue;
                pictureBox3.MouseClick += (s, arg) => WindowState = FormWindowState.Minimized;

                splitContainer1.Visible = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                splitContainer2.Visible = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);
                splitter1.Visible       = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                splitter2.Visible       = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);

                splitContainer1.Panel1.ControlAdded += (s, arg) =>
                {
                    splitContainer1.Panel1Collapsed = false;
                    if (!splitContainer1.Visible)
                    {
                        splitContainer1.Visible = true;
                        splitter1.Visible       = true;
                    }
                };
                splitContainer1.Panel2.ControlAdded += (s, arg) =>
                {
                    splitContainer1.Panel2Collapsed = false;
                    if (!splitContainer1.Visible)
                    {
                        splitContainer1.Visible = true;
                        splitter1.Visible       = true;
                    }
                };
                splitContainer2.Panel1.ControlAdded += (s, arg) =>
                {
                    splitContainer2.Panel1Collapsed = false;
                    if (!splitContainer2.Visible)
                    {
                        splitContainer2.Visible = true;
                        splitter2.Visible       = true;
                    }
                };
                splitContainer2.Panel2.ControlAdded += (s, arg) =>
                {
                    splitContainer2.Panel2Collapsed = false;
                    if (!splitContainer2.Visible)
                    {
                        splitContainer2.Visible = true;
                        splitter2.Visible       = true;
                    }
                };

                splitContainer1.Panel1.ControlRemoved += (s, arg) =>
                {
                    splitContainer1.Panel1Collapsed = (splitContainer1.Panel1.Controls.Count == 0 ? true : false);
                    splitContainer1.Visible         = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                    splitter1.Visible = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                };
                splitContainer1.Panel2.ControlRemoved += (s, arg) =>
                {
                    splitContainer1.Panel2Collapsed = (splitContainer1.Panel2.Controls.Count == 0 ? true : false);
                    splitContainer1.Visible         = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                    splitter1.Visible = (splitContainer1.Panel1.Controls.Count == 0 && splitContainer1.Panel2.Controls.Count == 0 ? false : true);
                };
                splitContainer2.Panel1.ControlRemoved += (s, arg) =>
                {
                    splitContainer2.Panel1Collapsed = (splitContainer2.Panel1.Controls.Count == 0 ? true : false);
                    splitContainer2.Visible         = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);
                    splitter2.Visible = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);
                };
                splitContainer2.Panel2.ControlRemoved += (s, arg) =>
                {
                    splitContainer2.Panel2Collapsed = (splitContainer2.Panel2.Controls.Count == 0 ? true : false);
                    splitContainer2.Visible         = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);
                    splitter2.Visible = (splitContainer2.Panel1.Controls.Count == 0 && splitContainer2.Panel2.Controls.Count == 0 ? false : true);
                };

                FormClosed += (s, args) => dataBase.ToUpdate(userLogin, "Вышел из системы");

                foreach (DataRow st in dataBase.SimpleData("FrequencyBand").Rows)
                {
                    comboBox2.Items.Add(st["Наименование диапазона"]);
                }

                comboBox1.Items.Add("L");
                comboBox1.Items.Add("R");
                comboBox1.Items.Add("V");
                comboBox1.Items.Add("H");

                bool indexChange = false;
                comboBox1.SelectedValueChanged += (s, e) =>
                {
                    if (tabControl1.SelectedTab.GetType() == typeof(Loading) && !indexChange)
                    {
                        if (tabControl1.TabPages.IndexOfKey("WHERE Спутник = \'" + (tabControl1.SelectedTab as Loading).nameISZ + "\' AND Диапазон = \'" + comboBox2.Text + "\' AND Поляризация = \'" + comboBox1.Text + "\'") == -1)
                        {
                            (tabControl1.SelectedTab as Loading).BandAndPolarizationNeedChange(comboBox2.Text, comboBox1.Text);
                        }
                        else
                        {
                            tabControl1.SelectedTab = tabControl1.TabPages["WHERE Спутник = \'" + (tabControl1.SelectedTab as Loading).nameISZ + "\' AND Диапазон = \'" + comboBox2.Text + "\' AND Поляризация = \'" + comboBox1.Text + "\'"];
                        }
                    }
                };
                comboBox2.SelectedValueChanged += (s, e) =>
                {
                    if (tabControl1.SelectedTab.GetType() == typeof(Loading) && !indexChange)
                    {
                        if (tabControl1.TabPages.IndexOfKey("WHERE Спутник = \'" + (tabControl1.SelectedTab as Loading).nameISZ + "\' AND Диапазон = \'" + comboBox2.Text + "\' AND Поляризация = \'" + comboBox1.Text + "\'") == -1)
                        {
                            (tabControl1.SelectedTab as Loading).BandAndPolarizationNeedChange(comboBox2.Text, comboBox1.Text);
                        }
                        else
                        {
                            tabControl1.SelectedTab = tabControl1.TabPages["WHERE Спутник = \'" + (tabControl1.SelectedTab as Loading).nameISZ + "\' AND Диапазон = \'" + comboBox2.Text + "\' AND Поляризация = \'" + comboBox1.Text + "\'"];
                        }
                    }
                };

                tabControl1.SelectedIndexChanged += (s, e) =>
                {
                    if (tabControl1.TabPages.Count == 0)
                    {
                        return;
                    }

                    if (tabControl1.SelectedTab.GetType() == typeof(SatelliteList))
                    {
                        comboBox1.Visible = false;
                        comboBox2.Visible = false;
                    }
                    else if (tabControl1.SelectedTab.GetType() == typeof(Loading))
                    {
                        indexChange       = true;
                        comboBox1.Visible = true;
                        comboBox2.Visible = true;
                        comboBox1.Text    = (tabControl1.SelectedTab as Loading).polarizationISZ;
                        comboBox2.Text    = (tabControl1.SelectedTab as Loading).bandISZ;
                        indexChange       = false;
                    }
                    else
                    {
                        DownSign = null;
                    }
                };
                tabControl1.OnPageClose += (s, e) =>
                {
                    if (tabControl1.TabPages[e.ClosingPageIndex].GetType() == typeof(Loading) && dataBase.dataset.Tables.Contains("Loading " + (tabControl1.TabPages[e.ClosingPageIndex] as Loading).keys))
                    {
                        dataBase.dataset.Tables["Loading " + (tabControl1.TabPages[e.ClosingPageIndex] as Loading).keys].Clear();
                    }
                };

                калькуляторToolStripMenuItem.Click += (s, e) => Process.Start(@"C:\WINDOWS\system32\calc.exe");
                графикToolStripMenuItem.Click      += (s, e) =>
                {
                    tabControl1.TabPages.Add(new Charts("Chart"));

                    tabControl1.SelectedIndex = tabControl1.TabCount - 1;
                };
                headLabel.TextAlign = ContentAlignment.MiddleCenter;
                headLabel.Dock      = DockStyle.Fill;

                if (DateTime.Today.Month == 1 && DateTime.Today.Day < 7 && userDepartment == 2)
                {
                    headLabel.Text = Supports.DeCezarus(dataBase.ToCount("SELECT Content FROM [MainSettings] WHERE [Who] = 'NYCongratulation'").ToString());
                }

                if (DateTime.Today.Month == 5 && DateTime.Today.Day == 9 && userDepartment == 2)
                {
                    headLabel.Text = Supports.DeCezarus(dataBase.ToCount("SELECT Content FROM [MainSettings] WHERE [Who] = '9Congratulation'").ToString());
                }

                if (DateTime.Today.Month == 11 && DateTime.Today.Day == 5 && userDepartment == 2)
                {
                    headLabel.Text = Supports.DeCezarus(dataBase.ToCount("SELECT Content FROM [MainSettings] WHERE [Who] = 'ExpCongratulation'").ToString());
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Profile.prepare " + e.Message);
            }
        }
예제 #27
0
        private void GetIn()
        {
            try {
                if (Convert.ToBoolean(dataBase.SimpleData("[Login] WHERE Login='******'").Rows[0]["Allowed"]).Equals(false))
                {
                    MessageBoxTi.Show("К сожалению вас заблокировали, обратитесь к администратору");
                    return;
                }
                if (gotIn)
                {
                    return;
                }
                if (textBox1.Text == "")
                {
                    toolTip1.Show("Введите логин!", textBox1, textBox1.Width, 0, 2000);
                    return;
                }
                else if (textBox2.Text == "")
                {
                    toolTip1.Show("Введите пароль!", textBox2, textBox1.Width, 0, 2000);
                    return;
                }
                else
                {
                    var Login = dataBase.SimpleData("[Login] WHERE Login='******'");

                    if (Login.Rows.Count == 0)
                    {
                        toolTip1.Show("Неверный логин или пароль", textBox1, textBox1.Width, 0, 2000);
                        return;
                    }


                    if (Login.Rows[0]["Login"].ToString() == textBox1.Text &&
                        Login.Rows[0]["Password"].ToString() == textBox2.Text)
                    {
                        gotIn = true;

                        dataBase.SimpleRequest("INSERT INTO [dbo].[MainLog] ([Who] ,[What] ,[WhenItWas])" +
                                               "SELECT[Login], 'Вышел из системы', [LastSeen] FROM(SELECT[Login], (SELECT top 1[What] FROM[MainLog] WHERE[Who] = [Login].[Login] ORDER BY[WhenItWas] DESC) AS[What], [LastSeen]" +
                                               "FROM[dbo].[Login] WHERE[LastSeen] is not null AND[LastSeen] < GETDATE() - '00:00:02.000') A WHERE[What] != 'Вышел из системы'");

                        if ((int)dataBase.ToCount("SELECT count(*) FROM [MainSettings] WHERE [Who] = 'ColorStyle' AND  [What] = '" + Login.Rows[0]["Login"].ToString() + "'") == 0)
                        {
                            if (Supports.textWhite == Supports.ColorSetDark.textWhite)
                            {
                                dataBase.SimpleRequest("INSERT INTO [MainSettings] ([Who], [What], [Content]) VALUES ('ColorStyle' , '" + Login.Rows[0]["Login"].ToString() + "', 'Dark')");
                            }
                            else
                            {
                                dataBase.SimpleRequest("INSERT INTO [MainSettings] ([Who], [What], [Content]) VALUES ('ColorStyle' , '" + Login.Rows[0]["Login"].ToString() + "', 'Lite')");
                            }
                        }
                        else
                        {
                            if (UsersColorChoise != -1)
                            {
                                if (UsersColorChoise == 1)
                                {
                                    dataBase.SimpleRequest("UPDATE [MainSettings] SET [Content] = 'Lite'  WHERE [Who] = 'ColorStyle' AND [What] = '" + Login.Rows[0]["Пользователь"].ToString() + "'");
                                }
                                else
                                {
                                    dataBase.SimpleRequest("UPDATE [MainSettings] SET [Content] = 'Dark'  WHERE [Who] = 'ColorStyle' AND [What] = '" + Login.Rows[0]["Пользователь"].ToString() + "'");
                                }
                            }
                            else if ((string)dataBase.ToCount("SELECT [Content] FROM [MainSettings] WHERE [Who] = 'ColorStyle' AND  [What] = '" + Login.Rows[0]["Login"].ToString() + "'") == "Dark")
                            {
                                pictureBox4_Click(this, new EventArgs());
                            }
                        }

                        object exist = dataBase.ToCount("SELECT [LastSeen] FROM [dbo].[Login] WHERE [dbo].[Login].[Login] = '" + textBox1.Text + "'");
                        if (exist != null)
                        {
                            if (((DateTime)exist).AddSeconds(2) > Convert.ToDateTime(dataBase.ToCount("SELECT GETDATE()")))
                            {
                                MessageBoxTi.Show("Другой пользователь уже вошёл в в базу под тиким логином");
                                gotIn = false;
                                return;
                            }
                        }


                        Hide();
                        Profile form = null;

                        if (!Convert.IsDBNull(Login.Rows[0]["Face"]))
                        {
                            form = new Profile(Login.Rows[0]["Login"].ToString(), face: (Bitmap)Image.FromStream(new MemoryStream((byte[])Login.Rows[0]["Face"])));
                        }
                        else
                        {
                            form = new Profile(Login.Rows[0]["Login"].ToString());
                        }

                        form.FormClosed += (se, args) => Close();
                        form.Show();
                        return;
                    }
                    else
                    {
                        toolTip1.Show("Неверный логин или пароль", textBox1, textBox1.Width, 0, 2000);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("LoginForm.GetIn " + e.Message);
            }
        }