Example #1
0
        /// <summary>
        /// Handles the specified command request.
        /// </summary>
        /// <param name="commandRequest">The command request.</param>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException(nameof(commandRequest));
            }

            if (commandRequest.Command.ToUpperInvariant() != "CREATE")
            {
                this.NextHandler.Handle(commandRequest);
                return;
            }

            string   firstName = null;
            string   lastName  = null;
            DateTime dateOfBirth;
            short    department;
            decimal  salary;
            char     clas;

            this.ReadRecord(out firstName, out lastName, out dateOfBirth, out department, out salary, out clas);

            RecordParams recordParams = new RecordParams(firstName, lastName, dateOfBirth, department, salary, clas);
            int          id           = this.Service.CreateRecord(recordParams);

            Console.WriteLine("Record #{0} is created.", id);
            this.Service.MemEntity.Clear();
        }
Example #2
0
        /// <inheritdoc/>
        public int CreateRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException($"{nameof(recordParams)} must nit be null");
            }

            this.validator.ValidateCabinetRecord(recordParams);
            this.fileStream.Position = this.fileStream.Length;
            this.dictionaryId.Add(this.id + 1, this.fileStream.Position);
            AddToDictionary<string, long>(this.firstNameDictionary, recordParams.FirstName.ToUpperInvariant(), this.fileStream.Position);
            AddToDictionary<string, long>(this.lastNameDictionary, recordParams.LastName.ToUpperInvariant(), this.fileStream.Position);
            AddToDictionary<DateTime, long>(this.dateOfBirthDictionary, recordParams.DateOfBirth, this.fileStream.Position);

            byte[] tempFirstName = Encoding.Default.GetBytes(recordParams.FirstName);
            byte[] tempLastName = Encoding.Default.GetBytes(recordParams.LastName);
            byte[] firstName = new byte[120];
            byte[] lastName = new byte[120];
            ToBytesDecimal toBytesDecimal = new ToBytesDecimal(recordParams.Salary);
            byte[] bytesSalary = BitConverter.GetBytes(toBytesDecimal.Bytes1).Concat(BitConverter.GetBytes(toBytesDecimal.Bytes2)).ToArray();
            Array.Copy(tempFirstName, 0, firstName, 0, tempFirstName.Length);
            Array.Copy(tempLastName, 0, lastName, 0, tempLastName.Length);
            this.fileStream.Write(BitConverter.GetBytes(recordParams.Department));
            this.fileStream.Write(BitConverter.GetBytes(++this.id));
            this.fileStream.Write(firstName);
            this.fileStream.Write(lastName);
            this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Year));
            this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Month));
            this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Day));
            this.fileStream.Write(bytesSalary);
            this.fileStream.Write(BitConverter.GetBytes(recordParams.Class));
            this.fileStream.Write(new byte[] { 0 });
            return this.id;
        }
Example #3
0
        /// <summary>
        /// Edits the record and logs.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="recordParams">The record parameters.</param>
        public void EditRecord(int id, RecordParams recordParams)
        {
            var sw = Stopwatch.StartNew();

            this.service.EditRecord(id, recordParams);
            sw.Stop();
            Console.WriteLine("EditRecord method execution duration is {0} ticks", sw.ElapsedTicks);
        }
Example #4
0
        /// <summary>
        /// Creates the record and logs.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <returns>
        /// The identifier.
        /// </returns>
        public int CreateRecord(RecordParams recordParams)
        {
            var sw     = Stopwatch.StartNew();
            var result = this.service.CreateRecord(recordParams);

            sw.Stop();
            Console.WriteLine("CreateRecord method execution duration is {0} ticks", sw.ElapsedTicks);
            return(result);
        }
Example #5
0
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordsParams is null.</exception>
        /// <exception cref="ArgumentException">Throws when validate is false.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException(nameof(recordParams));
            }

            if (recordParams.DateOfBirth < this.from || recordParams.DateOfBirth > this.to)
            {
                throw new ArgumentException($"{nameof(recordParams.DateOfBirth)} shoud be between  01-Jan-1950 and now");
            }
        }
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordParams is null. </exception>
        /// <exception cref="ArgumentException">Throws when validate is false.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException(nameof(recordParams));
            }

            if (recordParams.Class < this.minClass || recordParams.Class > this.maxClass)
            {
                throw new ArgumentException($"{nameof(recordParams.Class)} should be between A and Z");
            }
        }
Example #7
0
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordParams is null.</exception>
        /// <exception cref="ArgumentException">Throws when validate is false.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException(nameof(recordParams));
            }

            if (recordParams.Department <= this.from || recordParams.Department >= this.to)
            {
                throw new ArgumentException($"{nameof(recordParams.Department)} should be more than zero");
            }
        }
        public Guid Post([FromBody] RecordParams recordParams)
        {
            var record = Guid.NewGuid();

            Task.Factory.StartNew(() =>
            {
                var initial = new RecordDataInitializer();
                initial.InitialRecordData(recordParams, record);
            });

            return(record);
        }
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordsParams is null.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException($"{nameof(recordParams)} must not be null");
            }

            foreach (var validator in this.validators)
            {
                validator.ValidateCabinetRecord(recordParams);
            }
        }
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordsParams is null.</exception>
        /// <exception cref="ArgumentException">Throws when validate is false.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException(nameof(recordParams));
            }

            if (recordParams.Salary <= this.minSalary || recordParams.Salary >= this.maxSalary)
            {
                throw new ArgumentException($"{nameof(recordParams.Salary)} must be more than zero");
            }
        }
Example #11
0
        /// <summary>
        /// Edits the record and measures time.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="recordParams">The record parameters.</param>
        public void EditRecord(int id, RecordParams recordParams)
        {
            string context = string.Format(CultureInfo.InvariantCulture, "{0} - Calling {1} with id = {2} {3}\n", DateTime.Now, "EditRecord()", id, recordParams);

            File.AppendAllText("logger.txt", context);
            try
            {
                this.service.EditRecord(id, recordParams);
            }
            catch (Exception e)
            {
                File.AppendAllText("logger.txt", e.ToString());
                throw;
            }
        }
        /// <summary>
        /// Validates the cabinet record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordsParams is null.</exception>
        /// <exception cref="ArgumentException">Throws when validate is false.</exception>
        public void ValidateCabinetRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException(nameof(recordParams));
            }

            if (string.IsNullOrWhiteSpace(recordParams.FirstName))
            {
                throw new ArgumentException($"{nameof(recordParams.FirstName)} must not be null or contain only spaces");
            }

            if ((recordParams.FirstName.Length < this.minLength) || (recordParams.FirstName.Length > this.maxLength))
            {
                throw new ArgumentException($"{nameof(recordParams.FirstName)} length should be between 2 and 60");
            }
        }
Example #13
0
        /// <summary>
        /// Creates the record and measures time.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <returns>
        /// The identifier.
        /// </returns>
        public int CreateRecord(RecordParams recordParams)
        {
            string context = string.Format(CultureInfo.InvariantCulture, "{0} - Calling {1} with {2}\n", DateTime.Now, "CreateRecord()", recordParams);

            File.AppendAllText("logger.txt", context);
            try
            {
                var    result        = this.service.CreateRecord(recordParams);
                string resultContext = string.Format(CultureInfo.InvariantCulture, "{0} - GetStat() returned \'{1}\'\n", DateTime.Now, result.ToString(CultureInfo.InvariantCulture));
                File.AppendAllText("logger.txt", resultContext);
                return(result);
            }
            catch (Exception e)
            {
                File.AppendAllText("logger.txt", e.ToString());
                throw;
            }
        }
Example #14
0
        private static void StartRecordProcess(Dictionary <string, string> recordConfigs, View.Progress progress, List <string> fileList)
        {
            var client       = new PostClient($"{ServerAddr}Record");
            var recordParams = new RecordParams
            {
                RecordConfigs = recordConfigs,
                FileList      = fileList,
                RecordName    = recordConfigs["RecordName"]
            };

            var processId = Guid.Parse(client.Post(JsonConvert.SerializeObject(recordParams)).Replace("\"", string.Empty));
            var stage     = string.Empty;

            client.SetParams($"{{record}}:{processId}");
            while (stage != RecordProcessStage.ProcessCompleted && stage != RecordProcessStage.Failed)
            {
                var fatchClient = new PostClient($"{ServerAddr}Record?record={processId}");
                stage = fatchClient.Get().Replace("\"", string.Empty);
                progress.UPdateProgressStage(stage);
                Thread.Sleep(1000);
            }

            progress.FinishUpload();
        }
        public void InitialRecordData(RecordParams recordParams, Guid stageId)
        {
            try
            {
                Stage.Add(stageId, RecordProcessStage.OnCreatingRecord);
                var recordRepo = Repo <PowerRepository <Record> >();
                var newRecord  = new Record
                {
                    RecordName          = recordParams.RecordName,
                    RecordStartDateTime = DateTime.Parse(recordParams.RecordConfigs["StartDateTime"]),
                    RecordDuration      = TimeSpan.Parse(recordParams.RecordConfigs["RecordDuration"]),
                    RecordEndDateTime   = DateTime.Parse(recordParams.RecordConfigs["EndDateTime"])
                };
                recordRepo.AddOrUpdateDoCommit(newRecord);
                newRecord.ModelState = ModelState.Changed;

                var configRepo = Repo <PowerRepository <SystemConfig> >();
                var configs    = configRepo.GetModelList(obj => obj.ConfigType == "RecordInitial")
                                 .ToDictionary(obj => obj.ConfigName, item => item.ConfigValue);

                var initialzation =
                    $"{newRecord.Id}\r\n{recordParams.RecordConfigs["Period"]}\r\n{recordParams.RecordConfigs["Frequency"]}\r\n{recordParams.RecordConfigs["LineType"]}";

                foreach (var file in Directory.GetFiles(configs["dataDirectory"]))
                {
                    if (!recordParams.FileList.Contains(Path.GetFileNameWithoutExtension(file)))
                    {
                        File.Delete(file);
                    }
                }

                if (Directory.GetFiles(configs["dataDirectory"]).Length != recordParams.FileList.Count)
                {
                    Stage[stageId] = RecordProcessStage.MissingFile;
                    return;
                }

                File.WriteAllText(configs["InitialzationFile"], initialzation);

                if (!Globals.IsProcessRunning(configs["MainProcessName"]))
                {
                    Process.Start(configs["MainProcessPath"]);
                }

                File.WriteAllText(configs["FinishFile"], "0");
                File.WriteAllText(configs["StartFile"], "1");

                Stage[stageId] = RecordProcessStage.OnCaclating;

                while (File.ReadAllText(configs["FinishFile"]).Substring(0, 1) != "1")
                {
                    Thread.Sleep(1000);
                }

                var config = new RecordConfig
                {
                    LineType      = (LineType)byte.Parse(recordParams.RecordConfigs["LineType"]),
                    CalcPrecision = ushort.Parse(recordParams.RecordConfigs["Period"]),
                    Frequency     = ushort.Parse(recordParams.RecordConfigs["SampleRate"]),
                    RecordId      = newRecord.Id
                };
                var ctx = new PowerDbContext();
                ctx.RecordConfigs.Add(config);
                ctx.SaveChanges();

                using (var connection = new MySqlConnection(configs["MySqlConnString"]))
                {
                    Stage[stageId] = RecordProcessStage.OnAfterCaclating;
                    connection.Open();
                    using (var transction = connection.BeginTransaction())
                    {
                        try
                        {
                            using (var loadCmd = connection.CreateCommand())
                            {
                                loadCmd.CommandType = CommandType.Text;
                                loadCmd.CommandText = $"LOAD DATA LOCAL INFILE '{configs["ActiveFilePath"]}' INTO TABLE activevalues";
                                loadCmd.ExecuteNonQuery();
                                loadCmd.CommandText = $"LOAD DATA LOCAL INFILE '{configs["HarmonicFilePath"]}' INTO TABLE harmonics";
                                loadCmd.ExecuteNonQuery();
                            }
                            using (var cmd = connection.CreateCommand())
                            {
                                cmd.CommandType    = CommandType.StoredProcedure;
                                cmd.CommandText    = "transferPowers";
                                cmd.CommandTimeout = int.MaxValue;
                                cmd.Parameters.Add(new MySqlParameter()
                                {
                                    DbType        = DbType.Int64,
                                    Direction     = ParameterDirection.Input,
                                    ParameterName = "relativeRecordId",
                                    Value         = newRecord.Id
                                });
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "calcvoltageseconds";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "calcvoltagethreeseconds";
                                cmd.ExecuteNonQuery();
                            }

                            transction.Commit();
                        }
                        catch (Exception ex)
                        {
                            transction.Rollback();
                            File.WriteAllText(configs["ActiveFilePath"], string.Empty);
                            File.WriteAllText(configs["HarmonicFilePath"], string.Empty);
                            LogService.Instance.Error("数据库操作执行失败。", ex);
                            Stage[stageId] = RecordProcessStage.Failed;
                            return;
                        }
                    }
                    File.WriteAllText(configs["ActiveFilePath"], string.Empty);
                    File.WriteAllText(configs["HarmonicFilePath"], string.Empty);
                    File.WriteAllText(configs["StartFile"], "0");
                }
                Stage[stageId]      = RecordProcessStage.ProcessCompleted;
                newRecord.Finalized = true;
                recordRepo.AddOrUpdateDoCommit(newRecord);
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("生成记录失败。", ex);
            }
        }
Example #16
0
        /// <summary>
        /// Edits the record.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="recordParams">The record parameters.</param>
        /// <exception cref="ArgumentNullException">Throws when recordParams is null.</exception>
        /// <exception cref="KeyNotFoundException">Throws when Id not found.</exception>
        public void EditRecord(int id, RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException($"{nameof(recordParams)} must nit be null");
            }

            this.validator.ValidateCabinetRecord(recordParams);
            byte[] buffer = new byte[277];
            this.fileStream.Position = 0;

            if (this.dictionaryId.ContainsKey(id))
            {
                long position = this.dictionaryId[id];
                this.fileStream.Position = position;
                this.fileStream.Read(buffer, 0, 277);
                FileCabinetRecord record = this.RecordFromBytes(buffer);

                if (record.FirstName.ToUpperInvariant() != recordParams.FirstName.ToUpperInvariant())
                {
                    this.firstNameDictionary[record.FirstName.ToUpperInvariant()].Remove(position);
                    AddToDictionary<string, long>(this.firstNameDictionary, recordParams.FirstName.ToUpperInvariant(), position);
                }

                if (record.LastName.ToUpperInvariant() != recordParams.LastName.ToUpperInvariant())
                {
                    this.lastNameDictionary[record.LastName.ToUpperInvariant()].Remove(position);
                    AddToDictionary<string, long>(this.lastNameDictionary, recordParams.LastName.ToUpperInvariant(), position);
                }

                if (record.DateOfBirth != recordParams.DateOfBirth)
                {
                    this.dateOfBirthDictionary[record.DateOfBirth].Remove(position);
                    AddToDictionary<DateTime, long>(this.dateOfBirthDictionary, recordParams.DateOfBirth, position);
                }

                this.fileStream.Position = position;

                byte[] tempFirstName = Encoding.Default.GetBytes(recordParams.FirstName);
                byte[] tempLastName = Encoding.Default.GetBytes(recordParams.LastName);
                byte[] firstName = new byte[120];
                byte[] lastName = new byte[120];
                ToBytesDecimal toBytesDecimal = new ToBytesDecimal(recordParams.Salary);
                byte[] bytesSalary = BitConverter.GetBytes(toBytesDecimal.Bytes1).Concat(BitConverter.GetBytes(toBytesDecimal.Bytes2)).ToArray();
                Array.Copy(tempFirstName, 0, firstName, 0, tempFirstName.Length);
                Array.Copy(tempLastName, 0, lastName, 0, tempLastName.Length);

                this.fileStream.Write(BitConverter.GetBytes(recordParams.Department));
                this.fileStream.Write(BitConverter.GetBytes(id));
                this.fileStream.Write(firstName);
                this.fileStream.Write(lastName);
                this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Year));
                this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Month));
                this.fileStream.Write(BitConverter.GetBytes(recordParams.DateOfBirth.Day));
                this.fileStream.Write(bytesSalary);
                this.fileStream.Write(BitConverter.GetBytes(recordParams.Class));
                this.fileStream.Write(new byte[] { 0 });
                this.fileStream.Position = this.fileStream.Length;

                return;
            }

            throw new KeyNotFoundException($"wrong {nameof(id)}");
        }
Example #17
0
        /// <summary>
        /// Handles the specified command request.
        /// </summary>
        /// <param name="commandRequest">The command request.</param>
        /// <exception cref="ArgumentNullException">Throws when commandRequest is null.</exception>
        public override void Handle(AppCommandRequest commandRequest)
        {
            if (commandRequest is null)
            {
                throw new ArgumentNullException(nameof(commandRequest));
            }

            if (commandRequest.Command.ToUpperInvariant() != "UPDATE")
            {
                this.NextHandler.Handle(commandRequest);
                return;
            }

            int subIndex   = commandRequest.Parameters.IndexOf(" where ", StringComparison.InvariantCultureIgnoreCase);
            int startIndex = commandRequest.Parameters.IndexOf("set ", StringComparison.InvariantCultureIgnoreCase);

            if (subIndex == -1)
            {
                Console.WriteLine("Missed where.");
                return;
            }

            if (startIndex == -1)
            {
                Console.WriteLine("Missed set.");
                return;
            }

            var param = commandRequest.Parameters.Substring(startIndex + 3, subIndex)
                        .Split(',', StringSplitOptions.RemoveEmptyEntries);

            string   firstName   = default;
            string   lastName    = default;
            DateTime dateOfBirth = default;
            short    department  = default;
            decimal  salary      = default;
            char     clas        = default;

            foreach (var record in param)
            {
                var values = record.Replace("=", " ", StringComparison.InvariantCultureIgnoreCase)
                             .Replace("\'", string.Empty, StringComparison.InvariantCultureIgnoreCase)
                             .Split(' ', StringSplitOptions.RemoveEmptyEntries);
                switch (values[0].ToUpperInvariant())
                {
                case "FIRSTNAME":
                    firstName = values[1];
                    break;

                case "LASTNAME":
                    lastName = values[1];
                    break;

                case "DATEOFBIRTH":
                    DateTime.TryParseExact(values[1], "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateOfBirth);
                    break;

                case "SALARY":
                    if (!decimal.TryParse(values[1], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out salary))
                    {
                        salary = default;
                    }

                    break;

                case "DEPARTMENT":
                    if (!short.TryParse(values[1], out department))
                    {
                        department = default;
                    }

                    break;

                case "CLASS":
                    if (!char.TryParse(values[1], out clas))
                    {
                        clas = default;
                    }

                    break;

                default:
                    break;
                }
            }

            RecordParams recordParams = new RecordParams();

            foreach (var record in this.Service.Where(commandRequest.Parameters.Substring(subIndex + 7)))
            {
                recordParams.FirstName   = firstName == default ? record.FirstName : firstName;
                recordParams.LastName    = lastName == default ? record.LastName : lastName;
                recordParams.DateOfBirth = dateOfBirth == default ? record.DateOfBirth : dateOfBirth;
                recordParams.Salary      = salary == default ? record.Salary : salary;
                recordParams.Department  = department == default ? record.Department : department;
                recordParams.Class       = clas == default ? record.Class : clas;

                this.Service.EditRecord(record.Id, recordParams);
            }

            this.Service.MemEntity.Clear();
        }