Exemple #1
0
        public void Test_IsPostfix()
        {
            var source = "test.txt";
            var result = Valid.IsPostfix(source, new string[] { "txt" });

            Console.WriteLine(result);
        }
        public async Task <IActionResult> Create(int countryId, [Bind("Id,Name,CreationDate")] Organisation organisation)
        {
            organisation.CountryId = countryId;
            if (ModelState.IsValid)
            {
                var c = (from org in _context.Organisations
                         where org.Name.Contains(organisation.Name)
                         select org).ToList();

                if (c.Count > 0)
                {
                    return(RedirectToAction("Index", "Organisations", new { id = countryId, name = _context.Countries.Where(c => c.Id == countryId).FirstOrDefault().Name }));
                }
                if (!Valid.Datecheck(organisation.CreationDate))
                {
                    return(RedirectToAction("Index", "Organisations", new { id = countryId, name = _context.Countries.Where(c => c.Id == countryId).FirstOrDefault().Name }));
                }

                _context.Add(organisation);
                await _context.SaveChangesAsync();

                // return RedirectToAction(nameof(Index));
                return(RedirectToAction("Index", "Organisations", new { id = countryId, name = _context.Countries.Where(c => c.Id == countryId).FirstOrDefault().Name }));
            }
            // ViewData["CountryId"] = new SelectList(_context.Countries, "Id", "Name", organisation.CountryId);
            //   return View(organisation);
            return(RedirectToAction("Index", "Organisations", new { id = countryId, name = _context.Countries.Where(c => c.Id == countryId).FirstOrDefault().Name }));
        }
        /// <summary>
        /// Returns true if InventoryValidation instances are equal
        /// </summary>
        /// <param name="other">Instance of InventoryValidation to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(InventoryValidation other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Id == other.Id ||
                     Id != null &&
                     Id.Equals(other.Id)
                     ) &&
                 (
                     Valid == other.Valid ||
                     Valid != null &&
                     Valid.Equals(other.Valid)
                 ) &&
                 (
                     Remaining == other.Remaining ||
                     Remaining != null &&
                     Remaining.Equals(other.Remaining)
                 ));
        }
        private static bool Validade(string outputValid)
        {
            var allValid = new List <bool>();

            try
            {
                var outputSplited = outputValid.Split(' ');

                if (outputSplited.Length != 3)
                {
                    return(false);
                }

                allValid.Add(Valid.Validade(outputSplited[0], EOutputConvert.Double));
                allValid.Add(Valid.Validade(outputSplited[1], EOutputConvert.String));
                allValid.Add(Valid.Validade(outputSplited[2], EOutputConvert.DateTime));

                if (outputSplited[1].Equals("Private") || outputSplited[1].Equals("Public"))
                {
                    allValid.Add(true);
                }
                else
                {
                    allValid.Add(false);
                }

                return(allValid.All(x => x == true));
            }
            catch
            {
                return(false);
            }
        }
 /// <summary>
 /// Called when associated validator is valid.
 /// </summary>
 /// <param name="validationContext">Validation context.</param>
 /// <param name="contextParams">Additional context parameters.</param>
 /// <param name="errors">Validation errors container.</param>
 protected override void OnValid(object validationContext, IDictionary <string, object> contextParams, IValidationErrors errors)
 {
     if (Valid != null)
     {
         Valid.GetValue(validationContext, contextParams);
     }
 }
Exemple #6
0
        /// <summary>
        /// 下載附加檔案
        /// </summary>
        /// <param name="serverPath">伺服器端的檔案路徑</param>
        /// <param name="clientPath">存檔的路徑</param>
        /// <returns></returns>
        public string DownloadFile(string serverPath, string clientPath)
        {
            string msg = Valid.GetInstance().ValidFilePath(serverPath);

            if (msg != string.Empty)
            {
                return("不存在的路徑");
            }

            try
            {
                using (Stream stream = File.Open(serverPath, FileMode.Open))
                {
                    using (FileStream fs = new FileStream(clientPath, FileMode.OpenOrCreate))
                    {
                        stream.CopyTo(fs);
                        fs.Flush();
                    }
                }

                return("下載成功");
            }
            catch (Exception ex)
            {
                LogInfo.WriteErrorInfo(ex);
                return("下載失敗");
            }
        }
        public static string GenerateFilterQuery(Valid from, Valid to, Valid cc, Valid bcc, Valid subject, Valid body, Valid date, Valid box, Valid hasAttachment)
        {
            var query = new Dictionary <string, object>();

            ValidQueryMailAddressMapperValue[from](query, "from");
            ValidQueryMailAddressMapperValue[to](query, "to");
            ValidQueryMailAddressMapperValue[cc](query, "cc");
            ValidQueryMailAddressMapperValue[bcc](query, "bcc");
            ValidQueryMailAddressMapperValue[subject](query, "subject");
            ValidQueryMailAddressMapperValue[body](query, "body");
            ValidDateBoxMapperValue[date](query, "date");
            ValidDateBoxMapperValue[box](query, "box");
            ValidDateBoxMapperValue[hasAttachment](query, "hasAttachment");
            var filter = new Dictionary <string, object>
            {
                ["resultFields"] = new List <string> {
                    "date", "body", "id", "box"
                },
                ["pageSize"] = 3,
                ["query"]    = new Dictionary <string, object>
                {
                    ["query"]      = query,
                    ["queryLogic"] = "and",
                },
            };

            return(filter.ToJson());
        }
Exemple #8
0
        public string GetAll()
        {
            Dictionary <string, object> data = Converter.JSONToDictionary(Context.Request.InputStream);
            string result, filter;
            int    pageIndex, pageRowCount;

            if (!Valid.StockGetAll(data, out result, out filter, out pageIndex, out pageRowCount))
            {
                return(result);
            }

            DataSet ds = Database.FillSet(new StockProc(StockProcType.GetAll, filter, pageIndex, pageRowCount));

            if (ds.Tables.Count == 2)
            {
                result = "{\"RESULT\":1,\"TOTALROW\":" + ds.Tables[0].Rows[0]["TOTALROW"].ToString() + ",\"PAGEINDEX\":" + ds.Tables[0].Rows[0]["PAGEINDEX"].ToString() + ",";
                ds.Tables[1].TableName = "LIST";
                result += Converter.DataTableToJSONArray(ds.Tables[1]) + "}";
                return(result);
            }
            if (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 1 && ds.Tables[0].Columns.Contains("RESULT"))
            {
                return("{\"RESULT\":" + ds.Tables[0].Rows[0]["RESULT"].ToString() + "}");
            }
            return("{\"RESULT\":-1}");
        }
        public void ValidOptionalFieldsTests(Param param, Valid type)
        {
            var request = CreateUserRequest();

            ValidOptionalFieldMapper[param](type, request);
            PerformTest(request);
        }
Exemple #10
0
        private void Test()
        {
            int b = Conv.ToInt("23");
            //Singleton<TestClass>.Instance = new TestClass();
            //Singleton<TestClass>.Instance.Print();

            //Singleton<TestClass2>.Instance = new TestClass2();
            //Singleton<TestClass2>.Instance.Print();
            TestClass aa = new TestClass();

            aa.Name = "woding";
            TestClass bb = Sys.Clone <TestClass>(aa);

            //  TestClass bb = aa;
            bb.Name = "nihao";
            MessageBox.Show(aa.Name);
            MessageBox.Show(bb.Name);

            TestClass kdfsdf = Conv.To <TestClass>(aa);

            MessageBox.Show(kdfsdf.Name);
            if (Valid.IsIpAddress("fasdfasfd"))
            {
                MessageBox.Show("ok");
            }
            else
            {
                MessageBox.Show("no");
            }
            Valid.IsDate("fasfdaf");
        }
Exemple #11
0
        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            string mail     = tbxMail.Text;
            string password = pbxPassword.Password;

            if (Valid.IsValidEmail(mail))
            {
            }
            else
            {
                MessageBox.Show($"Invalid: {mail}");
                return;
            }
            if (password.Length < 8)
            {
                MessageBox.Show($"Invalid: {password} \nYour password must have at least 8 characters ");
                return;
            }
            User user = new User()
            {
                Mail = mail, Password = password
            };

            Global.LoggedInUser = user;

            NavigationService.Navigate(new TempPage());
        }
        private Valid ModelIsValid(int id, Clients clients, ActionExecutingContext AEcontext)
        {
            Valid retValue = new Valid()
            {
                IsValid = true, Message = string.Empty
            };
            HttpMethods httpMethod = GetHttpMethod(AEcontext);

            if (httpMethod == HttpMethods.Put)
            {
                if (id != 0 && clients != null)
                {
                    if (id != clients.ClientId)
                    {
                        retValue = PrepareRetValue(false, "Client Id is not match!");
                        return(retValue);
                    }
                }
            }
            using (var validationHelper = new ValidationHelper(clients))
            {
                if (httpMethod == HttpMethods.Post || httpMethod == HttpMethods.Put)
                {
                    retValue = validationHelper.ObjectIsValid();
                    if (!retValue.IsValid)
                    {
                        return(retValue);
                    }
                }
            }


            return(retValue);
        }
Exemple #13
0
        public IActionResult Contact(ContactViewModel model)
        {
            Valid                     valid               = new Valid();
            ValidationResult          results             = valid.Validate(model);
            bool                      validationSucceeded = results.IsValid;
            IList <ValidationFailure> failures            = results.Errors;

            if (string.IsNullOrEmpty(model.Member1) && string.IsNullOrEmpty(model.Member2))
            {
                var validationMessage = "Please provide at least one member.";
                ModelState.AddModelError("Member1", validationMessage);
                ModelState.AddModelError("Member2", validationMessage);
            }
            if (model.Member1 == model.Member2)
            {
                var validationMessage = "Members can't be the same person";
                ModelState.AddModelError("Member1", validationMessage);
                ModelState.AddModelError("Member2", validationMessage);
            }
            if (model.Reason == "Other")
            {
                var validationMessage = "Please provide a comment for reason 'Other'";
                ModelState.AddModelError("Comment", validationMessage);
            }

            if (ModelState.IsValid)
            {
                //send email
                _mailService.Send("*****@*****.**", model.Reason, $"From: {model.Boss} - {model.Email}, Message: {model.Comment}");
                ViewBag.UserMessage = "Mail Sent";
                ModelState.Clear();
            }
            return(View());
        }
        public void ValidRequireFieldsTests(Valid name, Valid mail, Valid username, Valid language, Valid startDate, string timezone)
        {
            var request = CreateUserRequest(ValidNameMapper[name], null, ValidNameMapper[username], timezone, language.ToString().ToLower(), null);

            ValidMailMapper[mail](request, Param.UserPMail);
            ValidDateMapper[startDate](request, Param.UserPStartDate);
            PerformTest(request);
        }
 public ActionResult Inde(Valid val)
 {
     if (ModelState.IsValid)
     {
         return(View());
     }
     return(View("Index"));
 }
Exemple #16
0
 private void InvalidProperty(string propertyName)
 {
     if (!m_InvalidProperties.Contains(propertyName))
     {
         m_InvalidProperties.Add(propertyName);
         Valid.SetCondition(m_InvalidProperties.Count == 0);
     }
 }
//Added as a part of .NetMig 3.5
        protected void CheckValid1(object Source, ValidatorEventArgs e)
        {
            if ((Suffix.Text == "" || Prefix.Text == ""))
            {
                e.IsValid          = false;
                Valid.ErrorMessage = "";
                Valid.MarkInvalid();
            }
        }
        public async Task <AdminUserDto> LoginAsync(AdminUserLoginCommand request, CancellationToken cancellationToken)
        {
            var user = default(AdminUserEntity);

            request.Password = Encrypt.Md5By32(request.Password);

            var loginWay = "";

            if (!Valid.IsMobileNumberSimple(request.Account))
            {
                user = await db.Context.AdminUser.Where(c => c.UserName.Equals(request.Account)).FirstOrDefaultAsync(cancellationToken);

                if (user == null)
                {
                    Failure.Error("账号不存在");
                }

                loginWay = "Mobile";
            }
            else
            {
                user = await db.Context.AdminUser.Where(c => c.Mobile.Equals(request.Account)).FirstOrDefaultAsync(cancellationToken);

                if (user == null)
                {
                    Failure.Error("手机号码不存在");
                }

                loginWay = "UserName";
            }

            if (!user.Password.Equals(request.Password))
            {
                Failure.Error("密码错误");
            }
            if (user.Status != Status.Show)
            {
                Failure.Error("您的帐号禁止登录,请与管理员联系!");
            }


            user.LoginCount   += 1;
            user.LoginLastTime = DateTime.Now;
            user.LoginLastIp   = Web.IP;

            user.LoginRecords.Add(new LoginRecordEntity
            {
                AdminId   = user.Id,
                LoginIp   = user.LoginLastIp,
                LoginTime = user.LoginLastTime,
                LoginWay  = loginWay
            });

            db.Update(user);

            return(mapper.Map <AdminUserDto>(user));
        }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Value != null ? Value.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Valid.GetHashCode();
         hashCode = (hashCode * 397) ^ (Explanation != null ? Explanation.GetHashCode() : 0);
         return(hashCode);
     }
 }
Exemple #20
0
        /// <summary>
        /// 对Url进行Base64解码
        /// </summary>
        /// <param name="url">url</param>
        /// <returns></returns>
        public static string Base64Decrypt(string url)
        {
            if (!Valid.IsBase64(url))
            {
                return(url);
            }
            byte[] buffer  = Convert.FromBase64String(url);
            string tempUrl = Const.DefaultEncoding.GetString(buffer);

            return(UrlDecode(tempUrl));
        }
Exemple #21
0
        public void Test_IsBase64String()
        {
            var source  = "测试0001";
            var source1 = "5rWL6K+VMDAwMQ==";

            Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(source)));

            var result1 = Valid.IsBase64String(source1);

            Console.WriteLine(result1);
        }
        public void ConfigurationServiceValidCreateTest(Parameters parameter, Valid inputType)
        {
            var handler = new ConfigurationServiceManager();
            var request = new Dictionary <string, string>(DefaultParameters);

            request[parameter.ToString().ToLower()] = ValidCreateMapping[inputType];

            var response = handler.ConfigurationService <object>(request["service"], request["id"], request["body"], System.Net.Http.HttpMethod.Put);

            PrAssert.That(response, PrIs.SuccessfulResponse());
            PrAssert.That(response.Result, PrIs.Null);
        }
Exemple #23
0
        ///<summary>
        ///Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
        ///</summary>
        ///
        ///<returns>
        ///A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
        ///</returns>
        ///<filterpriority>2</filterpriority>
        public override string ToString()
        {
            StringBuilder str = new StringBuilder();

            str.Append("Value = ");
            foreach (char c in Value)
            {
                str.Append(c);
            }
            str.Append(" Valid = ").Append(Valid.ToString());
            return(str.ToString());
        }
Exemple #24
0
 public bool Equals(PartialKey other)
 {
     if (other is null)
     {
         return(false);
     }
     else
     {
         return(Valid.SequenceEqual(other.Valid) &&
                KeyPiece.SequenceEqual(other.KeyPiece));
     }
 }
        private void AddTriangle(int sideA, int sideB, int sideC)
        {
            var t = new Triangle(sideA, sideB, sideC);

            if (t.IsValid())
            {
                Valid.Add(t);
            }
            else
            {
                Invalid.Add(t);
            }
        }
Exemple #26
0
        public void Test_IsDomain()
        {
            var source  = "www.baidu.com";
            var source1 = "baidu.com";
            var source2 = "test.baidu.com";
            var result  = Valid.IsDomain(source);
            var result1 = Valid.IsDomain(source1);
            var result2 = Valid.IsDomain(source2);

            Console.WriteLine(result);
            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }
Exemple #27
0
        public string Report()
        {
            string result, dummydata;
            int    productid;
            Dictionary <string, object> data = Converter.JSONToDictionary(Context.Request.InputStream);

            if (!Valid.StockReport(data, out result, out productid, out dummydata))
            {
                throw new HttpRequestValidationException();
            }
            DataTable dt = Database.FillTable(new StockProc(StockProcType.Report, productid, dummydata));

            return(Converter.DataTableToJSON(dt));
        }
Exemple #28
0
        public string GetById()
        {
            string result;
            int    stockid;
            Dictionary <string, object> data = Converter.JSONToDictionary(Context.Request.InputStream);

            if (!Valid.StockGetById(data, out result, out stockid))
            {
                return(result);
            }
            DataTable dt = Database.FillTable(new StockProc(StockProcType.GetById, stockid));

            return(Converter.DataTableToJSON(dt));
        }
        public ActionResult Get(string guid)
        {
            Valid res = ValidatePass(guid);

            switch (res)
            {
            case Valid.Valid:
                return(Ok());

            case Valid.Invalid:
                return(new StatusCodeResult(410));
            }
            return(NotFound());
        }
    public static void Main(string [] args)
    {
        Valid v1 = new Valid(Test.checkInt);

        v1 += new Valid(Test.checkMax);
        v1 += new Valid(Test.checkMin);
        v1(1);
        v1(10);
        v1(20);
        v1(30);
        v1(254);
        v1(255);
        v1(256);
    }