private void CreateControls()
        {
            this.GenControls.Clear();
            this.panel1.Controls.Clear();

            foreach (DataRow row in FormFields.Rows)
            {
                var groupName   = row.Item("GroupName");
                var controlType = row.Item("ControlType");

                var control = CreateGenControl(groupName, controlType);

                control.Margin          = new System.Windows.Forms.Padding(0);
                control.FieldName       = row.Item("FieldName");
                control.FieldCaption    = row.Item("FieldCaption");
                control.LookupSource    = row.Item("LookupSource");
                control.WidthPercentage = ConvertSafe.ToInt32(row.Item("WidthPercentage"));
                control.HeightPixel     = ConvertSafe.ToInt32(row.Item("HeightPixel"));
                control.IsRequired      = ConvertSafe.ToBoolean(row.Item("IsRequired"));
                control.IsReadOnly      = ConvertSafe.ToBoolean(row.Item("IsReadOnly"));

                control.Initialize(Services);
                control.Process();
            }
        }
        private void btnProperties_Click(object sender, EventArgs e)
        {
            var row = gvAnswers.GetDataRow(gvAnswers.FocusedRowHandle);

            if (row == null)
            {
                return;
            }
            using (var frm = new Properties.frmPropertiesMultiChoice())
            {
                frm.Initialize(Services);
                frm.Process(row);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    //update lai table
                    var rowHandle = ConvertSafe.ToInt32(frm.MultiChoice_View_Answer_AnswerIndex) - 1;
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerText", frm.MultiChoice_View_Answer_AnswerText);
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_VariableName", frm.MultiChoice_View_Answer_AnswerCodes_VariableName);
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_UnCheckedCode", ConvertSafe.ToInt32(frm.MultiChoice_View_Answer_AnswerCodes_UnCheckedCode));
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_CheckedCode", ConvertSafe.ToInt32(frm.MultiChoice_View_Answer_AnswerCodes_CheckedCode));
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_OtherSpecify", ConvertSafe.ToBoolean(frm.MultiChoice_View_Answer_AnswerCodes_OtherSpecify));
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_OtherSpecify_VariableName", frm.MultiChoice_View_Answer_AnswerCodes_OtherSpecify_VariableName);
                    gvAnswers.SetRowCellValue(rowHandle, "MultiChoice_View_Answer_AnswerCodes_OtherSpecify_InType", frm.MultiChoice_View_Answer_AnswerCodes_OtherSpecify_InType);
                    gvAnswers.UpdateCurrentRow();
                }
            }
        }
        private void textEdit2_EditValueChanged(object sender, EventArgs e)
        {
            if (textEdit2.Text.ToString().Length == 2)
            {
                textEdit3.Focus();
                textEdit3.SelectAll();
            }

            if (ConvertSafe.ToInt32(textEdit2.Text.Trim()) >= 2)
            {
                FormatMonth();
                textEdit3.Focus();
                textEdit3.SelectAll();
            }
        }
        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (textEdit1.Text.ToString().Length == 2)
            {
                textEdit2.Focus();
                textEdit2.SelectAll();
            }

            if (ConvertSafe.ToInt32(textEdit1.Text.Trim()) >= 4)
            {
                FormatNgay();
                textEdit2.Focus();
                textEdit2.SelectAll();
            }
            SetMaskThang();
        }
Ejemplo n.º 5
0
        public static TryRegisterComputerId RegisterComputerId(string shopId, bool is1CServer = true, bool isMainCashbox = false)
        {
            if (string.IsNullOrEmpty(shopId))
            {
                return(new TryRegisterComputerId(0, false, "Пустой Id магазина"));
            }

            DataSet dsShop = SqlWorks.ExecProc("IsShopExists", shopId);

            if (dsShop == null || ConvertSafe.ToInt32(dsShop.Tables[0].Rows[0]["result"]) == 0)
            {
                return(new TryRegisterComputerId(0, false, $"Магазин с id = {shopId} отсутствует"));
            }

            DataSet ds = SqlWorks.ExecProc("RegisterComputer",
                                           shopId,
                                           Environment.MachineName,
                                           NetWork.GetLocalIPAddress(),
                                           is1CServer,
                                           isMainCashbox,
                                           HardwareInfo.GetMacAddress());

            if (ds != null)
            {
                int?id = Convert.ToInt32(ds.Tables[0].Rows[0]["ComputerId"]);
                if (id.HasValue)
                {
                    return(new TryRegisterComputerId(id.Value));
                }
                else
                {
                    NLogger.LogErrorToHdd("Ошибка регистрации. Не удалось получить ID компьютера.", MainSettings.Constants.MAGIC_UPDATER);
                    return(new TryRegisterComputerId(0, false, "Ошибка регистрации. Не удалось получить ID компьютера."));
                }
            }
            else
            {
                NLogger.LogErrorToHdd("Ошибка регистрации. Не удалось получить ID компьютера.", MainSettings.Constants.MAGIC_UPDATER);
                return(new TryRegisterComputerId(0, false, "Ошибка регистрации. Не удалось получить ID компьютера."));
            }
        }
 private void SetMaskThang()
 {
     if (ConvertSafe.ToInt32(textEdit1.Text.Trim()) <= 29)
     {
         textEdit2.Properties.Mask.EditMask = "[1-9]|[1][0-2]|[0][1-9]";
     }
     else
     {
         if (ConvertSafe.ToInt32(textEdit1.Text.Trim()) == 30)
         {
             textEdit2.Properties.Mask.EditMask = "[13456789]|[1][0-2]|[0][13456789]";
         }
         else if (ConvertSafe.ToInt32(textEdit1.Text.Trim()) == 31)
         {
             textEdit2.Properties.Mask.EditMask = "[13578]|[1][02]|[0][13578]";
         }
         else
         {
             textEdit2.Properties.Mask.EditMask = "[1-9]|[1][0-2]|[0][1-9]";
         }
     }
 }
Ejemplo n.º 7
0
        public void Populate(DataTable table)
        {
            last_x     = 0;
            row_y      = 0;
            row_height = 0;

            foreach (DataRow row in table.Rows)
            {
                var group   = row.Item("Group");
                var name    = row.Item("Name");
                var height  = ConvertSafe.ToInt32(row.Item("Height"));
                var width   = ConvertSafe.ToInt32(row.Item("Width"));
                var type    = row.Item("Type");
                var value   = row.Item("Value");
                var options = row.Item("Options");

                var groupControl = this.FindGroup(group);
                groupControl.CreateControl((int)(height * 1.2), width, type, name, value, options);
            }

            this.OnResize(EventArgs.Empty);
        }
Ejemplo n.º 8
0
        public TryLoadSettingsFromSql LoadSqlMainSettingsFromSQL()
        {
            DataSet ds = null;

            ds = SqlWorks.ExecProcExt(MainSettings.JsonSettings.ConnectionString, "GetComputerSettingsViaMac", HardwareInfo.GetMacAddress());
            if (ds != null)
            {
                ComputerId    = ConvertSafe.ToInt32(ds.Tables[0].Rows[0]["ComputerId"]);
                ShopID        = ConvertSafe.ToString(ds.Tables[0].Rows[0]["ShopId"]);
                Is1CServer    = ConvertSafe.ToBoolean(ds.Tables[0].Rows[0]["Is1CServer"]);
                IsMainCashbox = ConvertSafe.ToBoolean(ds.Tables[0].Rows[0]["IsMainCashbox"]);
                return(new TryLoadSettingsFromSql());
            }
            else
            {
                ComputerId    = 0;
                ShopID        = string.Empty;
                Is1CServer    = false;
                IsMainCashbox = false;
                return(new TryLoadSettingsFromSql(false, "Компьтер не зарегистрирован."));
            }
        }
        private DataTable GetDataView(DataTable tblQuestion, DataTable tblData)
        {
            foreach (DataRow row in tblQuestion.Rows)
            {
                row["QuestionName"] = HtmlToPlainText(row.Item("QuestionNameHTMLText"));
                int QuestionTypeID = ConvertSafe.ToInt32(row.Item("QuestionTypeID"));
                if (QuestionTypeID == 1)
                {
                    //tim tat ca nhung cau tra loi
                    var values = tblData.Select(string.Format("QuestionCode='{0}'", row.Item("QuestionCode")));
                    if (values.Count() > 0)
                    {
                        //tim value da chon luc truoc.
                        string result      = "";
                        bool   IsLocked    = false;
                        string valueSelect = tblData._FindValue("AnswerText", "FieldName", row.Item("QuestionCode"));
                        result = valueSelect;
                        //tim value khac
                        foreach (DataRow c_row in values)
                        {
                            if (c_row.Item("FieldName") != row.Item("QuestionCode"))
                            {
                                if (c_row.Item("AnswerText").IsNotEmpty())
                                {
                                    result += "[" + c_row.Item("AnswerText") + "]";
                                }
                            }

                            if (ConvertSafe.ToBoolean(c_row.Item("IsLocked")) == true)
                            {
                                IsLocked = true;
                            }
                        }
                        row["checked"]    = IsLocked;
                        row["AnswerText"] = result;
                    }
                }
                if (QuestionTypeID == 2)
                {
                    var values = tblData.Select(string.Format("QuestionCode='{0}'", row.Item("QuestionCode")));
                    if (values.Count() > 0)
                    {
                        //tim value da chon luc truoc.
                        string result   = "";
                        bool   IsLocked = false;
                        var    dt       = row.Item("MultiChoice_Answer_AnswerList").JSONToDataTable();

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var    c_row     = dt.Rows[i];
                            string var_name  = c_row.Item("MultiChoice_View_Answer_AnswerCodes_VariableName");
                            string valuetext = tblData._FindValue("AnswerText", "FieldName", var_name);
                            if (valuetext.IsNotEmpty())
                            {
                                result += valuetext;
                                string valuetextOther = tblData._FindValue("AnswerText", "FieldName", row.Item("QuestionCode") + "_" + c_row.Item("MultiChoice_View_Answer_AnswerCodes_VariableName") + "_K");
                                if (valuetextOther.IsNotEmpty())
                                {
                                    result += "[" + valuetextOther + "]";
                                }
                                result += Environment.NewLine;
                            }
                        }
                        foreach (var row_c in values)
                        {
                            if (ConvertSafe.ToBoolean(row_c.Item("IsLocked")) == true)
                            {
                                IsLocked = true;
                            }
                        }
                        row["checked"]    = IsLocked;
                        row["AnswerText"] = result;
                    }
                }
                if (QuestionTypeID == 3)
                {
                    bool IsLocked = false;


                    row["AnswerText"] = tblData._FindValue("AnswerText", "FieldName", row.Item("QuestionCode"));

                    var values = tblData.Select(string.Format("QuestionCode='{0}'", row.Item("QuestionCode")));
                    foreach (var row_c in values)
                    {
                        if (ConvertSafe.ToBoolean(row_c.Item("IsLocked")) == true)
                        {
                            IsLocked = true;
                        }
                    }
                    row["checked"] = IsLocked;
                }

                if (QuestionTypeID == 5)
                {
                }
                if (QuestionTypeID == 6)
                {
                }
                if (QuestionTypeID == 7)
                {
                    bool IsLocked = false;
                    row["AnswerText"] = tblData._FindValue("AnswerText", "FieldName", row.Item("QuestionCode"));

                    var values = tblData.Select(string.Format("QuestionCode='{0}'", row.Item("QuestionCode")));
                    foreach (var row_c in values)
                    {
                        if (ConvertSafe.ToBoolean(row_c.Item("IsLocked")) == true)
                        {
                            IsLocked = true;
                        }
                    }

                    row["checked"] = IsLocked;
                }
            }

            return(tblQuestion);
        }
Ejemplo n.º 10
0
        public static TryRegisterPlugin RegisterOrUpdatePluginLastModifiedDate(string fileName)
        {
            string dllLocalFullPath = Path.Combine(MainSettings.Constants.PluginOperationDllDirectoryPath, fileName);

            string dllFtpFullPath = Path.Combine(MainSettings.GlobalSettings.SelfUpdateFtpPath
                                                 , MainSettings.Constants.OPERATION_PLUGIN_DIRECTORY_NAME
                                                 , fileName);
            DateTime?ftpFileLastModifiedDate = FtpWorks.GetFileLastModifiedDate(MainSettings.GlobalSettings.SelfUpdateFtpServer
                                                                                , MainSettings.GlobalSettings.SelfUpdateFtpUser
                                                                                , MainSettings.GlobalSettings.SelfUpdateFtpPassword
                                                                                , Path.Combine(MainSettings.GlobalSettings.SelfUpdateFtpPath, MainSettings.Constants.OPERATION_PLUGIN_DIRECTORY_NAME)
                                                                                , fileName);

            if (ftpFileLastModifiedDate.HasValue)
            {
                try
                {
                    DataSet ds = SqlWorks.ExecProc("GetOperationTypeByFileName", fileName);
                    if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                    {
                        //Регистрируем
                        //Актуализируем файл из фтп, если нужно
                        var res = GetOrUpdateFileFromFtpLastModifiedDate(fileName, null);
                        if (!res.IsComplete)
                        {
                            return(new TryRegisterPlugin(false, $"Ошибка скачивания файла ({fileName}) с ftp в директорию ({MainSettings.Constants.PluginOperationDllDirectoryPath})"));
                        }
                        else
                        {
                            /*
                             * @Name nvarchar(512)
                             * ,@NameRus nvarchar(512)
                             * ,@GroupId int
                             * ,@FileName nvarchar(510)
                             * ,@FileMD5 nvarchar(64)
                             * ,@Description nvarchar(MAX)
                             */

                            //Пробуем получить имя типа операции
                            var dllResult = GetFromDll(dllLocalFullPath);
                            if (!dllResult.IsComplete)
                            {
                                return(new TryRegisterPlugin(false, $"Ошибка получения типа операции из файла ({dllLocalFullPath})"));
                            }

                            var addDs = SqlWorks.ExecProc("AddOperationType"
                                                          , dllResult.PluginOperationInstance.SqlName
                                                          , ""
                                                          , 1
                                                          , fileName
                                                          , ftpFileLastModifiedDate
                                                          , MD5Works.GetFileHash(dllLocalFullPath).ToUpper()
                                                          , "");

                            if (addDs != null && addDs.Tables.Count > 0 && addDs.Tables[0].Rows.Count > 0)
                            {
                                int id = ConvertSafe.ToInt32(addDs.Tables[0].Rows[0]["Id"]);
                                foreach (var param in dllResult.PluginOperationInstance.RegistrationParams)
                                {
                                    var resDs = SqlWorks.ExecProc("UpdateOperationTypesFieldsById"
                                                                  , id
                                                                  , param.Key
                                                                  , param.Value);

                                    if (resDs != null && resDs.Tables.Count > 0 && resDs.Tables[0].Rows.Count > 0)
                                    {
                                        if (Convert.ToInt32(resDs.Tables[0].Rows[0]["ResultId"]) == -1)
                                        {
                                            return(new TryRegisterPlugin(false, $"Ошибка записи параметров SQL из файла ({dllLocalFullPath}). SQL Error: {Convert.ToString(resDs.Tables[0].Rows[0]["Message"])}"));
                                        }
                                    }
                                    else
                                    {
                                        return(new TryRegisterPlugin(false, $"Ошибка записи параметров SQL из файла ({dllLocalFullPath})"));
                                    }
                                }
                            }

                            return(new TryRegisterPlugin());
                        }
                    }
                    else
                    {
                        DataRow  dr          = ds.Tables[0].Rows[0];
                        DateTime?sqlDateTime = null;
                        try
                        {
                            sqlDateTime = (DateTime?)dr["LastModifiedDate"];
                        }
                        catch
                        {
                            sqlDateTime = null;
                        }
                        //Обновляем, если нужно
                        if (!Extensions.IsNullableDateTimeIdentical(ftpFileLastModifiedDate, sqlDateTime))
                        {
                            //Актуализируем файл из фтп, если нужно
                            var res = GetOrUpdateFileFromFtpLastModifiedDate(fileName, sqlDateTime);
                            if (!res.IsComplete)
                            {
                                return(new TryRegisterPlugin(false, $"Ошибка скачивания файла ({fileName}) с ftp в директорию ({MainSettings.Constants.PluginOperationDllDirectoryPath})"));
                            }
                            else
                            {
                                var dllResult = GetFromDll(dllLocalFullPath);
                                if (!dllResult.IsComplete)
                                {
                                    return(new TryRegisterPlugin(false, $"Ошибка получения типа операции из файла ({dllLocalFullPath})"));
                                }

                                SqlWorks.ExecProc("UpdateOperationTypeById"
                                                  , Convert.ToInt32(dr["Id"])
                                                  , dllResult.PluginOperationInstance.SqlName
                                                  , ""
                                                  , 1
                                                  , fileName
                                                  , ftpFileLastModifiedDate
                                                  , MD5Works.GetFileHash(dllLocalFullPath).ToUpper()
                                                  , "");

                                foreach (var param in dllResult.PluginOperationInstance.RegistrationParams)
                                {
                                    var resDs = SqlWorks.ExecProc("UpdateOperationTypesFieldsById"
                                                                  , Convert.ToInt32(dr["Id"])
                                                                  , param.Key
                                                                  , param.Value);

                                    if (resDs != null && resDs.Tables.Count > 0 && resDs.Tables[0].Rows.Count > 0)
                                    {
                                        if (Convert.ToInt32(resDs.Tables[0].Rows[0]["ResultId"]) == -1)
                                        {
                                            return(new TryRegisterPlugin(false, $"Ошибка записи параметров SQL из файла ({dllLocalFullPath}). SQL Error: {Convert.ToString(resDs.Tables[0].Rows[0]["Message"])}"));
                                        }
                                    }
                                    else
                                    {
                                        return(new TryRegisterPlugin(false, $"Ошибка записи параметров SQL из файла ({dllLocalFullPath})"));
                                    }
                                }

                                return(new TryRegisterPlugin());
                            }
                        }

                        return(new TryRegisterPlugin());
                    }
                }
                catch (Exception ex)
                {
                    return(new TryRegisterPlugin(false, ex.ToString()));
                }
            }
            else
            {
                return(new TryRegisterPlugin(false, $"Не удалось получить дату последнего изменения файла ({fileName}) по ftp"));
            }
        }
Ejemplo n.º 11
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     OperationGroupId = ConvertSafe.ToInt32(cbOperationGroup.SelectedValue);
 }
Ejemplo n.º 12
0
 private bool CheckAgentIsOn()
 {
     try
     {
         if (MainSettings.MainSqlSettings.ComputerId.HasValue)
         {
             var ds = SqlWorks.ExecProc("GetComputerById", MainSettings.MainSqlSettings.ComputerId.Value);
             if (ds != null &&
                 ds.Tables.Count > 0 &&
                 ds.Tables[0].Rows.Count > 0)
             {
                 bool isOn = ConvertSafe.ToInt32(ds.Tables[0].Rows[0]["IsON"]) == 1 ? true : false;
                 if (isOn)
                 {
                     if (this.InvokeRequired)
                     {
                         this.Invoke(new MethodInvoker(() =>
                         {
                             lbAgentStatus.Text      = "Агент отчитывается в базу";
                             lbAgentStatus.BackColor = Color.LightGreen;
                         }));
                     }
                     else
                     {
                         lbAgentStatus.Text      = "Агент отчитывается в базу";
                         lbAgentStatus.BackColor = Color.LightGreen;
                     }
                     return(true);
                 }
                 else
                 {
                     if (this.InvokeRequired)
                     {
                         this.Invoke(new MethodInvoker(() =>
                         {
                             lbAgentStatus.Text      = "Агент не отчитывается в базу";
                             lbAgentStatus.BackColor = Color.Pink;
                         }));
                     }
                     else
                     {
                         lbAgentStatus.Text      = "Агент не отчитывается в базу";
                         lbAgentStatus.BackColor = Color.Pink;
                     }
                     return(false);
                 }
             }
             else
             {
                 if (this.InvokeRequired)
                 {
                     this.Invoke(new MethodInvoker(() =>
                     {
                         lbAgentStatus.Text      = "Агент не отчитывается в базу";
                         lbAgentStatus.BackColor = Color.Pink;
                     }));
                 }
                 else
                 {
                     lbAgentStatus.Text      = "Агент не отчитывается в базу";
                     lbAgentStatus.BackColor = Color.Pink;
                 }
                 return(false);
             }
         }
     }
     catch (Exception ex)
     {
         if (this.InvokeRequired)
         {
             this.Invoke(new MethodInvoker(() =>
             {
                 lbAgentStatus.Text      = "Агент не отчитывается в базу";
                 lbAgentStatus.BackColor = Color.Pink;
             }));
         }
         else
         {
             lbAgentStatus.Text      = "Агент не отчитывается в базу";
             lbAgentStatus.BackColor = Color.Pink;
         }
         return(false);
     }
     return(false);
 }
Ejemplo n.º 13
0
        public static SqlServerCheckResult CheckBases(string hostName)
        {
            var result = new SqlServerCheckResult();

            var baseData       = OptionsHelper.GetDataBaseOptions(hostName);
            var basesIgnorList = OptionsHelper.GetDatabasesNameToIgnor(hostName);

            if (!baseData.IsNesseseryToCheckSqlBases ||
                string.IsNullOrEmpty(baseData.Login) ||
                string.IsNullOrEmpty(baseData.Password))
            {
                result.ErrorMessage = $@"Checking of database on server '{hostName}' is not nesessary or login/password did not load";
                return(result);
            }
            var connection = new SqlConnection(
                $"user id={baseData.Login};" +
                $"password={baseData.Password};server={hostName};" +
                $"database=master; " +
                $"connection timeout=30");

            try
            {
                connection.Open();
                SqlDataReader reader    = null;
                SqlCommand    myCommand = new SqlCommand("select ssdb.name, ssdb.status, sdb.state_desc from sys.sysdatabases ssdb " +
                                                         "join sys.databases sdb on ssdb.name = sdb.name", connection);
                reader = myCommand.ExecuteReader();
                while (reader.Read())
                {
                    var baseName = reader["name"].ToString();
                    if (basesIgnorList?.Contains(baseName) ?? false)
                    {
                        continue;
                    }
                    var baseStatus       = ConvertSafe.ToInt32(reader["status"]);
                    var baseStatusSimple = reader["state_desc"].ToString();

                    var statuses = GetBaseStatusesByStatusCode(baseStatus);

                    if (
                        (
                            !(
                                statuses.Contains(Constants.DatabaseStates.ONLINE) ||
                                statuses.Contains(Constants.DatabaseStates.TRUNCATE_LOG_ON_CHKPT) ||
                                statuses.Contains(Constants.DatabaseStates.TORN_PAGE_DETECTION)
                                )
                        ) ||
                        baseStatusSimple.ToUpper() != Constants.DatabaseStates.SIMPLE_STATUS_ONLINE
                        )
                    {
                        statuses.Add(baseStatusSimple);

                        result.DataBaseInfoList.Add(new DataBaseInfoModel()
                        {
                            Name     = baseName,
                            Statuses = statuses
                        });
                    }
                }
            }
            catch (Exception e)
            {
                result.ErrorMessage = $"DataBase on server '{hostName}' get databases list error: {e.Message}";
                Logger.LogError($"Database error. ^^^Direct write to log^^^ ERROR:{result.ErrorMessage}{Environment.NewLine}Full error text: {e.ToString()}");
            }
            finally
            {
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                }
            }
            return(result);
        }