示例#1
0
        private int GetMaxRetrieveMail()
        {
            _commonFacade = new CommonFacade();
            ParameterEntity param = _commonFacade.GetParamByName(Constants.ParameterName.MaxRetrieveMail);

            return(param != null?param.ParamValue.ToNullable <int>().Value : 200);
        }
        private void GetDescendantEntity(XElement element, string parentName)
        {
            var secondLevels = element.Elements();

            if (secondLevels.Count() > 0)
            {
                foreach (var item in secondLevels)
                {
                    string eleName   = item.Name.ToString();
                    var    subLevels = item.Elements();
                    if (subLevels.Count() > 0)
                    {
                        GetDescendantEntity(item, parentName + "." + eleName);
                    }
                    else
                    {
                        ParameterEntity entity = new ParameterEntity();
                        entity.PARAMETER_DESCRIPTION = item.Name.ToString();
                        entity.PARAMETER_DIMPATH     = "{CLUSTER,APPTYPE,APPID,STATION}";
                        entity.PARAMETER_DISPLAYNAME = item.Name.ToString();
                        entity.PARAMETER_NAME        = parentName + "." + item.Name.ToString();
                        entity.PARAMETER_PARENT_NAME = parentName;
                        entity.PARAMETER_SCOPE       = scope;
                        entity.PARAMETER_TYPE_NAME   = "STRING";
                        entity.PARAMETER_VALUE       = item.Value;
                        entityList.Add(entity);
                    }
                }
            }
        }
示例#3
0
        public static IList <ParameterEntity> TransformUriParameters(OpenApiOperation openApiOperation, string componentGroupId)
        {
            var parameterEntities = new List <ParameterEntity>();

            foreach (var openApiParameter in openApiOperation.Parameters)
            {
                var parameterEntity = new ParameterEntity
                {
                    Name         = openApiParameter.Name,
                    Description  = openApiParameter.Description,
                    In           = openApiParameter.In.ToString().ToLower(),
                    IsRequired   = openApiParameter.Required,
                    IsReadOnly   = openApiParameter.Schema?.ReadOnly ?? false,
                    Nullable     = openApiParameter.Schema?.Nullable ?? true,
                    IsDeprecated = openApiParameter.Deprecated,
                    Pattern      = openApiParameter.Schema?.Pattern,
                    Format       = openApiParameter.Schema?.Format,
                    Types        = new List <PropertyTypeEntity>
                    {
                        TransformHelper.ParseOpenApiSchema(openApiParameter.Schema, componentGroupId)
                    }
                };
                parameterEntities.Add(parameterEntity);
            }
            return(parameterEntities);
        }
 public string AddProductParameterVaule(int parameterValueId, int productId)
 {
     try
     {
         ProductEntity          PE   = _productService.GetProductById(productId);
         ParameterValueEntity   PVE  = _parameterValueService.GetParameterValueById(parameterValueId);
         ParameterEntity        ParE = PVE.Parameter;
         ProductParameterEntity PPE  = new ProductParameterEntity()
         {
             Addtime = DateTime.Now,
             //Adduser = PE.Adduser,
             Adduser        = _workContext.CurrentUser.Id.ToString(),
             Parameter      = ParE,
             ParameterValue = PVE,
             Product        = PE,
             Sort           = 0,
             Updtime        = DateTime.Now,
             //Upduser = PE.Upduser
             Upduser = _workContext.CurrentUser.Id.ToString(),
         };
         _productParameterService.Create(PPE);
         return("绑定商品属性值成功");
     }
     catch (Exception e)
     {
         return("绑定商品属性值失败");
     }
 }
示例#5
0
文件: HpFacade.cs 项目: KKPBank/CSM
        public string GetParameter(string paramName)
        {
            _commonFacade = new CommonFacade();
            ParameterEntity param = _commonFacade.GetCacheParamByName(paramName);

            return(param != null ? param.ParamValue : string.Empty);
        }
        public HttpResponseMessage AddParameterValue([FromBody] ParameterValueModel parameterValueModel)
        {
            Regex reg = new Regex(@"^[^ %@#!*~&',;=?$\x22]+$");
            var   m   = reg.IsMatch(parameterValueModel.Parametervalue);

            if (!m)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "存在非法字符!")));
            }
            ParameterEntity      pe  = _parameterService.GetParameterById(parameterValueModel.ParameterId);
            ParameterValueEntity pev = new ParameterValueEntity()
            {
                Upduser        = parameterValueModel.Upduser,
                Updtime        = DateTime.Now,
                Sort           = parameterValueModel.Sort,
                Parametervalue = parameterValueModel.Parametervalue,
                Parameter      = pe,
                // Adduser = parameterValueModel.Adduser,
                Adduser = _workContext.CurrentUser.Id.ToString(),
                Addtime = DateTime.Now,
            };

            try
            {
                _parameterValueService.Create(pev);
                return(PageHelper.toJson(PageHelper.ReturnValue(true, "添加参数值" + pev.Parametervalue + "成功")));
            }
            catch (Exception e)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "添加参数值" + pev.Parametervalue + "失败")));
            }
        }
        public HttpResponseMessage AddParameter([FromBody] ParameterModel parameter)
        {
            Regex reg = new Regex(@"^[^ %@#!*~&',;=?$\x22]+$");
            var   m   = reg.IsMatch(parameter.Name);

            if (!m)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "存在非法字符!")));
            }
            ClassifyEntity  ce = _classifyService.GetClassifyById(parameter.ClassifyId);
            ParameterEntity pe = new ParameterEntity()
            {
                Upduser  = parameter.Upduser,
                Updtime  = DateTime.Now,
                Sort     = parameter.Sort,
                Name     = parameter.Name,
                Classify = ce,
                //Adduser = parameter.Adduser,
                Adduser = _workContext.CurrentUser.Id.ToString(),
                Addtime = DateTime.Now,
            };

            try
            {
                _parameterService.Create(pe);
                return(PageHelper.toJson(PageHelper.ReturnValue(true, "添加参数" + pe.Name + "成功")));
            }
            catch (Exception e)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "添加参数" + pe.Name + "失败")));
            }
        }
        void AddData(StoreDbContext dbContext)
        {
            if (!dbContext.Products.Any())
            {
                var product = new ProductEntity("default", "description");
                dbContext.Products.Add(product);

                dbContext.SaveChanges();

                var appFeature = new FeatureEntity(product.Id, "app-feature", enabled: true);

                var toggle = new ToggleEntity(appFeature.Id, "Esquio.Toggles.XToggle");

                var stringparameter = new ParameterEntity(toggle.Id, "strparam", "value1");
                toggle.Parameters.Add(stringparameter);

                var intparameter = new ParameterEntity(toggle.Id, "intparam", "1");
                toggle.Parameters.Add(intparameter);

                appFeature.Toggles.Add(toggle);

                dbContext.Features.Add(appFeature);

                dbContext.SaveChanges();
            }
        }
示例#9
0
 public static int GetIntValue(string value)
 {
     if (Regex.IsMatch(value, @"^(0|[1-9]\d*)$"))
     {
         return(int.Parse(value));
     }
     else
     {
         return(int.Parse(ParameterEntity.FindByParameterName(value).UserParameter.Value));
     }
 }
示例#10
0
 public static bool GetBoolValue(string value)
 {
     if (Regex.IsMatch(value, @"(?:F(?:ALSE|alse)|(?:fals|tru)e|T(?:RUE|rue))"))
     {
         return(Convert.ToBoolean(value));
     }
     else
     {
         return(Convert.ToBoolean(ParameterEntity.FindByParameterName(value).UserParameter.Value));
     }
 }
        public async Task <CreateParameterResult> HandleAsync(CreateParameterCommand cmd, CancellationToken ct)
        {
            await _context.semaphore.WaitAsync();

            try
            {
                var parameters = _context.Set <ParameterEntity>();
                var rules      = _context.Set <RuleEntity>();

                //If group does not exist throw exception
                //A rule must belong to a group

                var rule = await rules.Where(g => g.ExternalId == cmd.RuleId).Select(g => g).FirstOrDefaultAsync();

                if (rule == null)
                {
                    throw new NotFoundException($"Rule '{cmd.RuleId}' not found");
                }

                //If Index already present throw exception
                //Two rules of the same group cannot have the same index

                var parametersDuplicateIndex = await parameters.Where(p => p.Rule.ExternalId == cmd.RuleId && p.Index == cmd.Index).Select(p => p).ToArrayAsync();

                if (parametersDuplicateIndex.Length > 0)
                {
                    throw new ConflictException($"Parameter with index '{cmd.Index}' already exists.");
                }

                var             externalId       = Guid.NewGuid();
                ParameterEntity createdParameter = new ParameterEntity
                {
                    ExternalId = externalId,
                    Index      = cmd.Index,
                    Value      = cmd.Value,
                    Rule       = rule
                };

                await parameters.AddAsync(createdParameter, ct);

                await _context.SaveChangesAsync();

                return(new CreateParameterResult
                {
                    Id = externalId
                });
            }
            finally
            {
                _context.semaphore.Release();
            }
        }
示例#12
0
 public bool Delete(ParameterEntity entity)
 {
     try
     {
         _parameterRepository.Delete(entity);
         return(true);
     }
     catch (Exception e)
     {
         _log.Error(e, "数据库操作出错");
         return(false);
     }
 }
示例#13
0
 public ParameterEntity Update(ParameterEntity entity)
 {
     try
     {
         _parameterRepository.Update(entity);
         return(entity);
     }
     catch (Exception e)
     {
         _log.Error(e, "数据库操作出错");
         return(null);
     }
 }
示例#14
0
    public static string ReplaceTextTags(string text)
    {
        string newText = text.Replace("<br>", "\n");
        Regex  regex   = new Regex(@"\<param=[^\>]+\>");
        Match  match   = regex.Match(newText);

        while (match.Success)
        {
            string paramName = match.Value.Replace("<param=", "").Replace(">", "");
            UnityEngine.Debug.Log(paramName);
            newText = newText.Replace(match.Value, ParameterEntity.FindByParameterName(paramName).UserParameter.Value);
            match   = match.NextMatch();
        }
        return(newText);
    }
        public void updateParameter(HttpContext context)
        {
            int             ParameterID   = Convert.ToInt32(context.Request["ParameterID"]);
            string          ParameterName = context.Request["ParameterName"];
            string          descrs        = context.Request["descr"];
            int             ParameterType = Convert.ToInt32(context.Request["ParameterType"]);
            ParameterEntity pe            = new ParameterEntity();

            pe._parameterid   = ParameterID;
            pe._parametername = ParameterName;
            pe._descr         = descrs;
            pe._parametertype = ParameterType;
            bool result = MgrServices.ParameterService.ParameterUpdata(pe);

            context.Response.Write(result);
        }
        public void InsertParameter(HttpContext context)
        {
            string          ParameterName = context.Request["ParameterName"];
            string          descr         = context.Request["descr"];
            int             ParameterType = Convert.ToInt32(context.Request["ParameterType"]);
            int             P_Delete      = Convert.ToInt32("0");
            ParameterEntity pe            = new ParameterEntity();

            pe._parametername = ParameterName;
            pe._descr         = descr;
            pe._parametertype = ParameterType;
            pe._p_delete      = P_Delete;
            bool result = MgrServices.ParameterService.ParameterInsert(pe);

            context.Response.Write(result);
        }
        public List <ParameterEntity> GetApplicationEntity()
        {
            entityList = new List <ParameterEntity>();
            string      filePath    = Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
            string      _appDir     = Path.GetDirectoryName(filePath);
            XDocument   config      = XDocument.Load(_appDir + @"\ApplicationConfig.xml");
            CommonModel commonModel = ReadIhasFileData.getInstance();
            XElement    xRoot       = config.Root;
            string      rootName    = commonModel.APPTYPE; //xRoot.Name.ToString();

            scope = commonModel.APPTYPE;
            ParameterEntity entityRoot = new ParameterEntity();

            entityRoot.PARAMETER_DESCRIPTION = rootName;
            entityRoot.PARAMETER_DISPLAYNAME = rootName;
            entityRoot.PARAMETER_DIMPATH     = "{CLUSTER,APPTYPE,APPID,STATION}";
            entityRoot.PARAMETER_NAME        = rootName;
            entityRoot.PARAMETER_PARENT_NAME = "Customer";
            entityRoot.PARAMETER_SCOPE       = scope;
            entityRoot.PARAMETER_TYPE_NAME   = "STRING";
            entityRoot.PARAMETER_VALUE       = "";
            entityList.Add(entityRoot);
            var firstLevelElts = xRoot.Elements();

            if (firstLevelElts.Count() > 0)
            {
                foreach (var item in firstLevelElts)
                {
                    string          subName = item.Name.ToString();
                    ParameterEntity entity  = new ParameterEntity();
                    entity.PARAMETER_DESCRIPTION = subName;
                    entity.PARAMETER_DISPLAYNAME = subName;
                    entity.PARAMETER_DIMPATH     = "{CLUSTER,APPTYPE,APPID,STATION}";
                    entity.PARAMETER_NAME        = rootName + "." + subName;
                    entity.PARAMETER_PARENT_NAME = rootName;
                    entity.PARAMETER_SCOPE       = scope;
                    entity.PARAMETER_TYPE_NAME   = "STRING";
                    entity.PARAMETER_VALUE       = "";
                    entityList.Add(entity);
                    GetDescendantEntity(item, rootName + "." + subName);
                }
                int count = entityList.Count();
            }
            return(entityList);
        }
示例#18
0
        public ActionResult InitEdit(string jsonData)
        {
            _commonFacade = new CommonFacade();

            #region "For show in hint"

            ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
            ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);

            int?limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();
            var singleLimitSize     = limitSingleFileSize.HasValue ? (limitSingleFileSize / 1048576) : 0;
            ViewBag.UploadLimitType = string.Format(CultureInfo.InvariantCulture, param.ParamDesc, singleLimitSize);

            #endregion

            List <DocumentTypeEntity> docTypeList = null;
            var attachVM = JsonConvert.DeserializeObject <AttachViewModel>(jsonData);

            if (attachVM.ListIndex != null)
            {
                AttachmentEntity selectedAttach = attachVM.AttachmentList[attachVM.ListIndex.Value];
                attachVM.Filename   = selectedAttach.Filename;
                attachVM.DocName    = selectedAttach.Name;
                attachVM.DocDesc    = selectedAttach.Description;
                attachVM.ExpiryDate = selectedAttach.ExpiryDateDisplay;
                docTypeList         = _commonFacade.GetDocumentTypeList(selectedAttach.AttachTypeList, Constants.DocumentCategory.Announcement);
            }
            else
            {
                docTypeList = _commonFacade.GetActiveDocumentTypes(Constants.DocumentCategory.Announcement);
            }

            if (docTypeList != null)
            {
                attachVM.DocTypeCheckBoxes = docTypeList.Select(x => new CheckBoxes
                {
                    Value   = x.DocTypeId.ToString(),
                    Text    = x.Name,
                    Checked = x.IsChecked
                }).ToList();
            }

            return(PartialView("~/Views/Attachment/_AttachEdit.cshtml", attachVM));
        }
示例#19
0
        public HttpResponseMessage DelParameter(int parameterId)
        {
            ParameterEntity pe = _parameterService.GetParameterById(parameterId);

            try
            {
                List <ParameterValueEntity> parList = _parameterValueService.GetParameterValuesByParameter(parameterId).ToList();
                foreach (var parameter in parList)
                {//先把该参数下的所有参数值删除;
                    _parameterValueService.Delete(parameter);
                }
                _parameterService.Delete(pe);//删除该参数;
                return(PageHelper.toJson(PageHelper.ReturnValue(true, "删除成功!")));
            }
            catch (Exception e)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "删除失败!")));
            }
        }
示例#20
0
        public static ParameterEntity ConvertToParameterEntity(ArgoRequest ar)
        {
            var rt = new ParameterEntity {
                Vtn          = ar.Transistors.Vtn.ToString(),
                Vtp          = ar.Transistors.Vtp.ToString(),
                NetList      = ar.NetList,
                Time         = ar.Time.ToString(),
                Signals      = string.Join(":", ar.Signals),
                Includes     = string.Join(":", ar.Includes),
                Hspice       = ar.HspicePath,
                HspiceOption = string.Join(":", ar.HspiceOptions),
                Gnd          = ar.Gnd,
                Vdd          = ar.Vdd,
                IcCommand    = string.Join(":", ar.IcCommands),
                Temperature  = ar.Temperature
            };

            ar.ResultFile = rt.Hash();

            return(rt);
        }
示例#21
0
    public static bool IsConditionValid(string formula)
    {
        formula = formula.Replace(" ", "");
        List <string> formulaList = FormulaHelper.FormatFormula(formula);

        if (formulaList.Count == 1)
        {
            // アイテムの場合
            Debug.Log(formulaList[0]);
            ItemEntity itemEntity = ItemEntity.FindByItemName(formulaList[0]);
            return(itemEntity.UserItem.IsOwned);
        }
        else
        {
            // 式の場合
            ParameterEntity paramEntity = ParameterEntity.FindByParameterName(formulaList[0]);
            if (paramEntity.Parameter.Type == Parameter.ParamType.BOOL)
            {
                return(FormulaHelper.GetBoolValue(formulaList[0]) == FormulaHelper.GetBoolValue(formulaList[2]));
            }
            else
            {
                switch (formulaList[1])
                {
                case "=":
                    return(FormulaHelper.GetIntValue(formulaList[0]) == FormulaHelper.GetIntValue(formulaList[2]));

                case "<":
                    return(FormulaHelper.GetIntValue(formulaList[0]) < FormulaHelper.GetIntValue(formulaList[2]));

                case ">":
                    return(FormulaHelper.GetIntValue(formulaList[0]) > FormulaHelper.GetIntValue(formulaList[2]));

                default:
                    return(false);
                }
            }
        }
    }
示例#22
0
        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public HttpResponseMessage Post(ParameterModel model)
        {
            if (String.IsNullOrEmpty(model.Name) || model.Id == 0)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(false, "数据异常!")));
            }

            var entity = new ParameterEntity
            {
                Category = _categoryService.GetCategoryById(model.Id),//添加时候 这里的Id传的是分类ID
                Name     = model.Name,
                Sort     = model.Sort,
                AddTime  = DateTime.Now,
                UpdTime  = DateTime.Now,
            };

            if (_parameterService.Create(entity).Id > 0)
            {
                return(PageHelper.toJson(PageHelper.ReturnValue(true, "添加成功!")));
            }
            return(PageHelper.toJson(PageHelper.ReturnValue(false, "添加失败!")));
        }
示例#23
0
        public async Task <ActionResult <ResponseEntity> > GetPremium(RequestEntity requestEntity)
        {
            try
            {
                var list = await GetParameters();

                int month = Convert.ToDateTime(requestEntity.DateOfBirth).Month;

                ParameterEntity result = list.Find(x => (x.State == requestEntity.State || x.State == "*") &&
                                                   (x.MontOfBirth == month || x.MontOfBirth == -1) &&
                                                   (x.AgeFrom <= requestEntity.Age && x.AgeTo >= requestEntity.Age));
                ResponseEntity res = new ResponseEntity()
                {
                    Premium = result.Premium
                };
                return(res);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
示例#24
0
    public void UpdateParam(string formula)
    {
        List <string>   formulaList = FormulaHelper.FormatFormula(formula);
        ParameterEntity paramEntity = ParameterEntity.FindByParameterName(formulaList[0]);

        if (formulaList.Count == 3)
        {
            if (paramEntity.Parameter.Type == Parameter.ParamType.BOOL)
            {
                paramEntity.UserParameter.UpdateValue(FormulaHelper.GetBoolValue(formulaList[2]).ToString());
            }
            if (paramEntity.Parameter.Type == Parameter.ParamType.INT)
            {
                paramEntity.UserParameter.UpdateValue(FormulaHelper.GetIntValue(formulaList[2]).ToString());
            }
        }
        else if (formulaList.Count == 5)
        {
            if (paramEntity.Parameter.Type == Parameter.ParamType.INT)
            {
                int[] values = new int[2];
                values[0] = FormulaHelper.GetIntValue(formulaList[2]);
                values[1] = FormulaHelper.GetIntValue(formulaList[4]);
                paramEntity.UserParameter.UpdateValue(FormulaHelper.Calculate(values, formulaList[3]).ToString());
            }
            else
            {
                ShowWarning(formula);
            }
        }
        else
        {
            ShowWarning(formula);
        }
        GameDataManager.Instance.SaveData();
    }
示例#25
0
        public int GetPageSizeStart()
        {
            ParameterEntity paramEntity = this.GetCacheParamByName(Constants.ParameterName.PageSizeStart);

            return((paramEntity != null) ? paramEntity.ParamValue.ToNullable <int>().Value : 15);
        }
示例#26
0
        public ActionResult InitEdit(int?attachmentId, int?customerId, string documentLevel)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Attachment").Add("AttachmentId", attachmentId)
                        .Add("CustomerId", customerId).Add("DocumentLevel", documentLevel).ToInputLogString());

            try
            {
                _commonFacade   = new CommonFacade();
                _customerFacade = new CustomerFacade();

                #region "For show in hint"

                ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);

                int?limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();
                var singleLimitSize     = limitSingleFileSize.HasValue ? (limitSingleFileSize / 1048576) : 0;
                ViewBag.UploadLimitType = string.Format(CultureInfo.InvariantCulture, param.ParamDesc, singleLimitSize);

                #endregion

                var attachVM = new AttachViewModel();
                List <DocumentTypeEntity> docTypeList = null;

                if (attachmentId.HasValue)
                {
                    AttachmentEntity selectedAttach = _customerFacade.GetAttachmentByID(attachmentId.Value, documentLevel);
                    attachVM.Filename   = selectedAttach.Filename;
                    attachVM.DocName    = selectedAttach.Name;
                    attachVM.DocDesc    = selectedAttach.Description;
                    attachVM.ExpiryDate = selectedAttach.ExpiryDateDisplay;
                    attachVM.CustomerId = selectedAttach.CustomerId;
                    attachVM.Status     = selectedAttach.Status;

                    attachVM.AttachmentId = attachmentId.Value;

                    docTypeList = _commonFacade.GetDocumentTypeList(selectedAttach.AttachTypeList, Constants.DocumentCategory.Customer);
                }
                else
                {
                    attachVM.CustomerId = customerId; // case new
                    docTypeList         = _commonFacade.GetActiveDocumentTypes(Constants.DocumentCategory.Customer);
                }

                if (docTypeList != null)
                {
                    attachVM.JsonAttachType    = JsonConvert.SerializeObject(docTypeList);
                    attachVM.DocTypeCheckBoxes = docTypeList.Select(x => new CheckBoxes
                    {
                        Value   = x.DocTypeId.ToString(),
                        Text    = x.Name,
                        Checked = x.IsChecked
                    }).ToList();
                }

                //var statusList = _commonFacade.GetStatusSelectList();
                //attachVM.StatusList = new SelectList((IEnumerable)statusList, "Key", "Value", string.Empty);

                return(PartialView("~/Views/Document/_EditAttachment.cshtml", attachVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Attachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
示例#27
0
        public ActionResult Edit(AttachViewModel attachVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Edit Attachment").Add("DocName", attachVM.DocName)
                        .Add("DocDesc", attachVM.DocDesc).ToInputLogString());

            try
            {
                if (attachVM.AttachmentId.HasValue && attachVM.AttachmentId != 0)
                {
                    ModelState.Remove("FileAttach");
                }

                if (string.IsNullOrEmpty(attachVM.ExpiryDate))
                {
                    ModelState.AddModelError("ExpiryDate", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_RequiredField, Resource.Lbl_ExpiryDate));
                }
                else
                {
                    if (attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate) < DateTime.Now.Date)
                    {
                        ModelState.AddModelError("ExpiryDate", Resource.ValErr_InvalidDate_MustMoreThanToday);
                    }
                }

                //if (attachVM.Status.HasValue == false)
                //{
                //    ModelState.AddModelError("Status", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_RequiredField, Resource.Lbl_Status_Thai));
                //}

                // Validate MaxLength
                if (attachVM.DocDesc != null && attachVM.DocDesc.Count() > Constants.MaxLength.AttachDesc)
                {
                    ModelState.AddModelError("DocDesc", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_StringLength, Resource.Lbl_Detail, Constants.MaxLength.AttachDesc));
                    goto Outer;
                }

                if (ModelState.IsValid)
                {
                    AttachmentEntity attach = new AttachmentEntity();

                    var file = attachVM.FileAttach;
                    attach.Name         = attachVM.DocName;
                    attach.Description  = attachVM.DocDesc;
                    attach.ExpiryDate   = attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate);
                    attach.CustomerId   = attachVM.CustomerId;
                    attach.AttachmentId = attachVM.AttachmentId.HasValue ? attachVM.AttachmentId.Value : 0;
                    attach.Status       = Constants.ApplicationStatus.Active;

                    #region "AttachType"

                    var selectedAttachType = attachVM.DocTypeCheckBoxes.Where(x => x.Checked == true)
                                             .Select(x => new AttachmentTypeEntity
                    {
                        DocTypeId    = x.Value.ToNullable <int>(),
                        CreateUserId = this.UserInfo.UserId
                    }).ToList();

                    if (attachVM.AttachTypeList != null && attachVM.AttachTypeList.Count > 0)
                    {
                        var prevAttachTypes = (from at in attachVM.AttachTypeList
                                               select new AttachmentTypeEntity
                        {
                            AttachmentId = at.AttachmentId,
                            Code = at.Code,
                            Name = at.Name,
                            DocTypeId = at.DocTypeId,
                            IsDelete = !selectedAttachType.Select(x => x.DocTypeId).Contains(at.DocTypeId),
                            Status = at.Status,
                            CreateUserId = this.UserInfo.UserId
                        }).ToList();

                        var dupeAttachTypes = new List <AttachmentTypeEntity>(selectedAttachType);
                        dupeAttachTypes.AddRange(prevAttachTypes);

                        var duplicates = dupeAttachTypes.GroupBy(x => new { x.DocTypeId })
                                         .Where(g => g.Count() > 1)
                                         .Select(g => (object)g.Key.DocTypeId);

                        if (duplicates.Any())
                        {
                            //Logger.Info(_logMsg.Clear().SetPrefixMsg("Duplicate ID in list")
                            //    .Add("IDs", StringHelpers.ConvertListToString(duplicates.ToList(), ",")).ToInputLogString());
                            prevAttachTypes.RemoveAll(x => duplicates.Contains(x.DocTypeId));
                        }

                        selectedAttachType.AddRange(prevAttachTypes);
                    }

                    attach.AttachTypeList = selectedAttachType;

                    #endregion

                    // Verify that the user selected a file
                    if (file != null && file.ContentLength > 0)
                    {
                        _commonFacade = new CommonFacade();
                        ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);
                        int?            limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();

                        if (file.ContentLength > limitSingleFileSize.Value)
                        {
                            ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_SingleFileSizeExceedMaxLimit, (limitSingleFileSize.Value / 1048576)));
                            goto Outer;
                        }

                        // extract only the filename
                        var fileName = Path.GetFileName(file.FileName);


                        ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                        Match           match = Regex.Match(fileName, param.ParamValue, RegexOptions.IgnoreCase);

                        if (!match.Success)
                        {
                            ModelState.AddModelError("FileAttach", Resource.ValError_FileExtension);
                            goto Outer;
                        }

                        var docFolder   = _commonFacade.GetCSMDocumentFolder();
                        int seqNo       = _commonFacade.GetNextAttachmentSeq();
                        var fileNameUrl = ApplicationHelpers.GenerateFileName(docFolder, Path.GetExtension(file.FileName), seqNo, Constants.AttachmentPrefix.Customer);

                        var targetFile = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", docFolder, fileNameUrl);
                        file.SaveAs(targetFile);

                        attach.Url         = fileNameUrl;
                        attach.Filename    = fileName;
                        attach.ContentType = file.ContentType;
                    }

                    attach.CreateUserId = this.UserInfo.UserId; // for add CustomerLog

                    _customerFacade = new CustomerFacade();
                    _customerFacade.SaveCustomerAttachment(attach);

                    return(Json(new
                    {
                        Valid = true
                    }, "text/html"));
                }

Outer:
                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }, "text/html"));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Edit Attachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = Resource.Error_System,
                    Errors = string.Empty
                }, "text/html"));
            }
        }
示例#28
0
        public ActionResult Edit(AttachViewModel attachVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("List Attachment").Add("DocName", attachVM.DocName)
                        .Add("DocDesc", attachVM.DocDesc).ToInputLogString());

            AttachmentEntity attach = attachVM.ListIndex != null ? attachVM.AttachmentList[attachVM.ListIndex.Value] : new AttachmentEntity();
            int?oldFileSize         = 0; // เพื่อเช็คขนาดไฟล์รวม

            if (attach.AttachmentId != 0)
            {
                oldFileSize = attach.FileSize; // เพื่อเช็คขนาดไฟล์รวม
                ModelState.Remove("FileAttach");
            }

            if (ModelState.IsValid)
            {
                var file = attachVM.FileAttach;
                attach.Name        = attachVM.DocName;
                attach.Description = attachVM.DocDesc;
                attach.ExpiryDate  = attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate);

                var selectedAttachType = attachVM.DocTypeCheckBoxes.Where(x => x.Checked == true)
                                         .Select(x => new AttachmentTypeEntity
                {
                    DocTypeId    = x.Value.ToNullable <int>(),
                    CreateUserId = this.UserInfo.UserId
                }).ToList();

                if (attach.AttachTypeList != null && attach.AttachTypeList.Count > 0)
                {
                    var prevAttachTypes = (from at in attach.AttachTypeList
                                           select new AttachmentTypeEntity
                    {
                        AttachmentId = at.AttachmentId,
                        Code = at.Code,
                        Name = at.Name,
                        DocTypeId = at.DocTypeId,
                        IsDelete = !selectedAttachType.Select(x => x.DocTypeId).Contains(at.DocTypeId),
                        Status = at.Status,
                        CreateUserId = this.UserInfo.UserId
                    }).ToList();

                    var dupeAttachTypes = new List <AttachmentTypeEntity>(selectedAttachType);
                    dupeAttachTypes.AddRange(prevAttachTypes);

                    var duplicates = dupeAttachTypes.GroupBy(x => new { x.DocTypeId })
                                     .Where(g => g.Count() > 1)
                                     .Select(g => (object)g.Key.DocTypeId);

                    if (duplicates.Any())
                    {
                        //Logger.Info(_logMsg.Clear().SetPrefixMsg("Duplicate ID in list")
                        //    .Add("IDs", StringHelpers.ConvertListToString(duplicates.ToList(), ",")).ToInputLogString());
                        prevAttachTypes.RemoveAll(x => duplicates.Contains(x.DocTypeId));
                    }

                    selectedAttachType.AddRange(prevAttachTypes);
                }

                attach.AttachTypeList = selectedAttachType;

                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {
                    _commonFacade = new CommonFacade();
                    ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);
                    ParameterEntity paramTotalFileSize  = _commonFacade.GetCacheParamByName(Constants.ParameterName.TotalFileSize);
                    int?            limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();
                    int?            limitTotalFileSize  = paramTotalFileSize.ParamValue.ToNullable <int>();

                    if (file.ContentLength > limitSingleFileSize.Value)
                    {
                        ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_SingleFileSizeExceedMaxLimit, (limitSingleFileSize.Value / 1048576)));
                        goto Outer;
                    }

                    int?totalSize = attachVM.AttachmentList.Where(x => x.IsDelete == false).Sum(x => x.FileSize);
                    totalSize -= oldFileSize; // กรณีแก้ไข จะลบขนาดไฟล์เก่าออก
                    totalSize += file.ContentLength;

                    if (totalSize > limitTotalFileSize.Value)
                    {
                        ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_TotalFileSizeExceedMaxLimit, (limitTotalFileSize.Value / 1048576)));
                        goto Outer;
                    }

                    // extract only the filename
                    var fileName = Path.GetFileName(file.FileName);
                    //const string regexPattern = @"^.*\.(jpg|jpeg|doc|docx|xls|xlsx|ppt|txt)$";

                    ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                    Match           match = Regex.Match(fileName, param.ParamValue, RegexOptions.IgnoreCase);

                    if (!match.Success)
                    {
                        ModelState.AddModelError("FileAttach", Resource.ValError_FileExtension);
                        goto Outer;
                    }

                    string fileExtension = Path.GetExtension(file.FileName);
                    string path;

                    using (var tmp = new TempFile())
                    {
                        path = tmp.Path;
                        Logger.Debug("-- Upload File --:Is File Exists/" + System.IO.File.Exists(path));
                    }

                    // store the file inside ~/App_Data/uploads folder
                    //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);

                    attach.Filename      = fileName;
                    attach.ContentType   = file.ContentType;
                    attach.TempPath      = path;
                    attach.FileExtension = fileExtension;
                    attach.FileSize      = file.ContentLength;

                    if (attachVM.ListIndex == null)
                    {
                        attachVM.AttachmentList.Add(attach);
                    }
                }

                return(Json(new
                {
                    Valid = true,
                    Data = attachVM.AttachmentList
                }, "text/html"));
            }

Outer:
            return(Json(new
            {
                Valid = false,
                Error = string.Empty,
                Errors = GetModelValidationErrors()
            }, "text/html"));
        }
示例#29
0
 /// <summary>
 /// 添加实体
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public static int InsertEntity(ParameterEntity entity)
 {
     return(service.InsertEntity(entity));
 }
示例#30
0
 /// <summary>
 /// 编辑实体
 /// </summary>
 /// <param name="keyValue"></param>
 /// <returns></returns>
 public static int UpdateEntity(ParameterEntity entity)
 {
     return(service.UpdateEntity(entity));
 }
示例#31
0
        void parseEntityDecl()
        {
            // <!ENTITY already parsed.

            Entity  entity;
            bool isPE = false;
            string  name, notation, val = null, systemID = null, publicID = null;

            requireWhitespace();
            if (isChar('%'))
            {
                isPE = true;
                requireWhitespace();
            }

            name = getName();
            requireWhitespace();

            if (isString("PUBLIC"))
            {
                publicID = parsePublicID();
                systemID = parseSystemLiteral();
            }
            else if (isString("SYSTEM"))
            {
                systemID = parseSystemLiteral();
            }
            else
            {
                val = getEntityValue(isPE);
            }

            if (isPE)
            {
                // Parameter entity

                entity = new ParameterEntity(name);
                entity.SystemId = systemID;
                entity.PublicId = publicID;
                ((ParameterEntity)entity).Value = val;

                dtd.AddParameterEntity(name, entity);
            }
            else if (isString("NDATA"))
            {
                // Unparsed entity

                requireWhitespace();
                notation = getName();

                entity = new UnparsedEntity(name);
                entity.SystemId = systemID;
                entity.PublicId = publicID;
                ((UnparsedEntity)entity).Notation = notation;

                dtd.AddUnparsedEntity(name, entity);
            }
            else
            {
                // Parsed general entity

                entity = new ParsedGeneralEntity(name);
                entity.SystemId = systemID;
                entity.PublicId = publicID;
                ((ParsedGeneralEntity)entity).Value = val;

                dtd.AddParsedGeneralEntity(name, entity);
            }
            discardWhitespace();
            requireChar('>');
        }