Esempio n. 1
0
        private string ReplaceVariableNamesWithVariableValues(string logicText)
        {
            // Koşul içerisindeki sinyal isimleri alınır.
            List <string> variables = StaticHelper.GetStringsBetweenGivenChar(logicText, '$');

            // Koşul içerisinde sinyal ismi varsa sinyallerin isimleri sinyal değerleri ile değiştirilir.
            if (variables.Count > 0)
            {
                // Koşul text'i içerisinde sinyal isimleri güncel değerleri ile değiştirilir.
                try
                {
                    foreach (string variable in variables)
                    {
                        string oldValue = string.Format("${0}$", variable);
                        string newValue = DBHelper_MailClient.GetSignalValueByIdentification(variable);
                        newValue = newValue.Replace(",", ".");

                        logicText = logicText.Replace(oldValue, newValue);
                    }

                    logicText = logicText.ToUpper();
                    logicText = logicText.Replace("FALSE", "0");
                    logicText = logicText.Replace("TRUE", "1");
                }
                catch
                {
                    return(null);
                }
            }

            return(logicText);
        }
Esempio n. 2
0
        private void DelRowButton_Click(object sender, EventArgs e)
        {
            try
            {
                int numberOfRow = чекdataGridView.CurrentRow.Index;

                DataTable tempDT = new DataTable();
                tempDT.Columns.Add("Код товара", typeof(int));
                tempDT.Columns.Add("Наименование", typeof(string));
                tempDT.Columns.Add("Цена", typeof(double));
                tempDT.Columns.Add("Количество", typeof(int));
                tempDT.Columns.Add("Стоимость", typeof(double));

                for (int i = 0; i < чекdataGridView.Rows.Count; i++)
                {
                    if (i != numberOfRow)
                    {
                        tempDT.Rows.Add(Convert.ToInt32(чекdataGridView.Rows[i].Cells[0].Value), Convert.ToString(чекdataGridView.Rows[i].Cells[1].Value), Convert.ToDouble(чекdataGridView.Rows[i].Cells[2].Value), Convert.ToInt32(чекdataGridView.Rows[i].Cells[3].Value), Convert.ToDouble(чекdataGridView.Rows[i].Cells[4].Value));
                    }
                    else
                    {
                    }
                }
                cheque = tempDT;
                чекdataGridView.DataSource = cheque;
                GetFullCost();
            }
            catch (Exception ex)
            {
                StaticHelper.ErrorNotifier(ex);
            }
        }
        private void ОсновноеМеню_Load(object sender, EventArgs e)
        {
            timer1.Interval  = 10;
            timer1.Enabled   = true;
            label1.Text      = "Сегодня " + DateTime.Now.ToLongDateString();
            this.Size        = Screen.PrimaryScreen.WorkingArea.Size;
            this.WindowState = FormWindowState.Maximized;


            this.Enabled = false;
            Авторизация f = new Авторизация();

            f.ShowDialog();
            if (User.Access == 1)
            {
                отчётыToolStripMenuItem.Visible     = false;
                управлениеToolStripMenuItem.Visible = false;
            }
            if (User.Access == 0)
            {
                try
                {
                    this.Dispose();
                }
                catch (Exception ex)
                {
                    StaticHelper.ErrorNotifier(ex);
                }
            }
            else if (User.Access == 1 || User.Access == 2)
            {
                this.Enabled = true;
            }
        }
        public async Task <IActionResult> DeleteTaskComment([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var taskComment = await IncludeAllComments().FirstOrDefaultAsync(x => x.Id == id);

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

            var role = StaticHelper.GetCurrentRole(User);

            if (role != "admin")
            {
                if (taskComment.User.Email != User.Identity.Name || taskComment.User == null)
                {
                    return(BadRequest());
                }
            }

            _context.TaskComments.Remove(taskComment);
            await _context.SaveChangesAsync();

            return(new JsonResult(taskComment));
        }
        public async Task <IActionResult> PutTaskComment([FromRoute] int id, [FromQuery] string content)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (content == null)
            {
                return(BadRequest("Content is required!"));
            }

            var taskComment = await IncludeAllComments().FirstOrDefaultAsync(x => x.Id == id);

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

            var role = StaticHelper.GetCurrentRole(User);

            if (role != "admin")
            {
                if (taskComment.User.Email != User.Identity.Name || taskComment.User == null)
                {
                    return(BadRequest());
                }
            }

            taskComment.Content = content;
            _context.Entry(taskComment).State = EntityState.Modified;

            await _context.SaveChangesAsync();

            return(NoContent());
        }
        internal void CopyArmy()
        {
            PlanArmy army = SelectedArmy.PlanArmy;

            army.PlanUnits.Clear();

            var armyItems = new List <PlanUnit>();

            foreach (PlanUnitViewModel armyItemVM in SelectedArmy.PlanUnits)
            {
                PlanUnit armyItem = armyItemVM.PlanUnit;

                armyItem.Options = armyItemVM.Options.Select(option => option.Option).ToList();

                army.PlanUnits.Add(armyItemVM.PlanUnit);
            }

            var copiedArmy = new PlanArmyViewModel()
            {
                PlanArmy = StaticHelper.DeepClone(army)
            };

            Armies.Add(copiedArmy);

            SelectedArmy = copiedArmy;
        }
Esempio n. 7
0
        public async Task<IActionResult> GetArticle([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var article = await IncludeAllArticle().
                FirstOrDefaultAsync(x => x.Id == id);

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

            var role = StaticHelper.GetCurrentRole(User);
            if(role == "client" || role == "superclient")
            {
                if(article.TypeId != 2)
                {
                    return BadRequest();
                }
            }

            return new JsonResult(article);
        }
Esempio n. 8
0
        public async Task <IActionResult> GetTickets([FromQuery] int?count, [FromQuery] int?offset, [FromQuery] int?priority, [FromQuery] int?status)
        {
            var role = StaticHelper.GetCurrentRole(User);

            var tickets = SortByRole(role, IncludeAllTicket());

            if (tickets == null)
            {
                return(BadRequest("No tickets was found for your account"));
            }
            if (priority != null)
            {
                tickets = tickets.Where(x => x.PriorityId == priority);
            }
            if (status != null)
            {
                tickets = tickets.Where(x => x.StatusId == status);
            }
            if (offset != null)
            {
                tickets = tickets.Skip((int)offset);
            }
            if (count != null)
            {
                tickets = tickets.Take((int)count);
            }

            return(Ok(tickets));
        }
Esempio n. 9
0
 private void TextboxGlobalHotkey_KeyDown(object sender, KeyEventArgs e)
 {
     TextboxGlobalHotkey.Clear();
     _currentHotkey.Key       = e.Key;
     _currentHotkey.Modifiers = StaticHelper.GetCurrentKeyModifiers();
     TextboxGlobalHotkey.Text = _currentHotkey.ToString();
 }
Esempio n. 10
0
        private void DeleteRowButton_Click(object sender, EventArgs e)
        {
            try
            {
                int numberOfRow = dataGridView2.CurrentRow.Index;

                DataTable tempDT = new DataTable();
                tempDT.Columns.Add("Код товара", typeof(int));
                tempDT.Columns.Add("Наименование", typeof(string));
                tempDT.Columns.Add("Цена закупки", typeof(double));
                tempDT.Columns.Add("Цена продажи", typeof(double));
                tempDT.Columns.Add("Количество", typeof(int));

                for (int i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    if (i != numberOfRow)
                    {
                        tempDT.Rows.Add(Convert.ToInt32(dataGridView2.Rows[i].Cells[0].Value), Convert.ToString(dataGridView2.Rows[i].Cells[1].Value), Convert.ToDouble(dataGridView2.Rows[i].Cells[2].Value), Convert.ToInt32(dataGridView2.Rows[i].Cells[3].Value), Convert.ToDouble(dataGridView2.Rows[i].Cells[4].Value));
                    }
                    else
                    {
                    }
                }
                IncomingGoodsDataTable   = tempDT;
                dataGridView2.DataSource = IncomingGoodsDataTable;
            }
            catch (Exception ex)
            {
                StaticHelper.ErrorNotifier(ex);
            }
        }
Esempio n. 11
0
 public bool Create()
 {
     try
     {
         if (Id != 0)
         {
             log.Error("Se intentó crear LoopTask con Id ya existente. ID: " + Id);
             throw new Exception();
         }
         else
         {
             Data.LOOP_TASK loopTask = new Data.LOOP_TASK();
             loopTask.ID_TASK_ASSIGNMENT = TaskAssignment.Id;
             loopTask.STARTTIME          = StartTime;
             loopTask.ENDTIME            = EndTime;
             loopTask.ISACTIVE           = StaticHelper.BoolToShort(Isactive);
             Connection.ProcessSA_DB.LOOP_TASK.Add(loopTask);
             Connection.ProcessSA_DB.SaveChanges();
             Id = (int)loopTask.ID;
             return(true);
         }
     }
     catch (Exception e)
     {
         log.Error("Ha ocurrido un error durante la creación de LoopTask de la tarea " + TaskAssignment.Task.Id, e);
         return(false);
     }
 }
Esempio n. 12
0
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                Данные_для_прихода f = new Данные_для_прихода(BuyPriceNumericUpDown, AmountNumericUpDown);
                f.ShowDialog();
                if (AmountNumericUpDown.Value != 0)
                {
                    int    codeOfGood  = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
                    string title       = Convert.ToString(dataGridView1.CurrentRow.Cells[3].Value);
                    double priceOfBuy  = Convert.ToDouble(BuyPriceNumericUpDown.Value);
                    double priceOfSell = Convert.ToDouble(dataGridView1.CurrentRow.Cells[4].Value);
                    int    amount      = Convert.ToInt32(AmountNumericUpDown.Value);

                    AddRow(codeOfGood, title, priceOfBuy, priceOfSell, amount);


                    AmountNumericUpDown.Value    = 1;
                    BuyPriceNumericUpDown.Value  = 0;
                    SellPriceNumericUpDown.Value = 0;
                }
            }
            catch (Exception ex)
            {
                StaticHelper.ErrorNotifier(ex);
            }
        }
Esempio n. 13
0
 private void FireButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (label1.Visible == false)
         {
             ControlExtraControls(true);
         }
         else
         {
             var result = MessageBox.Show("Вы уверены, что хотите уволить этого сотрудника?", "Подтверждение увольнения", MessageBoxButtons.YesNo);
             if (result == DialogResult.Yes)
             {
                 string       Command      = "Update Сотрудники SET Уволен=@fired Where Код_Сотрудника=@codeOfWorker";
                 SqlParameter fired        = new SqlParameter("fired", FiredDatePicker.Value.ToShortDateString());
                 SqlParameter codeOfWorker = new SqlParameter("codeOfWorker", Convert.ToString(сотрудникиDataGridView.CurrentRow.Cells[0].Value));
                 StaticProcesser.ExecuteCommand(Command, fired, codeOfWorker);
                 сотрудникиTableAdapter.Fill(this.bookWorldDataSet.Сотрудники);
                 ControlExtraControls(false);
             }
             else
             {
                 ControlExtraControls(false);
             }
         }
     }
     catch (Exception ex)
     {
         StaticHelper.ErrorNotifier(ex);
     }
 }
Esempio n. 14
0
        public AbstractDriver(string _configFile) : this()
        {
            Stations = new List <Station>();

            //Default haberleşme ayarları
            SetDefaultCommunicationParameters();

            try
            {
                DBHelper = StaticHelper.InitializeDatabase(Constants.DatabaseConfigFileLocation);
                if (DBHelper != null)
                {
                    // Config dosyasından haberleşme ayarları ve istasyon isimleri çekiliyor
                    ReadDriverConfigFile(_configFile);

                    // Station'lara ait device'lar ve device'lara ait sinyallar veritabanından okunur.
                    // Child sınıfta burayı ekle
                    GetStationDevicesAndSignalsInfo();
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error("{0}: Beklenmedik bir hata nedeniyle sürücü oluşturulamadı. => {1}", this.GetType().Name, ex.Message);
                throw;
            }
        }
Esempio n. 15
0
        private void HandleMenuClickGuidance(Microsoft.Office.Core.CommandBarButton clickedControl, ref bool cancelDefault)
        {
            string[] idParts     = clickedControl.DescriptionText.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
            string   guidanceUrl = StaticHelper.GetGuidanceUrl(idParts[0]);

            System.Diagnostics.Process.Start(guidanceUrl);
        }
        public int UpdateHouseAddress(HouseAddressViewModel model)
        {
            try
            {
                var recordToUpdateInDb = dbContext.TblHouseAddress.Where(x => x.Id == model.HouseId).FirstOrDefault();
                if (recordToUpdateInDb != null)
                {
                    var duplicateNameRecord = dbContext.TblHouseAddress.Where(x => x.Id != model.HouseId &&
                                                                              x.HouseNo == model.HouseNo &&
                                                                              x.SectorId == model.SectorID).FirstOrDefault();

                    if (duplicateNameRecord != null)
                    {
                        return(0);
                    }
                    else
                    {
                        recordToUpdateInDb.HouseNo  = model.HouseNo;
                        recordToUpdateInDb.SectorId = model.SectorID;
                        return(dbContext.SaveChanges());
                    }
                }
                else
                {
                    return(0);
                }
            }
            catch (Exception ex)
            {
                StaticHelper.LogException(path: up.GetLogFilePath(), errorMessage: ex.Message, methodName: $"Repository name: {nameof(FileRepository)} - Method name:  {nameof(UpdateHouseAddress)}", stackTrace: ex.StackTrace);
                return(0);
            }
        }
 // bad
 public void Test()
 {
     if (StaticHelper.StaticCompare("a", "b"))
     {
         Console.WriteLine();
     }
 }
Esempio n. 18
0
    // Update is called once per frame
    void Update()
    {
        if (isChasing == true && IsActiveInGame && Vector3.Distance(transform.position, Globals.Inst.transform.position) < MaxRange)
        {
            if (!UseRaycastVision || (UseRaycastVision && RaycastPlayer()))
            {
                transform.rotation = StaticHelper.LookAt2D(transform.position, Globals.Inst.Player.transform.position);
                GetComponent <Rigidbody2D>().velocity = transform.up.normalized * ChaseSpeed;
            } //else the enemy doesn't see the player
            else
            {
                GetComponent <Rigidbody2D>().velocity = Vector2.zero;
            }
        }

        if (Health == 0)
        {
            Destroy(gameObject);
        }

        if (!isColliding)
        {
            StopCoroutine("detractHealth");
        }
    }
Esempio n. 19
0
 public IActionResult GetArticles([FromQuery] int? sectionId, [FromQuery] int? count, [FromQuery] int? offset, [FromQuery] int? typeId)
 {
     var articles = IncludeAllArticle();
     var role = StaticHelper.GetCurrentRole(User);
     if(role == "client" || role == "superclient")
     {
         typeId = 2;
     }
     if(sectionId != null)
     {
         articles = articles.Where(x => x.SectionId == sectionId);
     }
     if(typeId != null)
     {
         articles = articles.Where(x => x.TypeId == typeId);
     }
     if(offset != null)
     {
         articles = articles.Skip((int)offset);
     }
     if(count != null)
     {
         articles = articles.Take((int)count);
     }
     return new JsonResult(articles);
 }
Esempio n. 20
0
    // Update is called once per frame
    void Update()
    {
        if (IsActiveInGame && Vector3.Distance(transform.position, Globals.Inst.Player.transform.position) < MaxViewRange)
        {
            transform.rotation = StaticHelper.LookAt2D(transform.position, Globals.Inst.Player.transform.position);

            if (
                (!UseRaycastVision || (UseRaycastVision && RaycastPlayer())) &&
                Vector3.Distance(transform.position, Globals.Inst.Player.transform.position) < maxShootRange &&
                Vector3.Distance(transform.position, Globals.Inst.Player.transform.position) > minRange)
            {
                if (GetComponent <Rigidbody2D>().velocity.magnitude > 0)
                {
                    GetComponent <Rigidbody2D>().velocity = Vector2.zero;
                }
                isChasing = false;
                if (GetComponent <BaseWeapon>())
                {
                    GetComponent <BaseWeapon>().TryToFire();
                }
            }
            else
            {
                isChasing = true;
                GetComponent <Rigidbody2D>().velocity = transform.up.normalized * ChaseSpeed;
            }

            /*
             * if (Health == 0)
             * {
             *  Destroy(gameObject);
             * }
             */
        }
    }
Esempio n. 21
0
        public MainWindow(bool hasStartupArgs = false, string[] startupArgs = null)
        {
            _isInitializing              = true;
            _hasStartupArgs              = hasStartupArgs;
            _startupArgs                 = startupArgs;
            _pipeServer                  = new AsyncPipeServer();
            _pipeServer.MessageRecieved += new ServerMessage(MessageRecievedHandler);
            InitializeComponent();
            ClippySettings.Instance.InitializeSettings();
            ClipDataManager.Instance.ItemsChanged += ItemsChangedHandler;

            SetupWindow();
            Action hotkeyPressed = GlobalHotkeyPressed;
            var    interopHelper = new WindowInteropHelper(this);

            interopHelper.EnsureHandle();
            HotKeyHelper.Instance.Initialize(interopHelper.Handle, hotkeyPressed);

            LoadItemsList();
            ApplySettings();
            string pipeName = StaticHelper.GetPipeName();

            _pipeServer.Listen(pipeName);
            _isInitializing = false;
        }
        public int UpdateMessr(TblMessrs model)
        {
            try
            {
                var recordToUpdateInDb = dbContext.TblMessrs.Where(x => x.Id == model.Id).FirstOrDefault();
                if (recordToUpdateInDb != null)
                {
                    var duplicateNameRecord = dbContext.TblMessrs.Where(x => x.Id != model.Id &&
                                                                        (x.PhoneNo == model.PhoneNo ||
                                                                         x.Cnic == model.Cnic)).FirstOrDefault();

                    if (duplicateNameRecord != null)
                    {
                        return(0);
                    }
                    else
                    {
                        recordToUpdateInDb.Name    = model.Name;
                        recordToUpdateInDb.PhoneNo = model.PhoneNo;
                        recordToUpdateInDb.Cnic    = model.Cnic;
                        return(dbContext.SaveChanges());
                    }
                }
                else
                {
                    return(0);
                }
            }
            catch (Exception ex)
            {
                StaticHelper.LogException(path: up.GetLogFilePath(), errorMessage: ex.Message, methodName: $"Repository name: {nameof(ReceiptRepository)} - Method name:  {nameof(UpdateMessr)}", stackTrace: ex.StackTrace);
                return(0);
            }
        }
Esempio n. 23
0
        public IActionResult GetTaskComments([FromQuery] int?taskId)
        {
            if (taskId == null)
            {
                return(BadRequest("Task ID is required!"));
            }

            var task = _context
                       .TicketTasks
                       .Include(x => x.User)
                       .FirstOrDefault(x => x.Id == taskId);

            if (task == null)
            {
                return(NotFound("Task with such id doesn't exists!"));
            }

            var role = StaticHelper.GetCurrentRole(User);

            if (!StaticHelper.CheckTaskByRole(role, task, User.Identity.Name, _context))
            {
                return(BadRequest());
            }

            var taskComments = IncludeAllComments().Where(x => x.TaskId == taskId);

            return(new JsonResult(taskComments));
        }
 private void EnterButton_Click(object sender, EventArgs e)
 {
     try
     {
         if ((FioTextBox.Text != "" || FioTextBox.Text != " ") && (PhoneNumberTextBox.Text != "" || PhoneNumberTextBox.Text != " "))
         {
             SqlParameter fio         = new SqlParameter("fio", FioTextBox.Text);
             SqlParameter phoneNumber = new SqlParameter("phoneNumber", PhoneNumberTextBox.Text);
             string       Command;
             if (isChange)
             {
                 Command = "Update Постоянные_Клиенты SET ФИО = @fio, Телефон = @phoneNumber WHERE Номер_Карты = @cardNumber";
                 SqlParameter cardNumber = new SqlParameter("cardNumber", CardNumber);
                 StaticProcesser.ExecuteCommand(Command, fio, phoneNumber, cardNumber);
                 this.Dispose();
             }
             else
             {
                 Command = "Insert Into Постоянные_Клиенты (ФИО,Дата_Вручения,Телефон) VALUES (@fio,@date,@phoneNumber)";
                 SqlParameter date = new SqlParameter("date", DateTime.Now.ToShortDateString());
                 StaticProcesser.ExecuteCommand(Command, fio, date, phoneNumber);
                 this.Dispose();
             }
         }
         else
         {
             MessageBox.Show("Заполните все поля!");
         }
     }
     catch (Exception ex)
     {
         StaticHelper.ErrorNotifier(ex);
     }
 }
Esempio n. 25
0
 private void FormReportButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (ReportsComboBox.SelectedIndex == 0)
         {
             StaticProcesser.FillDataGrid(CommandForReportAboutSupply, ReportDataGrid);
         }
         if (ReportsComboBox.SelectedIndex == 1)
         {
             CommandForReportAboutGenres = "Select Жанры.Наименование, SUM(Количество) AS Количество  FROM Товары right join Состав_Продажи ON Состав_Продажи.Код_Товара = Товары.Код_Товара inner join Жанры ON Код_Жанра = Товары.Жанр inner join Продажа ON Продажа.Чек = Состав_Продажи.Чек Where Продажа.Дата>='" + StartDatePicker.Value.ToShortDateString() + "' And Продажа.Дата<='" + EndDatePicker.Value.ToShortDateString() + "' GROUP BY Жанры.Наименование";
             StaticProcesser.FillDataGrid(CommandForReportAboutGenres, ReportDataGrid);
         }
         if (ReportsComboBox.SelectedIndex == 2)
         {
             CommandForReportAboutTypes = "Select Тип_Товара.Наименование, SUM(Количество) AS Количество FROM Товары right join Состав_Продажи ON Состав_Продажи.Код_Товара = Товары.Код_Товара inner join Тип_Товара ON Тип_Товара.Код_Типа=Товары.Тип_Товара inner join Продажа ON Продажа.Чек=Состав_Продажи.Чек Where Продажа.Дата>='" + StartDatePicker.Value.ToShortDateString() + "' and Продажа.Дата<='" + EndDatePicker.Value.ToShortDateString() + "' GROUP BY Тип_Товара.Наименование";
             StaticProcesser.FillDataGrid(CommandForReportAboutTypes, ReportDataGrid);
         }
         if (ReportsComboBox.SelectedIndex == 3)
         {
             CommandForReportAboutFinance = "SELECT (Select SUM(Цена_Закупки*Количество)From Состав_Прихода left join Приход ON Приход.Номер_Прихода=Состав_Прихода.Номер_Прихода Where Приход.Дата>='" + StartDatePicker.Value.ToShortDateString() + "' and Приход.Дата<='" + EndDatePicker.Value.ToShortDateString() + "') AS [Сумма затрат на товары],(Select SUM(Сумма_Чека) FROM Продажа Where Дата>='" + StartDatePicker.Value.ToShortDateString() + "' and Дата<='" + EndDatePicker.Value.ToShortDateString() + "') AS [Выручка от продаж]";
             StaticProcesser.FillDataGrid(CommandForReportAboutFinance, ReportDataGrid);
         }
     }
     catch (Exception ex)
     {
         StaticHelper.ErrorNotifier(ex);
     }
 }
        public void Guidance(IRibbonControl control)
        {
            string[] idParts     = control.Id.Split(new[] { StaticHelper.SplitSequence }, StringSplitOptions.RemoveEmptyEntries);
            string   guidanceUrl = StaticHelper.GetGuidanceUrl(idParts[0]);

            System.Diagnostics.Process.Start(guidanceUrl);
        }
Esempio n. 27
0
        private static async Task <KelinciData> ReadKelinciDataAsync(NetworkStream stream, CancellationToken token)
        {
            byte[] mode   = new byte[1];
            byte[] length = new byte[4];
            try
            {
                //Read first Byte   ==> Mode
                int  bytesRead = stream.Read(mode, 0, 1);
                bool success   = (bytesRead == 1);
                Logger.Trace("{0} Mode bytes read", bytesRead);
                //Read next 4 Bytes ==> Length
                bytesRead = stream.Read(length, 0, 4);
                success   = success && (bytesRead == 4);
                Logger.Trace("{0} Length bytes read", bytesRead);
                //Read Bytes        ==> Data
                byte[] data = new byte[StaticHelper.ConvertLittleEndian(length)];

                int i = 0;
                while ((i != data.Length) && (!token.IsCancellationRequested))
                {
                    i += await stream.ReadAsync(data, i, data.Length - i, token);
                }

                if (success)
                {
                    return(new KelinciData(StaticHelper.ConvertLittleEndian(mode), StaticHelper.ConvertLittleEndian(length), data));
                }
                throw new IOException("ReadKelinciData failed");
            }
            catch (Exception e)
            {
                Logger.Error("Exception: {0}", e.ToString());
                return(null);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActionResult Update(int Id)
        {
            MemberTypeDto dto = _memberTypeContract.Edit(Id);

            ViewBag.Discount = StaticHelper.DiscountList("选择折扣");
            return(PartialView(dto));
        }
        public async Task <IActionResult> DeleteArticleAttachment([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var articleAttachment = await IncludeAllAttachments().FirstOrDefaultAsync(x => x.Id == id);

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

            var role    = StaticHelper.GetCurrentRole(User);
            var current = _context.Users.FirstOrDefault(x => x.Email == User.Identity.Name);

            if (current == null)
            {
                return(BadRequest());
            }
            if (role != "admin" & articleAttachment.Article.UserId != current.Id)
            {
                return(BadRequest());
            }

            _context.ArticleAttachments.Remove(articleAttachment);
            await _context.SaveChangesAsync();

            return(new JsonResult(articleAttachment));
        }
Esempio n. 30
0
        public async Task <IActionResult> GenerateClientLink([FromQuery] int?roleId, [FromQuery] string email)
        {
            var role = StaticHelper.GetCurrentRole(User);

            if (roleId != 5)
            {
                roleId = 4;
            }
            if (email == null)
            {
                return(BadRequest("Email is required!"));
            }
            if (StaticHelper.IsEmailInBase(email, db))
            {
                return(BadRequest("Provided email is already registred or occupied!"));
            }
            var regLink = new RegistrationToken()
            {
                RoleId = (int)roleId,
                Type   = "Client",
                Email  = email,
                Token  = Guid.NewGuid().ToString("N"),
                Opened = DateTime.Now
            };

            db.RegistrationTokens.Add(regLink);
            await db.SaveChangesAsync();

            return(Ok(regLink));
        }