public SaveResult<UserViewModel> ChangePassword(string email, string oldPassword, string newPassword, Guid? resetKey = null)
        {
            var result = new SaveResult<UserViewModel>();
            var user = this._userManager.Get(email);

            if (user == null)
            {
                Logger.Log("No user found for e-mail " + email, LogLevel.Error);
                return result;
            }

            result.Success = this._securityManager.ChangePassword(user.Id, oldPassword, newPassword, resetKey);

            if (result.Success)
            {
                this.SaveChanges();
                if (!this._mailer.SendPasswordSetMail(user.PreferredCulture, user.Name, user.Email))
                {
                    result.Message = Resources.Interface.ErrorSendingPasswordChangedMail;
                    Logger.Log(string.Format("An error occurred while sending the password changed mail to user {0}", user.Name), LogLevel.Error);
                }
            }

            return result;
        }
Exemplo n.º 2
0
        /// <summary>
        /// 保存数据
        /// </summary>
        protected override SaveResult SaveData()
        {
            SaveResult saveResult = SaveResult.Fail;
            bool       result     = ChargeInfoService.ClientInstance.SaveValuationList(new List <MED_ANES_VALUATION_LIST>(tmpValuationList));

            if (result)
            {
                saveResult = SaveResult.Success;
            }

            foreach (var item in tmpValuationList)
            {
                item.ModelStatus = ModelStatus.Default;
            }

            return(saveResult);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] SageVM sage)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(SaveResult.Fail(ModelState.ToValidationMessages())));
            }

            var user = await _sageQuery.GetByIdAsync(sage.Id);

            sage.UpdateUser(user);

            await _sageCommand.UpdateAsync(user);

            _logger.LogInformation("Sage " + sage.Name + " [id: " + sage.Id + "] updated by " /* + _userHelper.UserName*/);

            return(Ok(SaveResult.Success(user.Id)));
        }
        public async Task <SaveResult> Save(InvoicesReturn InvoicesReturn)
        {
            SaveResult saveRlt = new SaveResult();

            saveRlt.UniqueKey = InvoicesReturn.ZFPHM;//回传接收方的主键
            using (IDbConnection conn = SqlConnectionFactory.CreateSqlConnection())
            {
                conn.Open();
                IDbTransaction dbTransaction = conn.BeginTransaction();
                try
                {
                    string insertSql = $@"INSERT INTO [@AVA_INVRETURN] (Code,Name,U_ZFPDM,U_ZKPRQ,U_ZFPZT,U_ZFPJE,U_ZSKPH)
                                            VALUES (
                                            '{InvoicesReturn.ZFPHM}',
                                            '{InvoicesReturn.ZFPHM}',
                                            '{InvoicesReturn.ZFPDM}',
                                            '{InvoicesReturn.ZKPRQ}',
                                            '{InvoicesReturn.ZFPZT}',
                                            '{InvoicesReturn.ZFPJE}',
                                            '{InvoicesReturn.ZSKPH}')";

                    //string insertSql = $@"INSERT INTO [@AVA_INVRETURN] (Code,Name,U_ZFPDM,U_ZKPRQ,U_ZFPZT,U_ZFPJE,U_ZSKPH)
                    //                        VALUES (@Code,@Name,@U_ZFPDM,@U_ZKPRQ,@U_ZFPZT,@U_ZFPJE,@U_ZSKPH)";
                    var rt = await conn.ExecuteScalarAsync(insertSql, null, dbTransaction);

                    //await conn.ExecuteAsync(insertSql);


                    saveRlt.ReturnUniqueKey = InvoicesReturn.ZFPHM;//回传保存订单的主键
                    dbTransaction.Commit();
                    saveRlt.Code = 0;
                }
                catch (Exception ex)
                {
                    dbTransaction.Rollback();
                    saveRlt.Code    = 1;
                    saveRlt.Message = ex.Message;
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
                return(saveRlt);
            }
        }
Exemplo n.º 5
0
        public async Task <SaveResult> SaveEntityList(MessageTemplateViewModel model, MessageTemplate parentEntity)
        {
            SaveResult saveResult = new SaveResult();

            var currentEntities = parentEntity.ApplicationRoleMessageTemplates;

            if (model.RoleIds == null)
            {
                if (currentEntities.Any())
                {
                    var ApplicationRoleMessageTemplateIds = currentEntities.ToList().ToList().Select(b => b.Id);

                    var toDeleteList = _context.ApplicationRoleMessageTemplate.Where(a => ApplicationRoleMessageTemplateIds.Contains(a.Id));

                    _context.ApplicationRoleMessageTemplate.RemoveRange(toDeleteList);
                    await _context.SaveChangesAsync();

                    saveResult.IsSuccess = true;
                }
                else
                {
                    saveResult.IsSuccess = true;
                }
            }
            else
            {
                var regions = _context.ApplicationRole.Where(a => model.RoleIds.Contains(a.Id));

                if (currentEntities.Any())
                {
                    saveResult.IsSuccess = await AddApplicationRoleMessageTemplateWherePreviousExists(model, currentEntities, regions);

                    if (saveResult.IsSuccess)
                    {
                        saveResult = await ManageExistingApplicationRoleMessageTemplate(model, currentEntities, regions);
                    }
                }
                else
                {
                    saveResult.IsSuccess = await AddEntity(model, currentEntities, regions);
                }
            }


            return(saveResult);
        }
Exemplo n.º 6
0
        private void btn_AddInt_Click(object sender, EventArgs e)
        {
            SysDept dept = new SysDept();

            dept.Name = "aaa" + Guid.NewGuid().ToString();

            SaveResult saveResult = Mydb.Insert(dept);

            if (saveResult.OK)
            {
                MessageBox.Show(saveResult.PK_Int.ToString());
            }
            else
            {
                MessageBox.Show(saveResult.Msg);
            }
        }
Exemplo n.º 7
0
        public async Task <SaveResult> SaveEntity(CountryViewModel viewModel)
        {
            SaveResult saveResult = new SaveResult();
            Dictionary <bool, string> dictionary = new Dictionary <bool, string>();

            var entity = new Country();

            try
            {
                if (viewModel.Id != 0)
                {
                    if (_context.Country.Any(a => a.Id == viewModel.Id))
                    {
                        entity = await _context.Country.FirstOrDefaultAsync(a => a.Id == viewModel.Id);
                    }
                    entity = viewModel.ToEntity(entity);
                    _context.Country.Update(entity);
                }
                else
                {
                    entity = viewModel.ToEntity(entity);
                    _context.Country.Add(entity);
                }

                await _context.SaveChangesAsync();

                if (entity.Id > 0)
                {
                    saveResult.IsSuccess = true;
                    saveResult.Id        = entity.Id;
                }
            }
            catch (DbUpdateException upDateEx)
            {
                var    results = upDateEx.GetSqlerrorNo();
                string msg     = results == (int)SqlErrNo.FK ? ConstEntity.MissingValueMsg : ConstEntity.UniqueKeyMsg;
                saveResult = dictionary.GetValidateEntityResults(msg).ToSaveResult();
            }
            catch (Exception ex)
            {
                saveResult.Message = CrudError.SaveErrorMsg;
            }


            return(saveResult);
        }
Exemplo n.º 8
0
        public async Task <SaveResult> SaveEntityList(CalendarViewModel model, Calendar parentEntity)
        {
            SaveResult saveResult = new SaveResult();

            var currentEntities = parentEntity.Moderators;

            if (model.ModeratorIds == null)
            {
                if (currentEntities.Any())
                {
                    var ModeratorIds = currentEntities.ToList().ToList().Select(b => b.Id);

                    var toDeleteList = _context.Moderator.Where(a => ModeratorIds.Contains(a.Id));

                    _context.Moderator.RemoveRange(toDeleteList);
                    await _context.SaveChangesAsync();

                    saveResult.IsSuccess = true;
                }
                else
                {
                    saveResult.IsSuccess = true;
                }
            }
            else
            {
                var existingEntityList = _context.Member.Where(a => model.ModeratorIds.Contains(a.Id));

                if (currentEntities.Any())
                {
                    saveResult.IsSuccess = await AddModeratorWherePreviousExists(model, currentEntities, existingEntityList);

                    if (saveResult.IsSuccess)
                    {
                        saveResult = await ManageExistingModerator(model, currentEntities, existingEntityList);
                    }
                }
                else
                {
                    saveResult.IsSuccess = await AddEntity(model, currentEntities, existingEntityList);
                }
            }


            return(saveResult);
        }
Exemplo n.º 9
0
        public async Task <SaveResult> SaveEntityList(TimeTrialViewModel model, TimeTrial parentEntity)
        {
            SaveResult saveResult = new SaveResult();

            var currentEntities = parentEntity.TimeTrialDistances;

            if (model.DistanceIds == null)
            {
                if (currentEntities.Any())
                {
                    var TimeTrialDistanceIds = currentEntities.ToList().ToList().Select(b => b.Id);

                    var toDeleteList = _context.TimeTrialDistance.Where(a => TimeTrialDistanceIds.Contains(a.Id));

                    _context.TimeTrialDistance.RemoveRange(toDeleteList);
                    await _context.SaveChangesAsync();

                    saveResult.IsSuccess = true;
                }
                else
                {
                    saveResult.IsSuccess = true;
                }
            }
            else
            {
                var regions = _context.Distance.Where(a => model.DistanceIds.Contains(a.Id));

                if (currentEntities.Any())
                {
                    saveResult.IsSuccess = await AddTimeTrialDistanceWherePreviousExists(model, currentEntities, regions);

                    if (saveResult.IsSuccess)
                    {
                        saveResult = await ManageExistingTimeTrialDistance(model, currentEntities, regions);
                    }
                }
                else
                {
                    saveResult.IsSuccess = await AddEntity(model, currentEntities, regions);
                }
            }


            return(saveResult);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 保存实体
        /// </summary>
        /// <param name="fbEntityList"></param>
        /// <returns></returns>
        public SaveResult Save(SaveEntity saveEntity)
        {
            SaveResult result = new SaveResult();

            try
            {
                result.FBEntity   = base.SaveEntityBLLSave(saveEntity);
                result.Successful = true;
            }
            catch (FBBLLException ex)
            {
                result.Successful = false;
                result.Exception  = ex.Message;
                SystemBLL.Debug(ex.ToString());
            }
            return(result);
        }
Exemplo n.º 11
0
        public override void DoSave(IButtonInfo sender) // 保存数据
        {
            this.UpdateLastControl();                   //更新最后一个输入框的数据

            if (!ValidatingSummaryData(_BLL.CurrentBusiness.Tables[tb_IA.__TableName]))
            {
                return;                                                                         //检查主表数据合法性
            }
            if (!ValidatingDetailData(_BLL.CurrentBusiness.Tables[tb_IAs.__TableName]))
            {
                return;                                                                         //检查从表数据合法性
            }
            //注意:只有修改状态下保存修改日志
            if (_UpdateType == UpdateType.Modify)
            {
                _BLL.WriteLog();
            }

            //创建用于保存的临时数据
            DataSet    dsTemplate = _BLL.CreateSaveData(_BLL.CurrentBusiness, _UpdateType);
            SaveResult result     = _BLL.Save(dsTemplate); //调用业务逻辑保存数据方法

            if (result.Success)                            //保存成功, 不需要重新加载数据,更新当前的缓存数据就行.
            {
                if (_UpdateType == UpdateType.Add)
                {
                    _BLL.DataBindRow[tb_IA.__KeyName] = result.DocNo;                                //更新单据号码
                }
                if (_UpdateType == UpdateType.Modify)
                {
                    _BLL.NotifyUser();                        //修改后短信或Email通知制单人
                }
                this.UpdateSummaryRow(_BLL.DataBindRow);      //刷新表格内当前记录的缓存数据.
                this.DoBindingSummaryEditor(_BLL.DataBinder); //重新显示数据
                if (_UpdateType == UpdateType.Add)
                {
                    gvSummary.MoveLast(); //如是新增单据,移动到取后一条记录.
                }
                base.DoSave(sender);      //调用基类的方法. 此行代码应放较后位置.
                Msg.ShowInformation("保存成功!");
            }
            else
            {
                Msg.Warning("保存失败!");
            }
        }
Exemplo n.º 12
0
 private void RegisterXRefSpec(DocumentBuildContext context, FileModel model, SaveResult result)
 {
     foreach (var spec in result.XRefSpecs)
     {
         if (!string.IsNullOrWhiteSpace(spec?.Uid))
         {
             if (context.XRefSpecMap.ContainsKey(spec.Uid))
             {
                 Logger.LogWarning($"Uid({spec.Uid}) duplicated.", file: model.LocalPathFromRepoRoot);
             }
             else
             {
                 context.XRefSpecMap[spec.Uid] = spec.ToReadOnly();
             }
         }
     }
 }
Exemplo n.º 13
0
 private void RegisterXRefSpec(SaveResult result)
 {
     foreach (var spec in result.XRefSpecs)
     {
         if (!string.IsNullOrWhiteSpace(spec?.Uid))
         {
             Context.RegisterInternalXrefSpec(spec);
         }
     }
     foreach (var spec in result.ExternalXRefSpecs)
     {
         if (!string.IsNullOrWhiteSpace(spec?.Uid))
         {
             Context.ReportExternalXRefSpec(spec);
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// 保存患者信息
        /// </summary>
        protected override SaveResult SaveData()
        {
            SaveResult saveResult = SaveResult.Fail;
            bool       result     = true;

            if (_anesInputData != null)
            {
                _anesInputData.CANCELED_TYPE         = CANCELED_TYPE ? "1" : null;
                _anesInputData.SPINAL_ANES_COMP      = SPINAL_ANES_COMP ? 1 : 0;
                _anesInputData.CONS_DISTURBANCE      = CONS_DISTURBANCE ? 1 : 0;
                _anesInputData.RES_TRACT_OBSTRUCE    = RES_TRACT_OBSTRUCE ? 1 : 0;
                _anesInputData.TRACHEA_6H            = TRACHEA_6H ? 1 : 0;
                _anesInputData.CENTRAL_VENOUS        = CENTRAL_VENOUS ? 1 : 0;
                _anesInputData.OXYGEN_SATURATION     = OXYGEN_SATURATION ? 1 : 0;
                _anesInputData.AFTER_ANES_COMA       = AFTER_ANES_COMA ? 1 : 0;
                _anesInputData.ANES_ANAPHYLAXIS      = ANES_ANAPHYLAXIS ? 1 : 0;
                _anesInputData.TRACHEA_HOARSE        = TRACHEA_HOARSE ? 1 : 0;
                _anesInputData.ANES_DEATH            = ANES_DEATH ? 1 : 0;
                _anesInputData.PACU_3H               = PACU_3H ? "1" : null;
                _anesInputData.PACU_TEMPERATURE      = PACU_TEMPERATURE ? 1 : 0;
                _anesInputData.NO_PLAN_IN_ICU        = NO_PLAN_IN_ICU ? 1 : 0;
                _anesInputData.BLOOD_EVENT           = BLOOD_EVENT ? 1 : 0;
                _anesInputData.OPER_EVENT            = OPER_EVENT ? 1 : 0;
                _anesInputData.ANES_EVENT            = ANES_EVENT ? 1 : 0;
                _anesInputData.PAT_INDETIFICATION    = PAT_INDETIFICATION ? 1 : 0;
                _anesInputData.OTHER_EVENT           = OTHER_EVENT ? 1 : 0;
                _anesInputData.UNEXPECT_EVENT_REASON = UNEXPECT_EVENT_REASON;

                _anesInputData.TRACHEA_REMOVE       = this.TRACHEA_REMOVE ? 1 : 0;
                _anesInputData.ANES_START_24H_DEATH = this.ANES_START_24H_DEATH ? 1 : 0;
                _anesInputData.ANES_START_24H_STOP  = this.ANES_START_24H_STOP ? 1 : 0;

                _anesInputData.PREVENT_STEP = PREVENT_STEP;
                _anesInputData.EVENT_COURSE = EVENT_COURSE;
                result = CareDocService.ClientInstance.SaveAnesInputData(_anesInputData);
            }

            if (result)
            {
                saveResult = SaveResult.Success;
            }


            return(saveResult);
        }
Exemplo n.º 15
0
        private async Task <SaveResult> SaveMeasurementsInternalAsync(string key, params MeasurementModel[] measurements)
        {
            Repository r      = new Repository(true);
            SaveResult result = null;

            try
            {
                result = await r.SaveMeasurementsAsync(key, measurements);
            }
            catch (UnauthorizedAccessException uex)
            {
                if (IsWebInvoked)
                {
                    Failure f = new Failure()
                    {
                        Code      = uex.HResult,
                        Exception = uex,
                        Index     = -1,
                        Reason    = uex.FriendlyException()
                    };
                    throw new WebFaultException <Failure>(f, System.Net.HttpStatusCode.Forbidden);
                }
                throw new FaultException(uex.Message);
            }
            catch (Exception ex)
            {
                Savonia.WCF.ErrorReporter.ErrorReporterModule em = new ErrorReporterModule();
                var source = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                em.HandleError(ex, string.Format("SaveMeasurementsInternal the actual root error. Request from: {0}", null != source ? source.Address : "n/a"));
                if (IsWebInvoked)
                {
                    Failure f = new Failure()
                    {
                        Code      = ex.HResult,
                        Exception = ex,
                        Index     = -1,
                        Reason    = ex.FriendlyException()
                    };
                    throw new WebFaultException <Failure>(f, System.Net.HttpStatusCode.BadRequest);
                }
                throw new FaultException(ex.FriendlyException());
            }

            return(result);
        }
Exemplo n.º 16
0
        public override SaveResult <Student> Add(Student entity)
        {
            var output = new SaveResult <Student>();                               // Meu

            output = base.Add(entity);                                             //JOSE
            if (entity.Id == QueryAll().FirstOrDefault(s => s.Id == entity.Id).Id) //MEU
            {
                output.Entity    = entity;
                output.IsSuccess = true;
            }

            if (output.IsSuccess || entity.Id == QueryAll().FirstOrDefault(s => s.Id == entity.Id).Id) //Meu
            {
                StudentsByDni.Add(output.Entity.Dni, output.Entity);                                   //de Jose
            }

            return(output);
        }
Exemplo n.º 17
0
 private void RegisterXRefSpec(DocumentBuildContext context, SaveResult result)
 {
     foreach (var spec in result.XRefSpecs)
     {
         if (!string.IsNullOrWhiteSpace(spec?.Uid))
         {
             XRefSpec xref;
             if (context.XRefSpecMap.TryGetValue(spec.Uid, out xref))
             {
                 Logger.LogWarning($"Uid({spec.Uid}) has already been defined in {((RelativePath)xref.Href).RemoveWorkingFolder()}.");
             }
             else
             {
                 context.XRefSpecMap[spec.Uid] = spec.ToReadOnly();
             }
         }
     }
 }
Exemplo n.º 18
0
        public ActionResult PageEdit(PageModel model)
        {
            CachedEditableModel cachedModel = CMSCache.Pages[model.ModelType];

            model.PageTemplateModel = GetPageModel(cachedModel);  //.GetPageModel();
            //UpdateModel( model.PageTemplateModel );

            PageManager manager = new PageManager();

            SaveResult result = manager.SavePage(model);

            if (result.State == SaveResultState.Success)
            {
                return(RedirectToAction("PageList"));
            }

            return(View(model));
        }
Exemplo n.º 19
0
            public void ReturnSaveResultIfNoExceptionsThrown()
            {
                var aggregate               = new Mock <Aggregate>();
                var pipelineHook            = new Mock <PipelineHook>();
                var decoratedAggregateStore = new Mock <IStoreAggregates>();
                var commit         = (Commit)FormatterServices.GetUninitializedObject(typeof(Commit));
                var aggregateStore = new HookableAggregateStore(decoratedAggregateStore.Object, new[] { pipelineHook.Object });
                var saveResult     = new SaveResult(aggregate.Object, commit);

                // ReSharper disable AccessToDisposedClosure
                using (var context = new CommandContext(Guid.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                {
                    decoratedAggregateStore.Setup(mock => mock.Save(aggregate.Object, context)).Returns(saveResult);

                    Assert.Same(saveResult, aggregateStore.Save(aggregate.Object, context));
                }
                // ReSharper restore AccessToDisposedClosure
            }
Exemplo n.º 20
0
        public virtual SaveResult <T> Add(T entity)
        {
            var output = new SaveResult <T>();

            if (entity.Id != default)
            {
                throw new Exception("la entidad ya tiene id");
            }

            entity.Id = Guid.NewGuid();
            _dbContext.Set <T>().Add(entity);
            _dbContext.SaveChanges();

            output.IsSuccess = true;
            output.Entity    = entity;

            return(output);
        }
        public void SaveTodoItem()
        {
            // arrange
            TodoItem expectedTodoItem = dataPrep.TodoItems.Create();

            expectedTodoItem.Description = Guid.NewGuid().ToString();

            mockContainer.Arrange <ITodoItemAccessor>(accessor => accessor.SaveTodoItem(expectedTodoItem)).Returns(new SaveResult <TodoItem>(expectedTodoItem));

            // act
            SaveResult <TodoItem> todoItemResult = manager.SaveTodoItem(expectedTodoItem);
            TodoItem actualTodoItem = todoItemResult.Result;

            //assert
            Assert.IsTrue(todoItemResult.Success);
            // because we mutated the expected object, the changed property is as expected on the original object too
            expectedTodoItem.ShouldDeepEqual(actualTodoItem);
        }
Exemplo n.º 22
0
        public SaveResult Save(FBEntity fbEntity)
        {
            SaveResult result = new SaveResult();

            try
            {
                using (FBCommonBLL fbCommonBLL = new FBCommonBLL())
                {
                    result = fbCommonBLL.FBCommSaveEntity(fbEntity);
                }
            }
            catch (Exception ex)
            {
                result.Successful = false;
                result.Exception  = ex.Message;
            }
            return(result);
        }
Exemplo n.º 23
0
 public SaveResult Save(SaveEntity saveEntity)
 {
     using (FBCommonBLL fbCommonBLL = new FBCommonBLL())
     {
         SaveResult result = new SaveResult();
         try
         {
             result = fbCommonBLL.Save(saveEntity);
         }
         catch (Exception ex)
         {
             result.Successful = false;
             result.Exception  = ex.Message;
             Tracer.Debug(ex.ToString());
         }
         return(result);
     }
 }
Exemplo n.º 24
0
        private string GetSaveResultErrorText(SaveResult saveResult)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var eloop in saveResult.errors)
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                sb.AppendFormat("Error {0} Status Code {1} ", eloop.message, eloop.statusCode.ToString());
                if (eloop.fields != null)
                {
                    sb.AppendFormat("Fields {0}", string.Join(",", eloop.fields));
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 25
0
        public virtual SaveResult <object> ChangeSpacesToDashesInName(Int32 id)
        {
            var result = new SaveResult <object>();

            try{
                var    item      = DataSource.Includes().FindItem(id);
                object objResult = null;
                item.ChangeSpacesToDashesInName();
                Db.SaveChanges();
                result.Object        = objResult;
                result.WasSuccessful = true;
                result.Message       = null;
            }catch (Exception ex) {
                result.WasSuccessful = false;
                result.Message       = ex.Message;
            }
            return(result);
        }
Exemplo n.º 26
0
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            var repo     = Entity.DepCon.Resolve <IRepository <Subject> >();
            var res_save = new SaveResult <Subject>();

            if (!Update)
            {
                var output_dni = Subject.ValidateName(txtName.Text);
                if (!output_dni.IsSuccess)
                {
                    MessageBox.Show(output_dni.AllErrors, "Warning!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    Subject newSubject = new Subject {
                        Name = txtName.Text
                    };
                    res_save = newSubject.Save();
                    //exit = true;
                }
            }
            else
            {
                //check por si acaso


                if (subject_for_update != null)
                {
                    subject_for_update.Name = txtName.Text;
                    res_save = subject_for_update.Save();
                    //exit = true;
                }
            }

            if (res_save.IsSuccess)
            {
                (this.Owner as MainWindow).lstbox_sb.ItemsSource = repo.QueryAll().ToList();
                this.Close();
            }
            else if (!string.IsNullOrWhiteSpace(res_save.AllErrors))
            {
                MessageBox.Show(res_save.AllErrors, "Warning!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 在快速切换前判断数据是否需要保存
        /// </summary>
        private bool SaveBeforeChangeOperEvent()
        {
            bool result = true;

            // 检查数据是否修改过 以及判断数据是否完整
            if (this.CheckDataChange() && this.CheckData())
            {
                ShowMessageBox("当前数据有修改,是否保存数据?",
                               MessageBoxButton.YesNoCancel,
                               MessageBoxImage.Question,
                               new Action <MessageBoxResult>((r) =>
                {
                    // 是or否 跳转,取消
                    if (r == MessageBoxResult.Yes || r == MessageBoxResult.OK)
                    {
                        SaveResult saveResult = SaveResult.Success;
                        try
                        {
                            WhirlingControlManager.ShowWaitingForm();
                            saveResult = SaveData();
                        }
                        finally
                        {
                            WhirlingControlManager.CloseWaitingForm();
                        }
                        if (saveResult == SaveResult.Fail)
                        {
                            ShowMessageBox("数据保存失败。", MessageBoxButton.OK, MessageBoxImage.Error);
                            result = false;
                        }
                    }
                    else if (r == MessageBoxResult.No)
                    {
                        result = true;
                    }
                    else if (r == MessageBoxResult.Cancel)
                    {
                        result = false;
                    }
                }));
            }

            return(result);
        }
Exemplo n.º 28
0
        private async Task <SaveResult> SaveAddress(MemberStagingViewModel viewModel)
        {
            try
            {
                SaveResult saveResult = new SaveResult();

                var entity = new Address();

                if (viewModel.Address.Id != 0)
                {
                    if (_context.Address.Any(a => a.Id == viewModel.Address.Id))
                    {
                        entity = await _context.Address.FirstOrDefaultAsync(a => a.Id == viewModel.Address.Id);
                    }
                    entity = viewModel.Address.ToEntity(entity);
                    _context.Address.Update(entity);
                }
                else
                {
                    entity = viewModel.Address.ToEntity(entity);
                    _context.Address.Add(entity);
                }

                await _context.SaveChangesAsync();

                if (entity.Id > 0)
                {
                    saveResult.IsSuccess = true;
                }
                saveResult.Id        = entity.Id;
                viewModel.AddressId  = entity.Id;
                viewModel.Address.Id = viewModel.AddressId;

                return(saveResult);
            }
            catch (DbUpdateException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 29
0
        /*Version ValidationResults */
        public SaveResult <Student> SaveStudent(Student student)
        {
            using (AcademyDbContext context = new AcademyDbContext())
            {
                var output = new SaveResult <Student>()
                {
                    Entity = student
                };

                if (student != null)
                {
                    try
                    {
                        var result = context.ListaStudents.Where(x => x.Dni.Equals(student.Dni));

                        if (result != null && result.Count() > 0)
                        {
                            output.IsSuccess = false;
                            output.Validation.Errors.Add($"El alumno {result.First().Name} ya está registrado con este dni, por favor, reviselos.");
                        }
                        else
                        {
                            output.IsSuccess = true;
                            context.Add(student);
                            context.SaveChanges();
                            student.Save();
                            output.Validation.Errors.Add("Alumno guardado correctamente. ¿Qué quieres hacer ahora?");
                        }
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        Console.WriteLine($"Se ha producido un error con el SGBD con error code:{e.ErrorCode} y por el motivo: {e.Message}");
                        Console.WriteLine($"En caso de Unknown Database, Fíjate que la base de datos esté creada y que tengas acceso al server");
                        Console.WriteLine($"Si no está creada recuerda: desde consola de administración de paquetes: add-migration y add-database");
                    }
                }
                else
                {
                    output.Validation.Errors.Add("Los campos Nombre y/o DNI no contienen información o no es válida");
                }
                Console.WriteLine(output.AllErrors);
                return(output);
            }
        }
        public List <SaveResult <PODTO> > GetSaveResults(List <PODTO> poList, DateTime dateStamp)
        {
            var validationResults = Validate(poList);
            List <SaveResult <PODTO> > saveResults = new List <SaveResult <PODTO> >();

            foreach (var validationResult in validationResults)
            {
                var poDTO = (PODTO)validationResult.GetModel();
                if (validationResult.IsValid)
                {
                    var exists = poQuery.GetByPrimaryKey(poDTO.PO_PK);
                    if (poDTO.PO_PK > 0 && exists != null)
                    {
                        UpdatePO(poDTO, dateStamp);
                    }
                    else
                    {
                        poDTO.PO_PK = 0;
                        AddPO(poDTO, dateStamp);
                    }

                    var saveResult = new SaveResult <PODTO>()
                    {
                        Message          = "SUCCESS",
                        Model            = poDTO,
                        Success          = true,
                        ValidationResult = validationResult,
                    };
                    saveResults.Add(saveResult);
                }
                else
                {
                    var saveResult = new SaveResult <PODTO>()
                    {
                        Message          = "FAILED",
                        Model            = poDTO,
                        Success          = false,
                        ValidationResult = validationResult,
                    };
                    saveResults.Add(saveResult);
                }
            }
            return(saveResults);
        }
Exemplo n.º 31
0
        public SaveResult ExcuteSqlCommand(string sql, object[] parameters)
        {
            SaveResult r;

            try
            {
                int count = this.context.Database.ExecuteSqlCommand(sql, parameters);
                r = new SaveResult {
                    IsSuccess = true, Rows = count
                };
            }
            catch (Exception exp)
            {
                r = new SaveResult {
                    IsSuccess = false, Message = exp.Message
                };
            }
            return(r);
        }
        public SaveResult<UserViewModel> RegisterAccount(RegisterViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var password = this._securityManager.GeneratePassword();
            User user = this._userManager.Create(model.Name, model.Email, StrixPlatform.CurrentCultureCode, password, false, model.AcceptedTerms, model.RegistrationComment);
            var result = new SaveResult<UserViewModel>(user != null, user.Map<UserViewModel>());

            if (user != null)
            {
                var verificationId = Guid.NewGuid();
                this._securityManager.SetVerificationId(user.Id, verificationId);
                this.SaveChanges();

                // Add the user role to allow logging in.
                this._roleManager.AddUserToRole(StrixPlatform.User.GroupId, user.Id, PlatformConstants.USERROLE);
                this.SaveChanges();

                if (StrixMembership.Configuration.Registration.AutoApproveUsers)
                {
                    if (!this._mailer.SendApprovedAccountMail(user.PreferredCulture, user.Name, user.Email, verificationId))
                    {
                        result.Message = Resources.Interface.ErrorSendingApprovedAccountMail;
                        Logger.Log(string.Format("An error occurred while sending the approved account mail to user {0}", user.Name), LogLevel.Error);
                    }
                }
                else
                {
                    if (!this._mailer.SendUnapprovedAccountMail(user.PreferredCulture, user.Name, user.Email, verificationId))
                    {
                        result.Message = Resources.Interface.ErrorSendingUnapprovedAccountMail;
                        Logger.Log(string.Format("An error occurred while sending the unapproved account mail to user {0}", user.Name), LogLevel.Error);
                    }
                }
            }

            return result;
        }
        public SaveResult<VocabularyViewModel> Save(VocabularyViewModel model, bool saveChanges)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var result = new SaveResult<VocabularyViewModel>();
            Vocabulary vocabulary;

            if (model.Id == Guid.Empty)
            {
                vocabulary = this._manager.CreateVocabulary(model.Name, model.Culture);
            }
            else
            {
                vocabulary = this._manager.GetVocabulary(model.Id);
                model.Map<Vocabulary>(vocabulary);
            }

            result.Success = vocabulary != null;

            if (result.Success && saveChanges)
            {
                this._source.SaveChanges();
            }

            result.Entity = vocabulary;
            return result;
        }
            public void ReturnSaveResultIfNoExceptionsThrown()
            {
                var aggregate = new Mock<Aggregate>();
                var pipelineHook = new Mock<PipelineHook>();
                var decoratedAggregateStore = new Mock<IStoreAggregates>();
                var commit = (Commit)FormatterServices.GetUninitializedObject(typeof(Commit));
                var aggregateStore = new HookableAggregateStore(decoratedAggregateStore.Object, new[] { pipelineHook.Object });
                var saveResult = new SaveResult(aggregate.Object, commit);

                // ReSharper disable AccessToDisposedClosure
                using (var context = new CommandContext(Guid.NewGuid(), HeaderCollection.Empty, CommandEnvelope.Empty))
                {
                    decoratedAggregateStore.Setup(mock => mock.Save(aggregate.Object, context)).Returns(saveResult);

                    Assert.Same(saveResult, aggregateStore.Save(aggregate.Object, context));
                }
                // ReSharper restore AccessToDisposedClosure
            }
        public SaveResult<UserViewModel> SendPasswordResetLink(Guid userId)
        {
            var result = new SaveResult<UserViewModel>();
            var user = this._userManager.Get(userId);

            if (user != null)
            {
                // Set a new verification key.
                var verificationId = Guid.NewGuid();
                this._securityManager.SetVerificationId(user.Id, verificationId);
                this.SaveChanges();
                result.Success = true;

                if (!this._mailer.SendSetPasswordMail(user.PreferredCulture, user.Name, user.Email, verificationId))
                {
                    Logger.Log(string.Format("An error occurred while sending the password reset mail to user {0}", user.Name), LogLevel.Error);
                    result.Message = Resources.Interface.ErrorSendingPasswordResetLink;
                }
            }

            return result;
        }
        public SaveResult<TermViewModel> SaveTag(TermViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var result = new SaveResult<TermViewModel>();
            Term term;

            if (model.Id == Guid.Empty)
            {
                term = this._manager.CreateTag(model.VocabularyId, model.Name);
            }
            else
            {
                term = this._manager.GetTag(model.Id);
                model.Map<Term>(term);
            }

            result.Success = term != null;

            if (result.Success)
            {
                this._source.SaveChanges();
            }

            result.Entity = term;
            return result;
        }
Exemplo n.º 37
0
        //update a list of objects in zuora
        public List<ResponseHolder> Update(List<zObject> input)
        {
            List<ResponseHolder> results = new List<ResponseHolder>();
            SaveResult[] res =  new SaveResult[]{};
            bool done = false;
            int updateNum = 50;
            while (!done)
            {
                List<zObject> doWork = new List<zObject>() { };

                if (input.Count > updateNum)
                {
                    List<zObject> updateList = input.GetRange(0, updateNum);
                    for (int i = 0; i < updateNum; i++)
                    {
                        zObject temp = updateList[i];
                        doWork.Add(temp);
                        input.Remove(temp);
                    }
                }
                else
                {
                    done = true;
                    doWork = input;
                }
                CheckTime();
                try
                {
                    res = svc.update(sh, doWork.ToArray());
                }
                catch (FaultException e)
                {
                    ResponseHolder error = new ResponseHolder();
                    error.Message = e.Message;
                    error.Success = false;
                    results.Add(error);
                    return results;
                }
                foreach (SaveResult sr in res)
                {
                    ResponseHolder temp = new ResponseHolder();
                    if (sr.Success)
                    {
                        temp.Id = sr.Id;
                        temp.Success = true;
                    }
                    else
                    {
                        temp.Success = false;
                        temp.Message = sr.Errors[0].Message;
                    }
                    results.Add(temp);
                }
            }
            return results;
        }
Exemplo n.º 38
0
 private void UpdateStatusBar(SaveResult fileSaved = SaveResult.None)
 {
     if (fileSaved == SaveResult.None)
     {
         if (_fs.IsNew)
         {
             if (_fs.IsEdited)
             {
                 ssBar.Items["tsInfo"].Text = "New file";
             }
             else
             {
                 ssBar.Items["tsInfo"].Text = "Editing new file";
             }
         }
         else
         {
             if (_fs.IsEdited)
             {
                 ssBar.Items["tsInfo"].Text = string.Format("Editing {0}", _fs.FilePath);
             }
             else
             {
                 ssBar.Items["tsInfo"].Text = string.Format("Opened {0} @ {1} {2}", _fs.FilePath, DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
             }
         }
     }
     else
     {
         switch (fileSaved)
         {
                 case SaveResult.Saved:
                     ssBar.Items["tsInfo"].Text = string.Format("Saved {0} @ {1} {2}", _fs.FilePath, DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
                     break;
                 case SaveResult.NotChanged:
                     ssBar.Items["tsInfo"].Text = string.Format("Not saved because no changes detected. Use CTRL+X to force save to disk.");
                     break;
                 case SaveResult.Cancelled:
                     ssBar.Items["tsInfo"].Text = string.Format("Not saved because cancelled by user.");
                     break;
                 case SaveResult.Failed:
                     ssBar.Items["tsInfo"].Text = string.Format("Not saved because an error occured. Check permissions on file/directory and available disk space.");
                     break;
         }
     }
     Text = String.Format("{0}{1} - {2}", _fs.IsEdited ? "*" : "",
                                   _fs.IsNew ? "New" : _fs.FilePath, _programVersion);
 }
Exemplo n.º 39
0
        private void PrintResultBySave(SaveResult result, string pageName)
        {
            var infoType = InfoType.Info;
            if (!result.Equals(SaveResult.Ok) && !result.Equals(SaveResult.NoChanges))
            {
                infoType = InfoType.Alert;
            }

            switch (result)
            {
                case SaveResult.SectionUpdate:
                    Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    break;
                case SaveResult.OkPageRename:
                case SaveResult.Ok:
                    PrintInfoMessage(WikiResource.msgSaveSucess, infoType);
                    if (Action.Equals(ActionOnPage.AddNew))
                    {
                        Response.RedirectLC(ActionHelper.GetEditPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);

                    }
                    else if (Action.Equals(ActionOnPage.AddNewFile))
                    {
                        Response.RedirectLC(ActionHelper.GetEditFilePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    }
                    break;
                case SaveResult.FileEmpty:
                    PrintInfoMessage(WikiResource.msgFileEmpty, infoType);
                    break;
                case SaveResult.FileSizeExceeded:
                    PrintInfoMessage(FileSizeComment.GetFileSizeExceptionString(FileUploader.MaxUploadSize), infoType);
                    break;
                case SaveResult.NoChanges:
                    PrintInfoMessage(WikiResource.msgNoChanges, infoType);
                    break;
                case SaveResult.PageNameIsEmpty:
                    PrintInfoMessage(WikiResource.msgPageNameEmpty, infoType);
                    break;
                case SaveResult.PageNameIsIncorrect:
                    PrintInfoMessage(WikiResource.msgPageNameIncorrect, infoType);
                    break;
                case SaveResult.SamePageExists:
                    PrintInfoMessage(WikiResource.msgSamePageExists, infoType);
                    break;
                case SaveResult.UserIdIsEmpty:
                    PrintInfoMessage(WikiResource.msgInternalError, infoType);
                    break;
                case SaveResult.OldVersion:
                    PrintInfoMessage(WikiResource.msgOldVersion, infoType);
                    break;
                case SaveResult.Error:
                    PrintInfoMessage(WikiResource.msgMarkupError, InfoType.Alert);
                    break;
            }
        }
Exemplo n.º 40
0
        private void PrintResultBySave(SaveResult result, string pageName)
        {
            var infoType = InfoType.Info;
            var authorId = SecurityContext.CurrentAccount.ID.ToString();
            if (!result.Equals(SaveResult.Ok) && !result.Equals(SaveResult.NoChanges))
            {
                infoType = InfoType.Alert;
            }

            switch (result)
            {
                case SaveResult.SectionUpdate:
                    //WikiNotifyClient.SendNoticeAsync(
                    //    authorId,
                    //    Common.Constants.EditPage,
                    //    pageName,
                    //    null,
                    //    GetListOfTagValForNotify(pageName, "edit wiki page", null));
                    Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    break;
                case SaveResult.OkPageRename:
                case SaveResult.Ok:
                    PrintInfoMessage(WikiResource.msgSaveSucess, infoType);
                    if (Action.Equals(ActionOnPage.AddNew))
                    {

                        //WikiNotifyClient.SendNoticeAsync(
                        //    authorId,
                        //    Common.Constants.NewPage,
                        //    null,
                        //    null,
                        //    GetListOfTagValForNotify(pageName));

                        //WikiActivityPublisher.AddPage(Wiki.GetPage(pageName));

                        Response.RedirectLC(ActionHelper.GetEditPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);

                    }
                    else if (Action.Equals(ActionOnPage.AddNewFile))
                    {
                        //WikiActivityPublisher.AddFile(Wiki.GetFile(pageName));
                        Response.RedirectLC(ActionHelper.GetEditFilePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    }
                    //else if (!IsFile)
                    //{
                    //    bool isNewPage = !WikiActivityPublisher.EditPage(Wiki.GetPage(pageName));

                    //    if (isNewPage)
                    //    {
                    //        WikiNotifyClient.SendNoticeAsync(
                    //            authorId,
                    //            Common.Constants.NewPage,
                    //            null,
                    //            null,
                    //            GetListOfTagValForNotify(pageName));
                    //    }
                    //    else
                    //    {
                    //        WikiNotifyClient.SendNoticeAsync(
                    //            authorId,
                    //            Common.Constants.EditPage,
                    //            pageName,
                    //            null,
                    //            GetListOfTagValForNotify(pageName, "edit wiki page", null));
                    //    }

                    //}
                    break;
                case SaveResult.FileEmpty:
                    PrintInfoMessage(WikiResource.msgFileEmpty, infoType);
                    break;
                case SaveResult.FileSizeExceeded:
                    PrintInfoMessage(WikiResource.msgFileSizeExceeded, infoType);
                    break;
                case SaveResult.NoChanges:
                    PrintInfoMessage(WikiResource.msgNoChanges, infoType);
                    break;
                case SaveResult.PageNameIsEmpty:
                    PrintInfoMessage(WikiResource.msgPageNameEmpty, infoType);
                    break;
                case SaveResult.PageNameIsIncorrect:
                    PrintInfoMessage(WikiResource.msgPageNameIncorrect, infoType);
                    break;
                case SaveResult.SamePageExists:
                    PrintInfoMessage(WikiResource.msgSamePageExists, infoType);
                    break;
                case SaveResult.UserIdIsEmpty:
                    PrintInfoMessage(WikiResource.msgInternalError, infoType);
                    break;
                case SaveResult.OldVersion:
                    PrintInfoMessage(WikiResource.msgOldVersion, infoType);
                    break;
                case SaveResult.Error:
                    PrintInfoMessage(WikiResource.msgMarkupError, InfoType.Alert);
                    break;
            }
        }
        public SaveResult<UserViewModel> UpdateAccount(UserViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (model.Id == Guid.Empty)
            {
                throw new ArgumentException("The id is empty.This method can only be used to update existing accounts");
            }

            var validCredentials = this._securityManager.ValidateUser(model.Id, model.Password) == ValidateUserResult.Valid;
            var result = new SaveResult<UserViewModel>();

            if (validCredentials)
            {
                result.Entity = this._userManager.Update(model.Id, model.Name, model.Email, model.PreferredCulture);
                result.Success = result.Entity != null;

                if (result.Success)
                {
                    this.SaveChanges();
                }
            }

            return result;
        }
Exemplo n.º 42
0
        //create a list of objects in zuora
        public List<ResponseHolder> Create(List<zObject> input, bool singleTransaction)
        {
            List<ResponseHolder> results = new List<ResponseHolder>();

            CallOptions co = new CallOptions();
            SaveResult[] sr = new SaveResult[]{};
            bool done = false;
            int createNum = 50;
            if (singleTransaction)
            {
                co.useSingleTransaction = true;
                co.useSingleTransactionSpecified = true;
            }

            while (!done)
            {
                List<zObject> doWork = new List<zObject>() { };

                if (input.Count > createNum)
                {
                    List<zObject> createList = input.GetRange(0, createNum);
                    for (int i = 0; i < createNum; i++)
                    {
                        zObject temp = createList[i];
                        doWork.Add(temp);
                        input.Remove(temp);
                    }
                }
                else
                {
                    done = true;
                    doWork = input;
                }

                CheckTime();
                try
                {
                    sr = svc.create(co, sh, doWork.ToArray());
                }
                catch (FaultException e)
                {
                    ResponseHolder error = new ResponseHolder();
                    error.Message = e.Message;
                    error.Success = false;
                    results.Add(error);
                    return results;
                }
                foreach (SaveResult s in sr)
                {
                    ResponseHolder temp = new ResponseHolder();
                    if (s.Success)
                    {
                        temp.Success = true;
                        temp.Id = s.Id;
                    }
                    else
                    {
                        temp.Success = false;
                        temp.Message = s.Errors[0].Message;
                        if(s.Errors[0].CodeSpecified)
                        {
                            temp.ErrorCode = s.Errors[0].Code.ToString();
                        }
                    }
                    results.Add(temp);
                }
            }
            return results;
        }
Exemplo n.º 43
0
        /// <summary>
        /// 保存记录
        /// </summary>
        /// <returns></returns>
        public SaveResult Save()
        {
            SaveResult result = new SaveResult();

            //save new
            if(this.m_id == 0)
            {
                if(this.m_huohao.Trim() == string.Empty)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品货号]不能为空或输入的不合法,无法保存!";

                    return result;
                }

                if (CheckProductHuoHaoExist(this.m_huohao.Trim()))
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品货号]重复,无法保存!";

                    return result;
                }

                if(this.m_partname_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品种类]不能为空,无法保存!";

                    return result;
                }

                if(this.m_dengji_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品等级]不能为空,无法保存!";

                    return result;
                }

                if(this.m_madeplace_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品产地]不能为空,无法保存!";

                    return result;
                }

                if(this.m_price == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品价格]不能为空,无法保存!";

                    return result;
                }

                if(this.m_safedata_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[安全标准]不能为空,无法保存!";

                    return result;
                }

                if(this.m_standarddata_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[执行标准]不能为空,无法保存!";

                    return result;
                }

                if(this.m_material_data_list.Count == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[面料成份信息列表]不能为空,无法保存!";

                    return result;
                }

                //当填充材质不为空时处理填充数据
                if(!string.IsNullOrEmpty(this.MaterialFillInfo.material_type))
                {
                    foreach(MaterialFillInfoObject.MaterialFillData data in this.MaterialFillInfo.m_material_fill_list)
                    {
                        if(data.Fill == "0")
                        {
                            result.Code = CodeType.Error;
                            result.Message = "填充规则数据制定不完整,请重新制定!";

                            return result;
                        }
                    }
                }

                ProductData info = new ProductData();

                info.huohao = this.m_huohao;
                info.partname_id = this.m_partname_id;
                info.dengji_id = this.m_dengji_id;
                info.madeplace_id = this.m_madeplace_id;
                info.price = this.m_price;
                info.safedata_id = this.m_safedata_id;
                info.standarddata_id = this.m_standarddata_id;
                info.pwash = this.m_pwash == true ? 1:0;
                info.pbad = this.m_pbad == true ? 1:0;
                info.tag_id = this.GetTagFileNameId();
                info.memo = this.m_memo;
                info.wash_id = this.GetWashFileNameId();
                info.color_id = this.m_color_id;
                info.gyear = this.m_gyear;
                info.gmonth = this.m_gmonth;
                info.lastamp = System.Guid.NewGuid();

                if(this.m_ptemplate)
                {
                    info.ptemplate = 1;
                    info.template_data = this.m_template_data;
                }

                if(info.tag_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "系统未能找到对应的吊牌模板文件,保存无法继续!";

                    return result;
                }

                if(info.wash_id == 0)
                {
                    if (this.m_partname_id == 21)
                        info.wash_id = 1;
                    else
                    {
                        result.Code = CodeType.Error;
                        result.Message = "系统未能找到对应的洗唛模板文件,保存无法继续!";

                        return result;
                    }

                }

                using (ProductContext ctx = new ProductContext())
                {
                    ctx.ProductData.Add(info);

                    if(ctx.SaveChanges() == 0)
                    {
                        result.Code = CodeType.Error;
                        result.Message = "产品基本信息保存失败";

                        return result;
                    }
                }

                using (ProductContext ctx = new ProductContext())
                {
                    this.m_id = (from product in ctx.ProductData
                                 where product.huohao == this.m_huohao
                                 select product.id).FirstOrDefault();
                }

                int index = 1;

                foreach(MaterialDataInfo ob in this.m_material_data_list)
                {
                    using (ProductContext ctx = new ProductContext())
                    {
                        MaterialData entity = new MaterialData();

                        entity.product_id = this.m_id;
                        entity.sel = ob.Sel;
                        entity.type = ob.Type;
                        entity.order_index = index++;
                        entity.memo = ob.Memo;
                        entity.lastamp = System.Guid.NewGuid();

                        ctx.MaterialData.Add(entity);

                        ctx.SaveChanges();
                    }
                }

                if(!string.IsNullOrEmpty(this.MaterialFillInfo.material_type))
                {
                    foreach(MaterialFillInfoObject.MaterialFillData fill in this.MaterialFillInfo.m_material_fill_list)
                    {
                        using (ProductContext ctx = new ProductContext())
                        {
                            MaterialFill entity = new MaterialFill();
                            entity.product_id = this.m_id;
                            entity.size_name = fill.SizeName;
                            entity.type = this.MaterialFillInfo.material_type;
                            entity.fill = fill.Fill;
                            entity.lastamp = System.Guid.NewGuid();

                            ctx.MaterialFill.Add(entity);

                            ctx.SaveChanges();
                        }
                    }
                }

                result.Code = CodeType.Ok;
                result.Message = "保存成功!";

                return result;
            }

            //Edit Save
            if(this.m_id > 0)
            {
                if (this.m_huohao.Trim() == string.Empty)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品货号]不能为空或输入的不合法,无法保存!";

                    return result;
                }

                using (ProductContext ctx = new ProductContext())
                {
                    int count = (from product in ctx.ProductData
                                 where product.id == this.m_id && product.huohao == this.m_huohao
                                 select product).Count();

                    if(count > 1)
                    {
                        result.Code = CodeType.Error;
                        result.Message = "[产品货号]重复,无法保存!";

                        return result;
                    }

                }

                if (this.m_price == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[产品价格]不能为空,无法保存!";

                    return result;
                }

                if (this.m_safedata_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[安全标准]不能为空,无法保存!";

                    return result;
                }

                if (this.m_standarddata_id == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[执行标准]不能为空,无法保存!";

                    return result;
                }

                if (this.m_material_data_list.Count == 0)
                {
                    result.Code = CodeType.Error;
                    result.Message = "[面料成份信息列表]不能为空,无法保存!";

                    return result;
                }

                //当填充材质不为空时处理填充数据
                if (!string.IsNullOrEmpty(this.MaterialFillInfo.material_type))
                {
                    foreach(MaterialFillInfoObject.MaterialFillData data in this.MaterialFillInfo.m_material_fill_list)
                    {
                        if(data.Fill == "0")
                        {
                            result.Code = CodeType.Error;
                            result.Message = "填充规则数据制定不完整,请重新制定!";

                            return result;
                        }
                    }
                }

                using (ProductContext ctx = new ProductContext())
                {
                    System.Guid entity_lastamp = (from product in ctx.ProductData
                                                  where product.id == this.m_id
                                                  select product.lastamp).FirstOrDefault();

                    if(entity_lastamp != this.m_lastamp)
                    {
                        result.Code = CodeType.Error;
                        result.Message = "当前编辑的记录已经变更,无法保存!";

                        return result;
                    }
                }

                using (ProductContext ctx = new ProductContext())
                {
                    ProductData info = (from entity in ctx.ProductData
                                        where entity.id == this.m_id
                                        select entity).FirstOrDefault();

                    info.huohao = this.m_huohao;
                    info.partname_id = this.m_partname_id;
                    info.dengji_id = this.m_dengji_id;
                    info.madeplace_id = this.m_madeplace_id;
                    info.price = this.m_price;
                    info.safedata_id = this.m_safedata_id;
                    info.standarddata_id = this.m_standarddata_id;
                    info.pwash = this.m_pwash == true ? 1:0;
                    info.pbad = this.m_pbad == true ?1:0;
                    info.memo = this.m_memo;
                    info.tag_id = this.GetTagFileNameId();
                    info.wash_id = this.GetWashFileNameId();
                    info.color_id = this.m_color_id;
                    info.gyear = this.m_gyear;
                    info.gmonth = this.m_gmonth;
                    info.lastamp = System.Guid.NewGuid();

                    if (this.m_ptemplate)
                    {
                        info.ptemplate = 1;
                        info.template_data = this.m_template_data;
                    }

                    if (info.tag_id == 0)
                    {
                        result.Code = CodeType.Error;
                        result.Message = "系统未能找到对应的吊牌模板文件,保存无法继续!";

                        return result;
                    }

                    if (info.wash_id == 0 )
                    {
                        if(this.m_partname_id == 21)
                        {
                            info.wash_id = 1;
                        }
                        else
                        {
                            result.Code = CodeType.Error;
                            result.Message = "系统未能找到对应的洗唛模板文件,保存无法继续!";

                            return result;
                        }

                    }

                    if (ctx.SaveChanges() == 0)
                    {
                        result.Code = CodeType.Error;
                        result.Message = "产品基本信息保存失败";

                        return result;
                    }
                }

                //保存成份信息

                using (ProductContext ctx = new ProductContext())
                {
                    var mi = from entity in ctx.MaterialData
                             where entity.product_id == this.m_id
                             select entity;

                    foreach(var obj in mi)
                    {
                        ctx.MaterialData.Remove(obj);
                    }

                    ctx.SaveChanges();
                }

                int index = 1;

                foreach (MaterialDataInfo ob in this.m_material_data_list)
                {
                    using (ProductContext ctx = new ProductContext())
                    {
                        MaterialData entity = new MaterialData();
                        entity.product_id = this.m_id;
                        entity.sel = ob.Sel;
                        entity.type = ob.Type;
                        entity.order_index = index++;
                        entity.memo = ob.Memo;
                        entity.lastamp = System.Guid.NewGuid();

                        ctx.MaterialData.Add(entity);

                        ctx.SaveChanges();
                    }
                }

                ////////////////////////////////////////////////////////

                using (ProductContext ctx = new ProductContext())
                {
                    var mi = from entity in ctx.MaterialFill
                             where entity.product_id == this.m_id
                             select entity;

                    foreach (var obj in mi)
                    {
                        ctx.MaterialFill.Remove(obj);
                    }

                    ctx.SaveChanges();
                }

                if (!string.IsNullOrEmpty(this.MaterialFillInfo.material_type))
                {
                    foreach (MaterialFillInfoObject.MaterialFillData fill in this.MaterialFillInfo.m_material_fill_list)
                    {
                        using (ProductContext ctx = new ProductContext())
                        {
                            MaterialFill entity = new MaterialFill();
                            entity.product_id = this.m_id;
                            entity.size_name = fill.SizeName;
                            entity.type = this.MaterialFillInfo.material_type;
                            entity.fill = fill.Fill;
                            entity.lastamp = System.Guid.NewGuid();

                            ctx.MaterialFill.Add(entity);

                            ctx.SaveChanges();
                        }
                    }
                }

                result.Code = CodeType.Ok;
                result.Message = "保存成功!";

                return result;
            }

            return result;
        }