示例#1
0
        void frmSysSettings_Shown(object sender, EventArgs e)
        {
            string portName = string.Empty;
            string portBaut = string.Empty;
            string tcpPort  = string.Empty;

            object o = ConfigDB.getConfig("comportName");

            if (o != null)
            {
                portName = (string)o;
            }
            o = ConfigDB.getConfig("baudRate");
            if (o != null)
            {
                portBaut = (string)o;
            }
            o = ConfigDB.getConfig("tcp_port");
            if (o != null)
            {
                tcpPort = (string)o;
            }
            this.cmbPortName.Text = portName;
            this.cmbBaut.Text     = portBaut;
            this.txtPort.Text     = tcpPort;
        }
        public async Task <IActionResult> GetMoldSettingsAsync(int moldId, CancellationToken ct, bool expand = false)
        {
            if (moldId <= 0)
            {
                return(NotFound());
            }

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var mold = await db.Molds.AsNoTracking().Include(m => m.MoldSettings)
                           .Where(m => m.Controller.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync(m => m.ID == moldId, ct)
                           .ConfigureAwait(false);

                if (mold == null)
                {
                    return(NotFound());
                }

                if (!expand)
                {
                    return(Ok(mold.MoldSettings.ToDictionary(s => s.Offset, s => (ushort)s.Value)));
                }

                var rawdata = new ushort[mold.MoldSettings.Max(ms => ms.Offset) + 1];

                foreach (var ms in mold.MoldSettings)
                {
                    rawdata[ms.Offset] = ms.RawData;
                }

                return(Ok(rawdata));
            }
        }
示例#3
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            //保存重新设置的总车位时,需要与当前已使用的量做比较
            //如果设置的新量小于当前使用量,就不能保存
            try
            {
                int new_count = (int)this.numberCount.Value;
                if (new_count < staticClass.current_used_count)
                {
                    MessageBox.Show("当前使用的车位数量已经超过设置的最大数量,请将车位数设置的更大些!");
                }
                else
                {
                    staticClass.total_count = new_count;
                    ConfigDB.saveConfig("total_count", staticClass.total_count);
                }

                staticClass.comport_name = this.cmbPortName.Text;
                nsConfigDB.ConfigDB.saveConfig("comport_name", staticClass.comport_name);

                this.Close();

                if (this.last_form != null)
                {
                    this.last_form.refresh();
                }
            }
            catch (System.Exception ex)
            {
            }
        }
        void frmSysSetting_Load(object sender, EventArgs e)
        {
            string portName = string.Empty;
            string ip       = string.Empty;
            string tcpPort  = string.Empty;

            object o = ConfigDB.getConfig("comportName");

            if (o != null)
            {
                portName = (string)o;
            }
            o = ConfigDB.getConfig("ip");
            if (o != null)
            {
                ip = (string)o;
            }
            o = ConfigDB.getConfig("tcp_port");
            if (o != null)
            {
                tcpPort = (string)o;
            }
            this.cmbPortName.Text = portName;
            this.txtPort.Text     = tcpPort;
            this.txtIP.Text       = ip;
        }
        public async Task <IActionResult> DeleteMoldAsync(int id, CancellationToken ct)
        {
            if (id <= 0)
            {
                return(NotFound());
            }

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var mold = await db.Molds
                           .Where(m => m.Controller.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync(m => m.ID == id, ct)
                           .ConfigureAwait(false);

                if (mold == null)
                {
                    return(NotFound());
                }

                await db.Entry(mold).Collection(m => m.MoldSettings).LoadAsync(ct).ConfigureAwait(false);

                var mx = new MoldX(mold);

                db.MoldSettings.RemoveRange(mold.MoldSettings);
                db.Molds.Remove(mold);
                await db.SaveChangesAsync(ct).ConfigureAwait(false);

                return(Ok(mx));
            }
        }
        private void LoadMetaData(ConfigDB db)
        {
            DataTable dt = db.LoadMetaData();

            foreach (DataRow dr in dt.Rows)
            {
                int    projectID = Utility.Value(dr["_fk_ProjectID"], -1);
                string groupName = Utility.Value(dr["GroupName"], "Unknown");
                string varName   = Utility.Value(dr["VarName"], "Unknown");
                int    intVal    = Utility.Value(dr["IntValue"], -1);
                double floatVal  = Utility.Value(dr["FloatValue"], 0.0);
                string textVal   = Utility.Value(dr["TextValue"], "");
                string comment   = Utility.Value(dr["Comment"], "No Comment");

                if (!_metaData.ContainsKey(projectID))
                {
                    _metaData.Add(projectID, new Dictionary <string, Dictionary <string, MetaDataEntry> >(StringComparer.InvariantCultureIgnoreCase));
                }

                Dictionary <string, Dictionary <string, MetaDataEntry> > projectSet = _metaData[projectID];

                if (!projectSet.ContainsKey(groupName))
                {
                    projectSet.Add(groupName, new Dictionary <string, MetaDataEntry>(StringComparer.InvariantCultureIgnoreCase));
                }

                Dictionary <string, MetaDataEntry> group = projectSet[groupName];
                if (group.ContainsKey(varName))
                {
                    group.Remove(varName);
                }

                group[varName] = new MetaDataEntry(projectID, groupName, varName, floatVal, intVal, textVal);
            }
        }
        public async Task <IActionResult> DeleteControllerAsync(int id, CancellationToken ct)
        {
            if (id <= 0)
            {
                return(NotFound());
            }

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var controller = await db.Controllers
                                 .Where(c => c.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                                 .SingleOrDefaultAsync(c => c.ID == id, ct)
                                 .ConfigureAwait(false);

                if (controller == null)
                {
                    return(NotFound());
                }

                db.Controllers.Remove(controller);
                await db.SaveChangesAsync(ct).ConfigureAwait(false);

                return(Ok(new ControllerX(controller)));
            }
        }
        public void initData(bool IsFile)
        {
            if (IsFile)
            {
                //if (Debugger.IsAttached == false)
                //{
                    config = new ConfigDB();
                    config.load();
                //}
                //else
                //{
                //    config = new ConfigDB();
                //    config.server = "";
                //    config.databaseName = "";
                //    config.username = "";
                //    config.password = "";
                //    config.database = "";
                //}
            }

            //Check it
            if (config.database == "")
            {
                if(config.server.Equals("DATA-PROTOCOL")){
                    embDB.Checked = true;
                }

                textServerName.EditValue = config.server;
                textDatabase.EditValue = config.databaseName;
                textUsername.EditValue = config.username;
                textPassword.EditValue = config.password;
                Cong.Text = config.port + "";

                textServerName.Properties.ReadOnly = false;
                textDatabase.Properties.ReadOnly = false;
                textDatabase.Enabled = true;
                textUsername.Properties.ReadOnly = false;
                textPassword.Properties.ReadOnly = false;
                Cong.Properties.ReadOnly = false;

                btnSave.Text = "Lưu";
            }
            else if (config.database.StartsWith("Security"))
            {
                textServerName.EditValue = "-- protocolvn.com --";
                textDatabase.EditValue = "-- protocolvn.com --";
                textUsername.EditValue = "-- protocolvn.com --";
                textPassword.EditValue = "-- protocolvn.com --";
                Cong.Text = "3050";

                textServerName.Properties.ReadOnly = true;
                textDatabase.Properties.ReadOnly = true;
                textDatabase.Enabled = false;
                textUsername.Properties.ReadOnly = true;
                textPassword.Properties.ReadOnly = true;
                Cong.Properties.ReadOnly = true;

                btnSave.Text = "Mới";
            }
        }
示例#9
0
        public static string Login(string username, string password)
        {
            PruneSessions();

            if (string.IsNullOrWhiteSpace(username))
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                return(null);
            }

            username = username.Trim();
            password = password.Trim();

            // Get org ID if present: username can be "orgId\user"
            var orgId = DataStore.DefaultOrgId;
            var n     = username.IndexOf('\\');

            if (n > 0 && n < username.Length - 1)
            {
                orgId    = username.Substring(0, n).Trim();
                username = username.Substring(n + 1).Trim();
            }

            User user;

            using (var db = new ConfigDB()) {
                user = db.Users.AsNoTracking()
                       .Where(ux => ux.IsEnabled)
                       .Where(ux => ux.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                       .SingleOrDefault(ux => ux.Name.Equals(username, StringComparison.OrdinalIgnoreCase) && ux.Password.Equals(password, StringComparison.OrdinalIgnoreCase));

                if (user == null)
                {
                    return(null);
                }
            }

            lock (m_Sessions) {
                // Already logged in?
                var existing = m_Sessions.Values
                               .Where(ss => ss.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                               .Where(ss => ss.Name.Equals(username, StringComparison.OrdinalIgnoreCase))
                               .ToList();

                // Remove existing login's
                foreach (var ux in existing)
                {
                    m_Sessions.Remove(ux.SessionID);
                }

                // New login
                var guid = Guid.NewGuid().ToString().Replace("-", "").ToUpperInvariant();
                m_Sessions[guid] = new UserSession(guid, user);
                return(guid);
            }
        }
示例#10
0
        public async Task <IActionResult> LoginAsync(string user, string password)
        {
            if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(password))
            {
                return(BadRequest($"Missing user name or password for login."));
            }

            user     = user.Trim();
            password = password.Trim();

            // Get org ID if present: username can be "orgId\user"
            var orgId = DataStore.DefaultOrgId;
            var flds  = user.Split(UserNameSeparators, 2);

            if (flds.Length > 1 && !string.IsNullOrWhiteSpace(flds[0]) && !string.IsNullOrWhiteSpace(flds[1]))
            {
                orgId = flds[0].Trim();
                user  = flds[1].Trim();
            }

            User dbuser;

            using (var db = new ConfigDB()) {
                dbuser = db.Users.AsNoTracking()
                         .Where(ux => ux.IsEnabled)
                         .Where(ux => ux.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                         .SingleOrDefault(ux => ux.Name.Equals(user, StringComparison.OrdinalIgnoreCase) && ux.Password.Equals(password, StringComparison.OrdinalIgnoreCase));

                if (dbuser == null)
                {
                    return(Unauthorized());
                }
            }

            // Create Claims
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, dbuser.Name),
                new Claim(ClaimTypes.SerialNumber, dbuser.ID.ToString()),
                new Claim(ClaimTypes.UserData, dbuser.OrgId),
                new Claim(ClaimTypes.Role, "Org_" + dbuser.OrgId)
            };

            foreach (var key in Enum.GetNames(typeof(Filters)))
            {
                var filter = (Filters)Enum.Parse(typeof(Filters), key);
                if (dbuser.Filters.HasFlag(filter))
                {
                    claims.Add(new Claim(ClaimTypes.Role, key));
                }
            }

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

            var options = new AuthenticationProperties();

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, options).ConfigureAwait(false);

            return(Created("user", new LoggedInUser(principal)));
        }
        private SQLConfigSingleton(IOptions <ConfigDB> settings)
        {
            Configuration = settings.Value;
            //ConnectionString = "Data Source=.;Initial Catalog=MS_Order;User ID=sa;Password=sa@@@@@@;MultipleActiveResultSets=True";//Configuration[SQL_CONFIG];
            ConnectionString = Configuration.ConnectionString; //GetConnectionString(_SQL_CONFIG);

            ConnectDbTimeOut = 300;                            //int.Parse(Configuration[SQL_TIMEOUT]);
        }
        public async Task StartAsync()
        {
            var initialConfiguration = await ConfigDB.LoadAsync().ConfigureAwait(false);

            Bot            = new TelegramBotClient(initialConfiguration.BotToken);
            Bot.OnMessage += HandleMessage;
            Bot.StartReceiving();
        }
        public async Task <IActionResult> UpdateMoldSettingAsync(int moldId, int offset, [FromBody] MoldSettingX delta, CancellationToken ct)
        {
            if (moldId <= 0)
            {
                return(NotFound());
            }
            if (offset < 0)
            {
                return(NotFound());
            }
            if (delta.MoldId != 0)
            {
                return(BadRequest("Mold ID cannot be changed."));
            }
            if (delta.Offset != 0)
            {
                return(BadRequest("Offset cannot be changed."));
            }

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var mold = await db.Molds.AsNoTracking().Include(m => m.MoldSettings)
                           .Where(m => m.Controller.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync(m => m.ID == moldId, ct)
                           .ConfigureAwait(false);

                if (mold == null)
                {
                    return(NotFound());
                }

                var ms = await db.MoldSettings.SingleOrDefaultAsync(s => s.MoldId == moldId && s.Offset == offset, ct).ConfigureAwait(false);

                if (ms == null)
                {
                    return(NotFound());
                }

                if (delta.m_RawData.HasValue)
                {
                    ms.RawData = delta.RawData.Value;
                }

                if (delta.Variable.HasValue)
                {
                    ms.Variable = (delta.Variable.Value == 0) ? (int?)null : delta.Variable.Value;
                }

                delta.Modified = DateTime.Now;

                await db.SaveChangesAsync(ct).ConfigureAwait(false);

                return(Ok(new MoldSettingX(ms)));
            }
        }
 public FormForgotPass(string logUserId)
 {
     InitializeComponent();
     txtPassword.Enabled    = false;
     txtConfirmPass.Enabled = false;
     btnSave.Enabled        = false;
     sCode           = ConfigDB.LoadConfig(Config.ParamValues.RANDOM_CODE).CONF_VALUE;
     sUserId         = logUserId;
     this.isModified = false;
 }
示例#15
0
        public static bool SendMail(string strPathFile, string strTo, string strDisplayName, string strBodyRandom)
        {
            try
            {
                string strHost = "";
                var    config  = ConfigDB.LoadConfig(Config.ParamValues.DOMINIO_MAIL);
                if (config.CONF_VALUE == null)
                {
                    throw new Exception("Dominio mail non valido");
                }
                strHost = config.CONF_VALUE;

                if (!Mail.IsValidEmail(strTo))
                {
                    MessageBox.Show("L'indirizzo mail del destinatario non è valido", "Indirizzo Mail Non Valido", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(false);
                }

                config = ConfigDB.LoadConfig(Config.ParamValues.MITTENTE_MAIL);
                if (config.CONF_VALUE == null)
                {
                    throw new Exception("Indirizzo mail del mittente non è valido");
                }
                MailAddress from = new MailAddress(config.CONF_VALUE, config.CONF_VALUE);
                MailAddress to   = new MailAddress(strTo, strDisplayName);

                List <MailAddress> cc = new List <MailAddress>();
                //cc.Add(new MailAddress("*****@*****.**", "Name and stuff"));

                string strObject = "";
                string strBody   = strBodyRandom;

                if (string.IsNullOrEmpty(strBody))
                {
                    config = ConfigDB.LoadConfig(Config.ParamValues.OGGETTO_MAIL);
                    if (!string.IsNullOrEmpty(config.CONF_VALUE))
                    {
                        strObject = config.CONF_VALUE;
                    }

                    config = ConfigDB.LoadConfig(Config.ParamValues.TESTO_MAIL);
                    if (!string.IsNullOrEmpty(config.CONF_VALUE))
                    {
                        strBody = config.CONF_VALUE;
                    }
                }
                SendMail(strObject, strBody, strHost, strPathFile, from, to, cc);
                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Non è stato possibile inviare la mail.", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
        }
示例#16
0
 public void initData()
 {
     config = new ConfigDB();
     config.load();
     //Check it
     textServerName.EditValue = config.server;
     textDatabase.EditValue = config.databaseName;
     textUsername.EditValue = config.username;
     textPassword.EditValue = config.password;
     Cong.Text = config.port + "";
 }
        public async Task <IActionResult> AddMoldAsync([FromBody] MoldX mold, CancellationToken ct)
        {
            if (mold.ID != 0)
            {
                return(BadRequest("ID must be set to zero."));
            }

            if (string.IsNullOrWhiteSpace(mold.Name))
            {
                return(BadRequest($"Invalid mold name: [{mold.Name}]."));
            }
            if (mold.ControllerId.HasValue && mold.ControllerId <= 0)
            {
                return(BadRequest($"Invalid controller: {mold.ControllerId}."));
            }

            mold.Name     = mold.Name.Trim();
            mold.Modified = null;

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                if (mold.ControllerId.HasValue)
                {
                    var ctrl = await db.Controllers
                               .Where(c => c.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                               .SingleOrDefaultAsync(c => c.ID == mold.ControllerId, ct)
                               .ConfigureAwait(false);

                    if (ctrl == null)
                    {
                        return(NotFound());
                    }
                }
                var cx = await db.Molds.AsNoTracking()
                         .Where(m => m.ControllerId == mold.ControllerId)
                         .SingleOrDefaultAsync(m => m.Name.Equals(mold.Name, StringComparison.OrdinalIgnoreCase), ct)
                         .ConfigureAwait(false);

                if (cx != null)
                {
                    return(BadRequest($"Controller/Mold [{mold.ControllerId}/{mold.Name}] already exists."));
                }

                var mx = mold.GetBase();

                db.Molds.Add(mx);
                db.MoldSettings.AddRange(mx.MoldSettings);

                await db.SaveChangesAsync(ct).ConfigureAwait(false);

                return(Created($"molds/{mx.ID}", new MoldX(mx)));
            }
        }
        public IActionResult TestDB()
        {
            try {
                using (var db = new ConfigDB()) {
                    var nc = db.Controllers.Count();
                    var nu = db.Users.Count();

                    return(Ok($"{nc} controllers, {nu} users."));
                }
            } catch (Exception ex) {
                return(Ok(ex.ToString()));
            }
        }
示例#19
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            object o = ConfigDB.getConfig("portName");

            if (o != null)
            {
                portName = o as string;
            }
            frmMain = new main();
            Application.Run(frmMain);
        }
        public async Task <IActionResult> GetControllersAsync(CancellationToken ct)
        {
            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                return(Ok((await db.Controllers.AsNoTracking()
                           .Where(c => c.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .ToListAsync(ct)
                           .ConfigureAwait(false)
                           ).Select(c => new ControllerX(c))
                          .ToDictionary(c => c.ID)));
            }
        }
示例#21
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.checkValidation())
            {
                ConfigDB.saveConfig("wssUrl", this.txtIP.Text);
                //ConfigDB.saveConfig("port", this.txtPort.Text);

                sysConfig.wssUrl = this.txtIP.Text;
                //sysConfig.tcp_port = int.Parse(this.txtPort.Text);

                this.Close();
            }
        }
        public static void GetXML(Users user)
        {
            string strFilePath = FileService.CreateFolder(ConfigDB.LoadConfig(Config.ParamValues.DIRECTORY_XML).CONF_VALUE);

            //deve essere creata una nuova cartella dentro la quale andare a salvare il file chiamato sempre guest
            //string strFilePath = CaricaFileService.GetXMLPathFileToSave();
            if (string.IsNullOrEmpty(strFilePath))
            {
                return;
            }

            strFilePath = strFilePath + "\\Guest.xml";

            FileStream fileStream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);

            try
            {
                XmlSerializer     serializer = new XmlSerializer(typeof(EricsoftGuestData));
                EricsoftGuestData ericsofts  = LoadEricsoft(user);

                using (fileStream)
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    serializer.Serialize(fileStream, ericsofts, ns);

                    if (serializer == null)
                    {
                        throw new SerializationException();
                    }
                }
                if (!File.Exists(strFilePath))
                {
                    throw new ApplicationException(" File non esistente. ");
                }

                MessageBox.Show("File è stato correttamente salvato nella directory: " + strFilePath, "Export File", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ApplicationException e)
            {
                MessageBox.Show("Impossibile trovare il file nella posizione indicata. " + e.Message, "File non trovato", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (SerializationException e)
            {
                MessageBox.Show("Serializzazione fallita. Motivo: " + e.Message, "Export File", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                fileStream.Close();
            }
        }
        protected void Load(string dbHandle, ConfigDB db)
        {
            _clientName = ConfigurationManager.AppSettings["ClientName"];
            LoadMetaData(db);
            Logger.Log(true, "Loaded Meta Data...", EventLogEntryType.Information, false, true);
            _testEnv = db.LoadTestEnvironment();
            Logger.Log(true, "Loaded Test Environment...", EventLogEntryType.Information, false, true);
            LoadRTSAttributes(db);
            Logger.Log(true, "Loaded RTS Attributes Data...", EventLogEntryType.Information, false, true);

            int?longDbCommandTimeout = null;

            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["LongDbCommandTimeout"]))
            {
                longDbCommandTimeout = int.Parse(ConfigurationManager.AppSettings["LongDbCommandTimeout"]);
            }
            _configHolder[dbHandle] = new ScoringEngine.TestCollection(
                ConfigurationManager.ConnectionStrings["ITEMBANK"].ConnectionString,
                ConfigurationManager.AppSettings["ScoringEnvironment"],
                ClientName,
                longDbCommandTimeout);

            Logger.Log(true, "Initialized Scoring Engine...", EventLogEntryType.Information, false, true);

            _admins = db.LoadAdministration();

            //do some error checking on the TDSSessionDatabases key in the app.config
            _sessionDatabases = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
            //remove all whitespace and newlines from the value in the app settings
            Regex ptrn = new Regex(@"\s*", RegexOptions.Compiled | RegexOptions.CultureInvariant);

            _tdsSessionDatabasesValue = ptrn.Replace(ConfigurationManager.AppSettings["TDSSessionDatabases"] ?? "", "");

            if (string.IsNullOrEmpty(_tdsSessionDatabasesValue))
            {
                Logger.Log(true, "The key TDSSessionDatabases does not appear in the app.config file", EventLogEntryType.Information, false, true);
            }
            else
            {
                string[] dbsArr = _tdsSessionDatabasesValue.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String value in dbsArr)
                {
                    if (!_sessionDatabases.Add(value))
                    {
                        Logger.Log(true, "The TDSSessionDatabases value in the app.config file contains a duplicate entry: " + value, EventLogEntryType.Information, false, true);
                    }
                }
            }
            Logger.Log(true, "Loaded Administration and Server Name...Finished initializing configuration", EventLogEntryType.Information, false, true);
        }
        public async Task <IActionResult> GetMoldsAsync(CancellationToken ct)
        {
            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var mx = await db.Molds.AsNoTracking()
                         .Where(m => m.Controller.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                         .GroupBy(m => m.Name)
                         .ToDictionaryAsync(g => g.Key, g => g.ToDictionary(x => x.ControllerId.GetValueOrDefault(0), x => new MoldX(x)) as IReadOnlyDictionary <int, MoldX>)
                         .ConfigureAwait(false);

                return(Ok(mx));
            }
        }
示例#25
0
        static void initialSystem()
        {
            object oip = ConfigDB.getConfig("ip");

            if (oip != null)
            {
                staticClass.ip = (string)oip;
            }
            object oTcpPort = ConfigDB.getConfig("tcp_port");

            if (oTcpPort != null)
            {
                staticClass.tcp_port = int.Parse((string)oTcpPort);
            }
        }
示例#26
0
        static void initialConfig()
        {
            object o = null;

            o = ConfigDB.getConfig("ip");
            if (o != null)
            {
                sysConfig.restIp = (string)o;
            }
            o = ConfigDB.getConfig("port");
            if (o != null)
            {
                sysConfig.tcp_port = int.Parse((string)o);
            }
        }
        public async Task <IActionResult> GetUsersAsync(CancellationToken ct)
        {
            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var ux = (await db.Users.AsNoTracking()
                          .Where(user => user.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                          .ToListAsync(ct)
                          .ConfigureAwait(false)
                          ).Select(user => new UserX(user))
                         .ToList();

                return(Ok(ux));
            }
        }
 /// <summary>
 /// Load all needed DB based configuration data.
 /// </summary>
 /// <param name="dbHandle"></param>
 public virtual void Load(string dbHandle)
 {
     if (!IsLoaded)
     {
         lock (_syncLoc)
         {
             if (!IsLoaded)
             {
                 ConfigDB db = new ConfigDB(dbHandle);
                 Logger.Log(true, "Created ConfigDB...", EventLogEntryType.Information, false, true);
                 Load(dbHandle, db);
                 IsLoaded = true;
             }
         }
     }
 }
        public async Task <IActionResult> GetTerminalConfigFile(string orgScript, CancellationToken ct)
        {
            if (orgScript.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
            {
                orgScript = orgScript.Substring(0, orgScript.Length - 3);
            }
            if (string.IsNullOrWhiteSpace(orgScript))
            {
                return(BadRequest($"Invalid script name: {orgScript}"));
            }

            if (string.IsNullOrWhiteSpace(WebSettings.TerminalConfigFilePath))
            {
                return(BadRequest("No TerminalConfigFilePath specified."));
            }

            var filepath = Path.Combine(WebSettings.WwwRootPath, TerminalConfigRoute) + orgScript + ".js";

            if (filepath.Equals(WebSettings.TerminalConfigFilePath, StringComparison.OrdinalIgnoreCase) &&
                System.IO.File.Exists(WebSettings.TerminalConfigFilePath))
            {
                using (var stream = System.IO.File.OpenText(WebSettings.TerminalConfigFilePath)) {
                    var script = await stream.ReadToEndAsync().ConfigureAwait(false);

                    return(Content(script, "application/javascript", Encoding.UTF8));
                }
            }
            else if (WebSettings.DatabaseVersion >= ConfigDB.Version_TermialConfig)
            {
                using (var db = new ConfigDB(WebSettings.DatabaseSchema, WebSettings.DatabaseVersion)) {
                    var config = await db.TerminalConfigs.SingleOrDefaultAsync(c => c.OrgId.Equals(orgScript, StringComparison.OrdinalIgnoreCase), ct).ConfigureAwait(false);

                    if (config == null)
                    {
                        return(NotFound());
                    }

                    var script = "var Config = " + config.Text + ";";

                    return(Content(script, "application/javascript", Encoding.UTF8));
                }
            }
            else
            {
                return(NotFound());
            }
        }
        public async Task <IActionResult> AddMoldSettingAsync(int moldId, int offset, ushort value, int variable, CancellationToken ct)
        {
            if (moldId <= 0)
            {
                return(NotFound());
            }
            if (offset < 0)
            {
                return(NotFound());
            }

            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var mold = await db.Molds.AsNoTracking().Include(m => m.MoldSettings)
                           .Where(m => m.Controller.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync(m => m.ID == moldId, ct)
                           .ConfigureAwait(false);

                if (mold == null)
                {
                    return(NotFound());
                }

                var mx = await db.MoldSettings.SingleOrDefaultAsync(s => s.MoldId == moldId && s.Offset == offset, ct).ConfigureAwait(false);

                if (mx != null)
                {
                    return(BadRequest($"Mold/Offset [{moldId}/{offset}] already exists."));
                }

                var ms = new MoldSetting()
                {
                    MoldId   = moldId,
                    Offset   = (short)offset,
                    Created  = DateTime.Now,
                    RawData  = value,
                    Variable = variable
                };

                db.MoldSettings.Add(ms);
                await db.SaveChangesAsync(ct).ConfigureAwait(false);

                return(Created($"molds/{ms.MoldId}/settings", new MoldSettingX(ms)));
            }
        }
示例#31
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.checkValidation())
            {
                //string portName = this.cmbPortName.Text;
                string ip      = this.txtIP.Text;
                string tcpPort = this.txtPort.Text;
                //ConfigDB.saveConfig("comportName", portName);
                ConfigDB.saveConfig("ip", ip);
                ConfigDB.saveConfig("tcp_port", tcpPort);

                staticClass.rest_ip = ip;
                //sysConfig.comportName = portName;
                staticClass.rest_port = tcpPort;

                this.Close();
            }
        }
        public async Task <IActionResult> GetUserAsync(int id, CancellationToken ct)
        {
            var orgId = HttpContext.GetOrg();

            using (var db = new ConfigDB()) {
                var user = await db.Users.AsNoTracking()
                           .Where(x => x.OrgId.Equals(orgId, StringComparison.OrdinalIgnoreCase))
                           .SingleOrDefaultAsync(x => x.ID == id, ct)
                           .ConfigureAwait(false);

                if (user == null)
                {
                    return(NotFound());
                }

                return(Ok(new UserX(user)));
            }
        }
示例#33
0
        public void initData(bool IsFile)
        {
            if(IsFile){
                config = new ConfigDB();
                config.load();
            }

            //Check it
            if (config.database == "")
            {
                textServerName.EditValue = config.server;
                textDatabase.EditValue = config.databaseName;
                textUsername.EditValue = config.username;
                textPassword.EditValue = config.password;
                Cong.Text = config.port + "";

                textServerName.Properties.ReadOnly = false;
                textDatabase.Properties.ReadOnly = false;
                textDatabase.Enabled = true;
                textUsername.Properties.ReadOnly = false;
                textPassword.Properties.ReadOnly = false;
                Cong.Properties.ReadOnly = false;

                btnSave.Text = "Lưu";
            }
            else if (config.database.StartsWith("Security"))
            {
                textServerName.EditValue = "-- protocolvn.com --";
                textDatabase.EditValue = "-- protocolvn.com --";
                textUsername.EditValue = "-- protocolvn.com --";
                textPassword.EditValue = "-- protocolvn.com --";
                Cong.Text = "3050";

                textServerName.Properties.ReadOnly = true;
                textDatabase.Properties.ReadOnly = true;
                textDatabase.Enabled = false;
                textUsername.Properties.ReadOnly = true;
                textPassword.Properties.ReadOnly = true;
                Cong.Properties.ReadOnly = true;

                btnSave.Text = "Mới";
            }
        }
示例#34
0
        private void initData(bool IsFile)
        {
            if (IsFile)
            {
                //if (Debugger.IsAttached == false)
                //{
                    config = new ConfigDB();
                    config.load();
                //}
                //else
                //{
                //    config = new ConfigDB();
                //    config.server = "";
                //    config.databaseName = "";
                //    config.username = "";
                //    config.password = "";
                //    config.database = "";
                //}
            }

            if (config.server == dbEMBServer)
            {
                if (config.databaseName == DB_DEMO)
                {
                    chkCSDLMau.Checked = true;
                }
                else if (config.databaseName == DB_APP)
                {
                    embDB.Checked = true;
                }
            }
            else
            {
                chkCSDLTuXa.Checked = true;
            }

            //Check it
            if (config.database == "")
            {
                if (chkCSDLTuXa.Checked)
                {
                    textServerName.EditValue = config.server;
                    textDatabase.EditValue = config.databaseName;
                    textUsername.EditValue = config.username;
                    textPassword.EditValue = config.password;
                    Cong.Text = config.port + "";
                }
                else
                {
                    textServerName.EditValue = "";
                    textDatabase.EditValue = "";
                    textUsername.EditValue = "";
                    textPassword.EditValue = "";
                    Cong.Text = "";
                }

                textServerName.Properties.ReadOnly = false;
                textDatabase.Properties.ReadOnly = false;
                //textDatabase.Enabled = true;
                textUsername.Properties.ReadOnly = false;
                textPassword.Properties.ReadOnly = false;
                Cong.Properties.ReadOnly = false;

                btnSave.Text = "Lưu";
            }
            else if (config.database.StartsWith("Security"))
            {
                textServerName.EditValue = "-- protocolvn.com --";
                textDatabase.EditValue = "-- protocolvn.com --";
                textUsername.EditValue = "-- protocolvn.com --";
                textPassword.EditValue = "-- protocolvn.com --";
                Cong.Text = "3050";

                textServerName.Properties.ReadOnly = true;
                textDatabase.Properties.ReadOnly = true;
                //textDatabase.Enabled = false;
                textUsername.Properties.ReadOnly = true;
                textPassword.Properties.ReadOnly = true;
                Cong.Properties.ReadOnly = true;

                btnSave.Text = "Mới";

                chkCSDLTuXa.Enabled = false;
                chkCSDLMau.Enabled = false;
                embDB.Enabled = false;
            }
        }
示例#35
0
        //PHUOCNT NC Giải pháp chưa backup từ xa được để backup từ xa ta phải thay câu lệnh hiện tại thành câu lệnh
        //gbak -b -v protocolvn.info:E/mydb.gdb C:\mybackup.fbk -user SYSDBA -pass masterkey
        private bool backup(string FilePath)
        {
            ConfigDB config = new ConfigDB();
            config.load();
            #region usingGBACK
            if (frmBackupRestore.usingGBACK == true)
            {
                try
                {
                    string arg = "";
                    if (config.databaseName == "")
                        arg = " -v -t -user " + config.username + " -password \"" + config.password + "\" " + config.database + " " + FilePath;
                    else
                        arg = " -v -t -user " + config.username + " -password \"" + config.password + "\" " + config.databaseName + " " + FilePath;

                    ProcessStartInfo psi = new ProcessStartInfo("gbak.exe", arg);
                    psi.WindowStyle = ProcessWindowStyle.Hidden;
                    Process p = Process.Start(psi);
                    if (p == null) return false;
                    while (p != null && !p.HasExited)
                    {
                        //NOOP
                    }
                    return (p.ExitCode == 0);
                }
                catch (Exception ex)
                {
                    PLException.AddException(ex);
                    return false;
                }
            }
            #endregion
            #region usingFile
            else
            {
                try
                {
                    String dbFile = "";
                    if (config.databaseName == "")
                        dbFile = config.database;
                    else
                        dbFile = config.databaseName;

                    String dbCloneFile = "";
                    try
                    {
                        //Tạo 1 tập tin tương ứng với nội dung cần backup
                        //dbCloneFile = dbFile.Substring(0, dbFile.LastIndexOf(".")) + DateTime.Now.ToString("yyyyMMddHHmm")
                        //    + ".gdb";
                        dbCloneFile = RadParams.RUNTIME_PATH + "\\temp\\" + dbFile.Substring(dbFile.LastIndexOf("\\") + 1);
                        if (File.Exists(dbCloneFile)) File.Delete(dbCloneFile);
                        File.Copy(dbFile, dbCloneFile);

                        //Nén tập tin db lại
                        bool result = ZipFile.Zip(dbCloneFile, FilePath);

                        return result;
                    }
                    catch (Exception ex)
                    {
                        PLException.AddException(ex);
                    }
                    finally
                    {
                        //Xoa tập tin nếu đã tạo bảng sao.
                        try { if (File.Exists(dbCloneFile)) File.Delete(dbCloneFile); }
                        catch { }
                    }
                }
                catch (Exception ex)
                {
                    PLException.AddException(new PLException(ex));
                }
                //Using Zip
            }
            #endregion
            return false;
        }
示例#36
0
        //PHUOCNT NC Giải pháp hiện tại chưa phục hồi từ xa được
        //để làm được thay thành câu lệnh bên dưới
        //gbak -c -v C:/backup_file.fbk protocolvn.info:E:/new_db.gdb -user sysdba -pass masterkey
        private bool restore(string filePath)
        {
            ConfigDB config = new ConfigDB();
            config.load();
            #region Dùng GBACK
            if (frmBackupRestore.usingGBACK == true)
            {
                try
                {
                    string arg = "";
                    if (config.databaseName == "")
                    {
                        arg = " -r o -v -user " + config.username + " -password \"" + config.password + "\" " + filePath + " " + config.database + ".bak";
                    }
                    else
                        arg = " -r o -v -user " + config.username + " -password \"" + config.password + "\" " + filePath + " " + config.databaseName + ".bak";

                    ProcessStartInfo psi = new ProcessStartInfo("gbak.exe", arg);
                    psi.WindowStyle = ProcessWindowStyle.Hidden;
                    Process p = Process.Start(psi);
                    if (p == null) return false;
                    while (p != null && !p.HasExited)
                    {
                        //NOOP
                    }
                    return (p.ExitCode == 0);
                }
                catch (Exception ex)
                {
                    PLException.AddException(ex);
                    return false;
                }
            }
            #endregion
            #region
            else
            {
                //Chuẩn bị tham số
                string fullDBFileName = config.databaseName;
                string dbInfo = RadParams.server + ";" + RadParams.database + ";" + RadParams.port + ";" +
                    RadParams.username + ";" + RadParams.password + ";" + filePath + ";" + fullDBFileName;

                //Đóng chương trình
                FrameworkParams.ExitApplication(FrameworkParams.EXIT_STATUS.NORMAL_NO_THANKS);

                //Gọi restore.
                Process p = new Process();
                p.StartInfo.FileName = RadParams.RUNTIME_PATH + @"\update\RestoreDB.exe";
                p.StartInfo.Arguments = FrameworkParams.ExecuteFileName + ";" + dbInfo;
                try { p.Start(); } catch { }
            }
            #endregion
            return false;
        }