Exemplo n.º 1
0
 public CanonicalPathBuilder(string fullPath)
 {
     _fullPath = fullPath;
     ThrowHelper.ThrowIfNull(fullPath, "fullPath");
     if (_fullPath == null) throw new InvalidPathException("The path is empty.");
     _validator = new Validator(_fullPath);
 }
Exemplo n.º 2
0
    /// <summary>
    /// Saves new workflow's data and redirects to Workflow_Edit.aspx.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Event arguments</param>
    protected void ButtonOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(txtWorkflowDisplayName.Text, GetString("Development-Workflow_New.RequiresDisplayName")).NotEmpty(txtWorkflowCodeName.Text, GetString("Development-Workflow_New.RequiresCodeName"))
            .IsCodeName(txtWorkflowCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == "")
        {
            WorkflowInfo wi = WorkflowInfoProvider.GetWorkflowInfo(txtWorkflowCodeName.Text);
            if (wi == null)
            {
                int workflowId = SaveNewWorkflow();

                if (workflowId > 0)
                {
                    WorkflowStepInfoProvider.CreateDefaultWorkflowSteps(workflowId);
                    URLHelper.Redirect("Workflow_Edit.aspx?workflowid=" + workflowId + "&saved=1");
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = GetString("Development-Workflow_New.WorkflowExists");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = result;
        }
    }
Exemplo n.º 3
0
 public static string GetDriveName(string fullPath)
 {
     var validator = new Validator(fullPath);
     var drive = new DriveParser(fullPath, validator);
     validator.ThrowOnError();
     return drive.AppendTo(string.Empty);
 }
Exemplo n.º 4
0
        public void Validate_Should_Return_Error_When_Referenced_Collection_Of_Objects_Have_Errors()
        {
            // Arrange
            var testClass =
                new TestClassWithCollectionOfReferencesToAnotherClass
                {
                    TestProperty =
                        new[]
                        {
                            new TestClass { TestProperty1 = "ABC", TestProperty2 = null },
                            new TestClass { TestProperty1 = "ABC", TestProperty2 = "ABC"},
                            new TestClass { TestProperty1 = null, TestProperty2 = "ABC"}
                        }
                };

            var validator = new Validator();

            // Act
            var errors = validator.Validate(testClass);

            // Assert
            Assert.IsNotNull(errors);
            Assert.AreEqual(testClass, errors.Object);
            Assert.AreEqual(2, errors.Errors.Length);

            Assert.AreEqual("TestProperty2", errors.Errors[0].Key);
            Assert.AreEqual("Error2", errors.Errors[0].Message);
            Assert.AreEqual("TestProperty1", errors.Errors[1].Key);
            Assert.AreEqual("Error1", errors.Errors[1].Message);
        }
Exemplo n.º 5
0
    private void Save()
    {
        string validationResult = new Validator()
            .NotEmpty(txtServerName.Text, rfvServerName.ErrorMessage)
            .Result;

        if (!string.IsNullOrEmpty(validationResult))
        {
            ShowError(validationResult);
            return;
        }

        try
        {
            SMTPServerPriorityEnum priority = (SMTPServerPriorityEnum)Enum.Parse(typeof(SMTPServerPriorityEnum), ddlPriorities.SelectedValue);

            SMTPServerInfo smtpServer =
                SMTPServerInfoProvider.CreateSMTPServer(txtServerName.Text, txtUserName.Text, txtPassword.Text, chkUseSSL.Checked, priority);

            if (chkAssign.Checked && currentSite != null)
            {
                SMTPServerSiteInfoProvider.AddSMTPServerToSite(smtpServer.ServerID, currentSite.SiteID);
            }

            URLHelper.Redirect(string.Format("Frameset.aspx?smtpserverid={0}&saved=1", smtpServer.ServerID));
        }
        catch (Exception e)
        {
            ShowError(e.Message);
            return;
        }
    }
Exemplo n.º 6
0
    public Point2D gazeCoords; //average coordinates from tet gaze data

	//init
	void Start () {
        //validate gaze data
        gazeValidator = new Validator(30);

        //listen for gaze events
        GazeManager.Instance.AddGazeListener(this);
	} //end function
    /// <summary>
    /// Saves new relationship name's data and redirects to RelationshipName_Edit.aspx.
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Event arguments</param>
    protected void ButtonOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(txtRelationshipNameDisplayName.Text, GetString("General.RequiresDisplayName")).NotEmpty(txtRelationshipNameCodeName.Text, GetString("General.RequiresCodeName"))
            .IsCodeName(txtRelationshipNameCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == string.Empty)
        {
            RelationshipNameInfo rni = RelationshipNameInfoProvider.GetRelationshipNameInfo(txtRelationshipNameCodeName.Text);
            if (rni == null)
            {
                int relationshipNameId = SaveNewRelationshipName();

                if (relationshipNameId > 0)
                {
                    URLHelper.Redirect("RelationshipName_Edit.aspx?relationshipnameid=" + relationshipNameId + "&saved=1");
                }
            }
            else
            {
                ShowError(GetString("RelationshipNames.RelationshipNameAlreadyExists"));
            }
        }
        else
        {
            ShowError(result);
        }
    }
    /// <summary>
    /// Handles btnOK's OnClick event - Update resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check if input is valid
        string cultureCode = txtUICultureCode.Text.Trim();
        string result = new Validator()
            .NotEmpty(txtUICultureName.Text, rfvUICultureName.ErrorMessage)
            .NotEmpty(cultureCode, rfvUICultureCode.ErrorMessage)
            .Result;

        // Check if requested culture exists
        try
        {
            CultureInfo obj = new CultureInfo(cultureCode);
        }
        catch
        {
            result = GetString("UICulture.ErrorNoGlobalCulture");
        }

        if (!string.IsNullOrEmpty(result))
        {
            ShowError(result);
        }
        else
        {
            SaveUICulture(cultureCode);
        }
    }
Exemplo n.º 9
0
        public void Validate_Should_Return_Errors()
        {
            // Arrange
            var validator = new Validator();
            var testClass = new TestClassWithAttrs();

            // Act
            var errors = validator.Validate(testClass);

            // Assert
            Assert.AreSame(testClass, errors.Object);
            Assert.AreEqual(10, errors.Errors.Length);

            CollectionAssert.AreEquivalent(
                new[]
                    {
                        new ValidationError("staticproperty", "Static_Property"),
                        new ValidationError("publicproperty", "Public_Property"),
                        new ValidationError("internalproperty", "Internal_Property"),
                        new ValidationError("protectedproperty", "Protected_Property"),
                        new ValidationError("privateproperty", "Private_Property"),

                        new ValidationError("staticmethod", "Static_Method"),
                        new ValidationError("publicmethod", "Public_Method"),
                        new ValidationError("internalmethod", "Internal_Method"),
                        new ValidationError("protectedmethod", "Protected_Method"),
                        new ValidationError("privatemethod", "Private_Method")
                    },
                errors.Errors);
        }
		public void ShouldCopyToModelState()
		{
			var modelstate = new ModelStateDictionary();

			const string property = "";

			var validator = new Validator
            {
            	() => property.Label("Property 1").IsRequired(),
            	() => property.Label("Property 2").IsRequired(),
            	() => property.Label("Property 3").IsRequired()
            };

			try
			{
				validator.Validate();
			}
			catch (ValidationException ex)
			{
				ex.CopyToModelState(modelstate, "foo");
			}

			modelstate.Count.ShouldEqual(3);
			modelstate["foo.Property 1"].ShouldNotBeNull();
			modelstate["foo.Property 2"].ShouldNotBeNull();
			modelstate["foo.Property 3"].ShouldNotBeNull();

		}
Exemplo n.º 11
0
 public void Should_be_able_to_create_a_validator_for_a_class()
 {
     _validator = Validator.New<Order>(x =>
         {
             // No Conditions Specified
         });
 }
    public void TestValidator()
    {
      var validator = new Validator();

      Assert.AreEqual("", validator.Validate());
      Assert.AreEqual("", validator.Error);

      validator.AddValidationRule(() => TestInt).Condition(() => TestInt <= 0).Message("Test int validation message");
      validator.Validate();
      Assert.IsFalse(string.IsNullOrWhiteSpace(validator.Validate()));
      Assert.AreEqual("Test int validation message", validator.Error);

      validator.AddValidationRule(() => TestObject).Condition(() => TestObject == null).Message("Test object validation message");
      validator.Validate();
      Assert.IsTrue(validator.Error.Contains("Test int validation message"));
      Assert.IsTrue(validator.Error.Contains("Test object validation message"));

      TestInt = 100;
      validator.Validate();
      Assert.AreEqual("Test object validation message", validator.Error);
      Assert.AreEqual("Test object validation message", validator["TestObject"]);
      Assert.IsTrue(string.IsNullOrWhiteSpace(validator["TestInt"]));

      TestObject = new object();
      Assert.AreEqual("", validator.Validate());
      Assert.AreEqual("", validator.Error);

      TestObject = null;
      validator.Validate();
      Assert.AreEqual("Test object validation message", validator.Error);
      validator.RemoveValidationRule(() => TestObject);
      validator.Validate();
      Assert.IsTrue(string.IsNullOrWhiteSpace(validator.Error));
    }
Exemplo n.º 13
0
 public void TestMethod1()
 {
     var validator = new Validator();
     var ctx = new MyDbContext();
     var results = validator.CheckDbContext(ctx).AlsoCheck(DatabaseObjectType.Trigger, "dbo", "MyTrigger").Validate();
     Assert.IsTrue(!results.Any());
 }
    void nameElem_Click(object sender, EventArgs e)
    {
        // Code name validation
        string err = new Validator().IsIdentificator(nameElem.CodeName, GetString("general.erroridentificatorformat")).Result;
        if (err != String.Empty)
        {
            lblError.Visible = true;
            lblError.Text = err;
            return;
        }

        // Checking for duplicate items
        DataSet ds = AlternativeFormInfoProvider.GetAlternativeForms("FormName='" + SqlHelperClass.GetSafeQueryString(nameElem.CodeName, false) +
            "' AND FormClassID=" + classId, null);

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            lblError.Visible = true;
            lblError.Text = GetString("general.codenameexists");
            return;
        }

        // Create new info object
        AlternativeFormInfo afi = new AlternativeFormInfo();
        afi.FormID = 0;
        afi.FormGUID = Guid.NewGuid();
        afi.FormClassID = classId;
        afi.FormName = nameElem.CodeName;
        afi.FormDisplayName = nameElem.DisplayName;

        AlternativeFormInfoProvider.SetAlternativeFormInfo(afi);

        URLHelper.Redirect("AlternativeForms_Frameset.aspx?classid=" + classId + "&altformid=" + afi.FormID + "&saved=1");
    }
Exemplo n.º 15
0
        public void Check_all_possible_errors_and_get_a_list_of_custom_exceptions()
        {
            var list = new Validator().CheckThat(() => _integerToCheck)
                .IsEqualTo<ArgumentException>(17,null)
                .IsEqualTo<ArgumentException>(_integerToCheck, null)
                .IsLessThan<ArgumentException>(17, null)
                .IsLessThan<ArgumentException>(12, null)
                .IsMoreThan<ArgumentException>(12, null)
                .IsMoreThan<ArgumentException>(17, null)
                .IsLessOrEqualTo<ArgumentException>(13, null)
                .IsLessOrEqualTo<ArgumentException>(14, null)
                .IsLessOrEqualTo<ArgumentException>(17, null)
                .IsMoreOrEqualTo<ArgumentException>(13, null)
                .IsMoreOrEqualTo<ArgumentException>(14, null)
                .IsMoreOrEqualTo<ArgumentException>(17, null)
                .IsBetween<ArgumentException>(3, 9,null)
                .IsBetween<ArgumentException>(8, 17,null)
                .IsBetween<ArgumentException>(15, 18,null)
                .List();

            Assert.That(list.ErrorsCollection.First().Value.Count, Is.EqualTo(7));
            foreach (var exception in list.ErrorsCollection.First().Value)
            {
                Assert.IsInstanceOfType(typeof(ArgumentException),exception);
            }
        }
    /// <summary>
    /// Handles btnOK's OnClick event - Save resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbModuleDisplayName.Text.Trim(), GetString("Administration-Module_New.ErrorEmptyModuleDisplayName")).NotEmpty(tbModuleCodeName.Text, GetString("Administration-Module_New.ErrorEmptyModuleCodeName"))
            .IsCodeName(tbModuleCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == "")
        {
            // finds if the resource code name is unique
            if (ResourceInfoProvider.GetResourceInfo(tbModuleCodeName.Text) == null)
            {
                //Save resource info
                ResourceInfo ri = new ResourceInfo();
                ri.ResourceName = tbModuleCodeName.Text;
                ri.ResourceDisplayName = tbModuleDisplayName.Text.Trim();

                ResourceInfoProvider.SetResourceInfo(ri);

                URLHelper.Redirect("Module_Edit_Frameset.aspx?moduleID=" + ri.ResourceId + "&saved=1");
            }
            else
            {
                // Show error message
                ShowError(GetString("Administration-Module_New.UniqueCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(result);
        }
    }
    /// <summary>
    /// On btnSend click.
    /// </summary>
    protected void btnSend_Click(object sender, EventArgs e)
    {
        txtFrom.Text = txtFrom.Text.Trim();
        txtTo.Text = txtTo.Text.Trim();

        string result = new Validator()
            .NotEmpty(txtFrom.Text, GetString("System_Email.EmptyEmail"))
            .NotEmpty(txtTo.Text, GetString("System_Email.EmptyEmail"))
            .Result;

        if (result != string.Empty)
        {
            ShowError(result);
            return;
        }

        // Validate e-mail addresses
        if (!(ValidationHelper.IsEmail(txtFrom.Text) && ValidationHelper.IsEmail(txtTo.Text)))
        {
            ShowError(GetString("System_Email.ErrorEmail"));
            return;
        }

        // Send the e-mail
        try
        {
            SendEmail();
            ShowConfirmation(GetString("System_Email.EmailSent"));
        }
        catch (Exception ex)
        {
            string message = EventLogProvider.GetExceptionLogMessage(ex);
            ShowError(ex.Message, message, null);
        }
    }
Exemplo n.º 18
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check valid input
        string errMsg = new Validator().
            NotEmpty(this.txtName.Text, GetString("img.errors.filename")).
            IsFolderName(this.txtName.Text, GetString("img.errors.filename")).
            Result;

        // Prepare the path
        string path = filePath;
        if (!newFile)
        {
            path = Path.GetDirectoryName(path);
        }
        path += "/" + txtName.Text + extension;

        // Check the file name for existence
        if (!this.txtName.Text.Equals(fileName, StringComparison.InvariantCultureIgnoreCase))
        {
            if (File.Exists(path))
            {
                errMsg = GetString("general.fileexists");
            }
        }

        if (!String.IsNullOrEmpty(errMsg))
        {
            this.lblError.Text = errMsg;
            this.lblError.Visible = true;
        }
        else
        {
            try
            {
                if (!newFile && !path.Equals(filePath, StringComparison.InvariantCultureIgnoreCase))
                {
                    // Move the file to the new location
                    File.WriteAllText(filePath, this.txtContent.Text);
                    File.Move(filePath, path);
                }
                else
                {
                    // Create the file or write into it
                    File.WriteAllText(path, this.txtContent.Text);
                }

                string script = "wopener.SetRefreshAction(); window.close()";

                this.ltlScript.Text = ScriptHelper.GetScript(script);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;

                // Log the exception
                EventLogProvider.LogException("FileSystemSelector", "SAVEFILE", ex);
            }
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (customerObj == null)
        {
            return;
        }

        if (!ECommerceContext.IsUserAuthorizedToModifyCustomer())
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers");
        }

        if (customerId != 0)
        {
            string errorMessage = new Validator().NotEmpty(txtAddressLine1.Text, "Customer_Edit_Address_Edit.rqvLine")
                                                 .NotEmpty(txtAddressCity.Text, "Customer_Edit_Address_Edit.rqvCity")
                                                 .NotEmpty(txtAddressZip.Text, "Customer_Edit_Address_Edit.rqvZipCode")
                                                 .NotEmpty(txtPersonalName.Text, "Customer_Edit_Address_Edit.rqvPersonalName").Result;

            // Check country presence
            if (errorMessage == "" && (ucCountrySelector.CountryID <= 0))
            {
                errorMessage = GetString("countryselector.selectedcountryerr");
            }

            if (errorMessage == "")
            {
                // Get object
                AddressInfo addressObj = AddressInfoProvider.GetAddressInfo(addressId);
                if (addressObj == null)
                {
                    addressObj = new AddressInfo();
                }

                addressObj.AddressIsBilling = chkAddressIsBilling.Checked;
                addressObj.AddressIsShipping = chkAddressIsShipping.Checked;
                addressObj.AddressZip = txtAddressZip.Text.Trim();
                addressObj.AddressPhone = txtAddressDeliveryPhone.Text.Trim();
                addressObj.AddressPersonalName = txtPersonalName.Text.Trim();
                addressObj.AddressLine1 = txtAddressLine1.Text.Trim();
                addressObj.AddressEnabled = chkAddressEnabled.Checked;
                addressObj.AddressLine2 = txtAddressLine2.Text.Trim();
                addressObj.AddressCity = txtAddressCity.Text.Trim();
                addressObj.AddressCountryID = ucCountrySelector.CountryID;
                addressObj.AddressStateID = ucCountrySelector.StateID;
                addressObj.AddressIsCompany = chkAddressIsCompany.Checked;
                addressObj.AddressName = AddressInfoProvider.GetAddressName(addressObj);
                addressObj.AddressCustomerID = customerId;

                AddressInfoProvider.SetAddressInfo(addressObj);

                URLHelper.Redirect("Customer_Edit_Address_Edit.aspx?customerId=" + customerId + "&addressId=" + Convert.ToString(addressObj.AddressID) + "&saved=1");
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = errorMessage;
            }
        }
    }
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string errorMessage = new Validator()
            .NotEmpty(txtTimeZoneName.Text, rfvName.ErrorMessage)
            .NotEmpty(txtTimeZoneDisplayName.Text, rfvDisplayName.ErrorMessage)
            .NotEmpty(txtTimeZoneGMT.Text, rfvGMT.ErrorMessage)
            .IsCodeName(txtTimeZoneName.Text, GetString("general.invalidcodename"))
            .IsDouble(txtTimeZoneGMT.Text, rvGMTDouble.ErrorMessage)
            .Result;
        if (chkTimeZoneDaylight.Checked)
        {
            if ((!startRuleEditor.IsValid()) || (!endRuleEditor.IsValid()))
            {
                errorMessage = GetString("TimeZ.RuleEditor.NotValid");
            }
        }

        if (errorMessage == "")
        {
            // timeZoneName must to be unique
            TimeZoneInfo timeZoneObj = TimeZoneInfoProvider.GetTimeZoneInfo(txtTimeZoneName.Text.Trim());

            // if timeZoneName value is unique
            if ((timeZoneObj == null) || (timeZoneObj.TimeZoneID == zoneid))
            {
                // if timeZoneName value is unique -> determine whether it is update or insert
                if ((timeZoneObj == null))
                {
                    // get TimeZoneInfo object by primary key
                    timeZoneObj = TimeZoneInfoProvider.GetTimeZoneInfo(zoneid);
                    if (timeZoneObj == null)
                    {
                        // create new item -> insert
                        timeZoneObj = new TimeZoneInfo();
                    }
                }

                timeZoneObj.TimeZoneName = txtTimeZoneName.Text.Trim();
                timeZoneObj.TimeZoneDaylight = chkTimeZoneDaylight.Checked;
                timeZoneObj.TimeZoneDisplayName = txtTimeZoneDisplayName.Text.Trim();
                timeZoneObj.TimeZoneRuleStartIn = ValidationHelper.GetDateTime(TimeZoneInfoProvider.CreateRuleDateTime(startRuleEditor.Rule), DateTime.Now);
                timeZoneObj.TimeZoneRuleEndIn = ValidationHelper.GetDateTime(TimeZoneInfoProvider.CreateRuleDateTime(endRuleEditor.Rule), DateTime.Now);
                timeZoneObj.TimeZoneRuleStartRule = startRuleEditor.Rule;
                timeZoneObj.TimeZoneRuleEndRule = endRuleEditor.Rule;
                timeZoneObj.TimeZoneGMT = Convert.ToDouble(txtTimeZoneGMT.Text.Trim());

                TimeZoneInfoProvider.SetTimeZoneInfo(timeZoneObj);

                URLHelper.Redirect("TimeZone_Edit.aspx?zoneid=" + Convert.ToString(timeZoneObj.TimeZoneID) + "&saved=1");
            }
            else
            {
                ShowError(GetString("TimeZ.Edit.TimeZoneNameExists"));
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
Exemplo n.º 21
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        CheckConfigurationModification();

        string errorMessage = new Validator()
            .NotEmpty(txtInternalStatusDisplayName.Text.Trim(), GetString("InternalStatus_Edit.errorDisplayName"))
            .NotEmpty(txtInternalStatusName.Text.Trim(), GetString("InternalStatus_Edit.errorCodeName")).Result;

        if (!ValidationHelper.IsCodeName(txtInternalStatusName.Text.Trim()))
        {
            errorMessage = GetString("General.ErrorCodeNameInIdentificatorFormat");
        }

        if (errorMessage == "")
        {

            // Check unique name for configured site
            DataSet ds = InternalStatusInfoProvider.GetInternalStatuses("InternalStatusName = '" + txtInternalStatusName.Text.Trim().Replace("'", "''") + "' AND ISNULL(InternalStatusSiteID, 0) = " + ConfiguredSiteID, null);
            InternalStatusInfo internalStatusObj = null;
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                internalStatusObj = new InternalStatusInfo(ds.Tables[0].Rows[0]);
            }

            // if internalStatusName value is unique
            if ((internalStatusObj == null) || (internalStatusObj.InternalStatusID == mStatusid))
            {
                // if internalStatusName value is unique -> determine whether it is update or insert
                if ((internalStatusObj == null))
                {
                    // get InternalStatusInfo object by primary key
                    internalStatusObj = InternalStatusInfoProvider.GetInternalStatusInfo(mStatusid);
                    if (internalStatusObj == null)
                    {
                        // create new item -> insert
                        internalStatusObj = new InternalStatusInfo();
                        internalStatusObj.InternalStatusSiteID = ConfiguredSiteID;
                    }
                }

                internalStatusObj.InternalStatusEnabled = chkInternalStatusEnabled.Checked;
                internalStatusObj.InternalStatusName = txtInternalStatusName.Text.Trim();
                internalStatusObj.InternalStatusDisplayName = txtInternalStatusDisplayName.Text.Trim();

                InternalStatusInfoProvider.SetInternalStatusInfo(internalStatusObj);

                URLHelper.Redirect("InternalStatus_Edit.aspx?statusid=" + Convert.ToString(internalStatusObj.InternalStatusID) + "&saved=1&siteId=" + SiteID);
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = GetString("InternalStatus_Edit.InternalStatusNameExists");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = errorMessage;
        }
    }
Exemplo n.º 22
0
    /// <summary>
    /// Saves data of edited workflow from TextBoxes into DB.
    /// </summary>
    protected void ButtonOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(TextBoxWorkflowDisplayName.Text, GetString("Development-Workflow_New.RequiresDisplayName"))
            .NotEmpty(txtCodeName.Text, GetString("Development-Workflow_New.RequiresCodeName"))
            .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == "")
        {
            if (currentWorkflow != null)
            {
                // Codename must be unique
                WorkflowInfo wiCodename = WorkflowInfoProvider.GetWorkflowInfo(txtCodeName.Text);
                if ((wiCodename == null) || (wiCodename.WorkflowID == currentWorkflow.WorkflowID))
                {
                    if (currentWorkflow.WorkflowDisplayName != TextBoxWorkflowDisplayName.Text)
                    {
                        // Refresh header
                        ScriptHelper.RefreshTabHeader(Page, null);
                    }

                    currentWorkflow.WorkflowDisplayName = TextBoxWorkflowDisplayName.Text;
                    currentWorkflow.WorkflowName = txtCodeName.Text;
                    currentWorkflow.WorkflowAutoPublishChanges = chkAutoPublish.Checked;

                    // Inherited from global settings
                    if (radSiteSettings.Checked)
                    {
                        currentWorkflow.WorkflowUseCheckinCheckout = null;
                    }
                    else
                    {
                        currentWorkflow.WorkflowUseCheckinCheckout = radYes.Checked;
                    }

                    // Save workflow info
                    WorkflowInfoProvider.SetWorkflowInfo(currentWorkflow);

                    lblInfo.Visible = true;
                    lblInfo.Text = GetString("General.ChangesSaved");
                }
                else
                {
                    lblError.Visible = true;
                    lblError.Text = GetString("Development-Workflow_New.WorkflowExists");
                }
            }
            else
            {
                lblError.Visible = true;
                lblError.Text = GetString("Development-Workflow_General.WorkflowDoesNotExists");
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = result;
        }
    }
Exemplo n.º 23
0
		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var form = controllerContext.HttpContext.Request.Form;

			var order = new Order
			{
				//OrderStatusId = OrderStatus.CreatedId,
				CreatedDate = DateTime.Now,
				DispatchedDate = DateTime.Now
			};

			try
			{
				var validator = new Validator
				{
					() => UpdateOrder(order, form, bindingContext.ModelState),
					() => UpdateCardContact(order, form, bindingContext.ModelState),
					() => UpdateDeliveryContact(order, form, bindingContext.ModelState),
					() => UpdateCard(order, form, bindingContext.ModelState)
				};

				validator.Validate();
			}
			catch (ValidationException)
			{
				//Ignore validation exceptions - they will be stored in ModelState.
			}

		
			EnsureBasketCountryId(order);

			return order;
		}
Exemplo n.º 24
0
    /// <summary>
    /// Handles btnOK's OnClick event.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        FormUserControlInfo fi = null;

        // Finds whether required fields are not empty
        string result = new Validator().NotEmpty(txtControlName.Text, rfvControlName.ErrorMessage).NotEmpty(txtControlDisplayName, rfvControlDisplayName.ErrorMessage).Result;

        // Check input file validity
        if (String.IsNullOrEmpty(result))
        {
            if (!tbFileName.IsValid())
            {
                result = tbFileName.ValidationError;
            }
        }

        // Try to create new form control if everything is OK
        if (String.IsNullOrEmpty(result))
        {
            fi = new FormUserControlInfo();
            fi.UserControlDisplayName = txtControlDisplayName.Text.Trim();
            fi.UserControlCodeName = txtControlName.Text.Trim();
            fi.UserControlFileName = tbFileName.Value.ToString();
            fi.UserControlType = drpTypeSelector.ControlType;
            fi.UserControlForText = false;
            fi.UserControlForLongText = false;
            fi.UserControlForInteger = false;
            fi.UserControlForLongInteger = false;
            fi.UserControlForDecimal = false;
            fi.UserControlForDateTime = false;
            fi.UserControlForBoolean = false;
            fi.UserControlForFile = false;
            fi.UserControlForDocAttachments = false;
            fi.UserControlForGUID = false;
            fi.UserControlForVisibility = false;
            fi.UserControlShowInBizForms = false;
            fi.UserControlDefaultDataType = "Text";
            try
            {
                FormUserControlInfoProvider.SetFormUserControlInfo(fi);
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.Message.Replace("%%name%%", fi.UserControlCodeName);
            }
        }
        else
        {
            lblError.Visible = true;
            lblError.Text = result;
        }

        // If control was succesfully created then redirect to editing page
        if (String.IsNullOrEmpty(lblError.Text) && (fi != null))
        {
            URLHelper.Redirect("Frameset.aspx?controlId=" + Convert.ToString(fi.UserControlID));
        }
    }
Exemplo n.º 25
0
 public void Using_a_matches_expression()
 {
     _validator = Validator.New<Order>(x =>
         {
             x.Property(y => y.OrderId)
                 .Contains("LMNOP");
         });
 }
        public void PlayerNameTooLongShouldReturnTrue(string playerName)
        {
            var validator = new Validator();

            bool result = validator.PlayerNameIsTooLong(playerName);

            Assert.True(result, "PlayerNameTooLongShouldReturnTrue method should return \"true\"");
        }
Exemplo n.º 27
0
    /// <summary>
    /// Validate button click event
    /// </summary>
    protected void btnValidate_Click(object sender, EventArgs e)
    {
        Validator addressMatch = new Validator();
        Collection<PostalAddress> standardAddresses = addressMatch.ValidateAddress(txtAddress1.Text, txtAddress2.Text, txtCity.Text, txtState.Text, txtZip5.Text, txtZip4.Text);

        dgResult.DataSource = standardAddresses;
        dgResult.DataBind();
    }
        public void PlayerNameNullOrWhitespaceShouldReturnFalse(string playerName)
        {
            var validator = new Validator();

            bool result = validator.PlayerNameIsNullOrWhiteSpace(playerName);

            Assert.True(result, "PlayerNameNullOrWhitespaceShouldReturnFalse method should return \"true\"");
        }
        public void ValidCommandShouldReturnTrue(string command)
        {
            var validator = new Validator();

            bool result = validator.InputCommandIsValid(command);

            Assert.True(result, "InputCommandValidator method should return \"true\"");
        }
    public void Validate_8CharacterPassword_PassValidaton()
    {
      var settings = new PasswordValidationSettings { MinimumPasswordLength = 8 };
      var validator = new Validator(settings);
      var actualResult = validator.Validate("12345678");

      Assert.IsTrue(actualResult);
    }
Exemplo n.º 31
0
        private async Task GetTokenUsingServicePrincipalWithCertTest(CertIdentifierType certIdentifierType)
        {
            string testCertUrl = Environment.GetEnvironmentVariable(Constants.TestCertUrlEnv);

            // Get a certificate from key vault.
            // For security, this certificate is not hard coded in the test case, since it gets added as app credential in Azure AD, and may not get removed.
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(Constants.AzureCliConnectionString);
            KeyVaultHelper            keyVaultHelper            = new KeyVaultHelper(new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)));
            string certAsString = await keyVaultHelper.ExportCertificateAsBlob(testCertUrl).ConfigureAwait(false);

            X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(certAsString), string.Empty);

            // Create an application
            GraphHelper graphHelper = new GraphHelper(_tenantId);
            Application app         = await graphHelper.CreateApplicationAsync(cert).ConfigureAwait(false);

            // Get token using service principal, this will cache the cert
            AppAuthenticationResult authResult = null;
            int count = 5;

            string thumbprint = cert.Thumbprint?.ToLower();

            // Construct connection string using client id and cert info
            string connectionString = null;

            switch (certIdentifierType)
            {
            case CertIdentifierType.SubjectName:
            case CertIdentifierType.Thumbprint:
                string thumbprintOrSubjectName = (certIdentifierType == CertIdentifierType.Thumbprint) ? $"CertificateThumbprint={thumbprint}" : $"CertificateSubjectName={cert.Subject}";
                connectionString = $"RunAs=App;AppId={app.AppId};TenantId={_tenantId};{thumbprintOrSubjectName};CertificateStoreLocation={Constants.CurrentUserStore};";
                break;

            case CertIdentifierType.KeyVaultCertificateSecretIdentifier:
                connectionString = $"RunAs=App;AppId={app.AppId};KeyVaultCertificateSecretIdentifier={testCertUrl};";
                break;
            }

            AzureServiceTokenProvider astp =
                new AzureServiceTokenProvider(connectionString);

            if (certIdentifierType == CertIdentifierType.SubjectName ||
                certIdentifierType == CertIdentifierType.Thumbprint)
            {
                // Import the certificate
                CertUtil.ImportCertificate(cert);
            }

            while (authResult == null && count > 0)
            {
                try
                {
                    await astp.GetAccessTokenAsync(Constants.KeyVaultResourceId);

                    authResult = await astp.GetAuthenticationResultAsync(Constants.SqlAzureResourceId, _tenantId);
                }
                catch
                {
                    // It takes time for Azure AD to realize a new application has been added.
                    await Task.Delay(20000);

                    count--;
                }
            }

            if (certIdentifierType == CertIdentifierType.SubjectName ||
                certIdentifierType == CertIdentifierType.Thumbprint)
            {
                // Delete the cert
                CertUtil.DeleteCertificate(cert.Thumbprint);

                var deletedCert = CertUtil.GetCertificate(cert.Thumbprint);
                Assert.Null(deletedCert);
            }

            // Get token again using a cert which is deleted, but in the cache
            await astp.GetAccessTokenAsync(Constants.SqlAzureResourceId, _tenantId);

            // Delete the application and service principal
            await graphHelper.DeleteApplicationAsync(app);

            Validator.ValidateToken(authResult.AccessToken, astp.PrincipalUsed, Constants.AppType, _tenantId,
                                    app.AppId, cert.Thumbprint, expiresOn: authResult.ExpiresOn);
        }
Exemplo n.º 32
0
 public void IsWithinRange_NumOutsideInclusiveRange_ReturnsFalse(int test, int min, int max)
 {
     //TODO: Test the IsWithinRange method in the Validator class
     Assert.IsFalse(Validator.IsWithinRange(test, min, max));
 }
Exemplo n.º 33
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.WriteLine("1) Display Categories");
                    Console.WriteLine("2) Add Category");
                    Console.WriteLine("3) Display Category and related products");
                    Console.WriteLine("4) Display all Categories and their related products");
                    choice = Console.ReadLine();
                    Console.WriteLine("\"q\" to quit");
                    Console.Clear();
                    logger.Info($"Option {choice} selected");
                    if (choice == "1")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.OrderBy(p => p.CategoryName);

                        Console.WriteLine($"{query.Count()} records returned");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName} - {item.Description}");
                        }
                    }
                    else if (choice == "2")
                    {
                        Category category = new Category();
                        Console.WriteLine("Enter Category Name:");
                        category.CategoryName = Console.ReadLine();
                        Console.WriteLine("Enter the Category Description:");
                        category.Description = Console.ReadLine();

                        ValidationContext       context = new ValidationContext(category, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();

                        var isValid = Validator.TryValidateObject(category, context, results, true);
                        if (isValid)
                        {
                            var db = new NorthwindContext();
                            // check for unique name
                            if (db.Categories.Any(c => c.CategoryName == category.CategoryName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" }));
                            }
                            else
                            {
                                logger.Info("Validation passed");
                                db.Categories.Add(category);
                                db.SaveChanges();
                            }
                        }
                        if (!isValid)
                        {
                            foreach (var result in results)
                            {
                                logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                            }
                        }
                    }
                    else if (choice == "3")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.OrderBy(p => p.CategoryId);

                        Console.WriteLine("Select the category whose products you want to display:");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        int id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");
                        Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                        Console.WriteLine($"{category.CategoryName} - {category.Description}");
                        foreach (Product p in category.Products)
                        {
                            Console.WriteLine(p.ProductName);
                        }
                    }
                    else if (choice == "4")
                    {
                        var db    = new NorthwindContext();
                        var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId);
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName}");
                            foreach (Product p in item.Products)
                            {
                                Console.WriteLine($"\t{p.ProductName}");
                            }
                        }
                    }
                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
Exemplo n.º 34
0
    /// <summary>
    /// Creates document.
    /// </summary>
    public int Save()
    {
        // Validate input data
        string message = new Validator().NotEmpty(txtDocumentName.Text.Trim(), GetString("om.enterdocumentname")).Result;

        if (message != String.Empty)
        {
            ShowError(message);
            return(0);
        }

        if (mNode == null)
        {
            ShowError(GetString("general.invalidparameters"));
            return(0);
        }

        // Select parent node
        TreeNode parent = mTree.SelectSingleNode(SiteContext.CurrentSiteName, ucPath.Value.ToString(), TreeProvider.ALL_CULTURES, false, null, false);

        if (parent == null)
        {
            ShowError(GetString("om.pathdoesnotexists"));
            return(0);
        }

        // Check security
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(parent.NodeID, mNode.NodeClassName))
        {
            RedirectToAccessDenied(GetString("cmsdesk.notauthorizedtocreatedocument"));
            return(0);
        }

        var newDocument = ProcessAction(mNode, parent, "copynode", false, true, true);

        if (newDocument == null)
        {
            ShowError(string.Format(GetString("om.invalidchildtype"), parent.ClassName));
            return(0);
        }

        // Get all language translations
        var documents = DocumentHelper.GetDocuments()
                        .All()
                        .OnCurrentSite()
                        .AllCultures()
                        .WhereEquals("NodeID", newDocument.NodeID);

        // Limit length to 100 characters
        string documentName = TextHelper.LimitLength(txtDocumentName.Text.Trim(), 100, String.Empty);

        // Update all documents and delete all aliases
        foreach (var document in documents)
        {
            UpdateDocument(document, documentName);
            DocumentAliasInfoProvider.DeleteNodeAliases(document.NodeID);

            // Set new node to any updated document to have updated info
            newDocument = document;
        }

        // Create new AB variant if AB test defined
        if (!CreateABVariant(newDocument))
        {
            return(0);
        }

        // Get the page mode
        if (PortalContext.ViewMode != ViewModeEnum.EditLive)
        {
            PortalContext.ViewMode = ViewModeEnum.EditForm;
        }
        txtDocumentName.Text = String.Empty;

        return(newDocument.NodeID);
    }
 private void dtp_Validating(object sender, CancelEventArgs e)
 {
     Validator.ObaveznoPoljeDtp(sender as DateTimePicker, e, errorProvider, Properties.Resources.ObaveznoPolje);
 }
Exemplo n.º 36
0
        private void dataGridview_KeyPress(object sender, KeyPressEventArgs e)
        {
            string texto = txt.Text;

            Validator.isDecimal(e, texto);
        }
Exemplo n.º 37
0
 private bool CanAddBlog()
 {
     return(Validator.IsValidTumblrUrl(crawlerService.NewBlogUrl));
 }
Exemplo n.º 38
0
 public void IsValidSsn_InvalidInput_ReturnsFalse(string input)
 {
     //TODO: Test the IsValidSSN method in the Validator class
     Assert.IsFalse(Validator.IsSsn(input));
 }
Exemplo n.º 39
0
 /**
  * Helper method to validate the object we want to persist against the validation annotations.
  * Will throw a ValidationException upon failing.
  */
 private void Validate(Domain.Project.Project project)
 {
     Validator.ValidateObject(project, new ValidationContext(project), true);
 }
Exemplo n.º 40
0
        public List <Consultation> UploadConsultationResult()
        {
            IWorkbook     workbook    = null;
            StringBuilder responseMsg = new StringBuilder();

            //获取绝对路径
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.ConsultationPath);
            //保存文件
            string saveName = FileHelper.Upload(HttpContext.Current, path);
            //string saveName = "Consultation_131568322669228587.xls";

            //读取标题
            string applicationConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "ApplicationConsultation.json");
            string projectConfig     = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "ProjectConsultation.json");

            Dictionary <string, string> applicationTitleMap = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(applicationConfig));
            Dictionary <string, string> projectTitleMap     = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(projectConfig));

            List <AddConsultationDTO> consultations = new List <AddConsultationDTO>();

            try
            {
                workbook = WorkbookFactory.Create(Path.Combine(path, saveName));

                foreach (ISheet sheet in workbook)
                {
                    //检查标题是否合法,记录标题的列下标
                    Dictionary <string, int> propertyIndex = null;
                    int typeTag = ParseTitle(applicationTitleMap, projectTitleMap, sheet, out propertyIndex);
                    sheet.RemoveRow(sheet.GetRow(0));
                    if (typeTag > 2 || typeTag < 1)
                    {
                        responseMsg.Append(sheet.SheetName + "标题不合法");
                        continue;
                    }

                    //判断是申请书还是项目评审结果
                    Type type = typeTag == 1 ? typeof(AddApplicationConsultationDTO) : typeof(AddProjectConsultationDTO);

                    List <ValidationResult> validationsResults = new List <ValidationResult>();

                    foreach (IRow row in sheet)
                    {
                        //一行数据转化成一个consultation对象
                        var consultation = ParseConsultation(row, type, propertyIndex);

                        //检查实体合法性
                        var context = new ValidationContext(consultation, null, null);
                        validationsResults.Clear();
                        Validator.TryValidateObject(consultation, context, validationsResults, true);
                        foreach (var result in validationsResults)
                        {
                            responseMsg.Append(string.Format("{0}表{1}行:{2}", sheet.SheetName, row.RowNum, result.ErrorMessage));
                        }

                        if (validationsResults.Count() == 0)
                        {
                            consultations.Add(consultation);
                        }
                    }
                }

                //检查申请书状态
                foreach (var acd in consultations.OfType <AddApplicationConsultationDTO>())
                {
                    var application = _ctx.Applications.FirstOrDefault(a => a.ApplicationId == acd.ApplicationId);
                    if (application == null || application.CurrentYear != SystemConfig.ApplicationStartYear || application.Status != ApplicationStatus.FINISH_REVIEW)
                    {
                        responseMsg.Append(string.Format("编号为{0}的申请书不符合条件", acd.ApplicationId));
                    }
                }

                //检查项目状态
                foreach (var pcd in consultations.OfType <AddProjectConsultationDTO>())
                {
                    var project = _ctx.Projects.FirstOrDefault(p => p.ProjectId == pcd.ProjectId);
                    if (project == null || project.Status != ProjectStatus.ACTIVE)
                    {
                        responseMsg.Append(string.Format("编号为{0}的项目不符合条件", pcd.ProjectId));
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (workbook != null)
                {
                    workbook.Close();
                }
            }

            //有问题抛出异常
            if (responseMsg.Length > 0)
            {
                throw new OtherException(responseMsg.ToString());
            }

            //插入数据
            using (var transaction = _ctx.Database.BeginTransaction())
            {
                try
                {
                    //申请书评审意见
                    foreach (var item in consultations.OfType <AddApplicationConsultationDTO>())
                    {
                        var ac = (ApplicationConsultation)TypeConverter(item);

                        _ctx.Consultations.Add(ac);

                        var application = _ctx.Applications.FirstOrDefault(a => a.ApplicationId == ac.ApplicationId);

                        switch (ac.Result)
                        {
                        case ApplicationConsultationResult.STORAGE:
                            application.Status = ApplicationStatus.STORAGE;

                            //院管理员导入咨询审议结果入库(临时使用,项目重构时修改)
                            //通知打点:发给普通用户
                            //_noticeService.AddNotice(
                            //    _noticeService.GetUserIdByApplicationId(application.ApplicationId), 24,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });
                            //通知打点:发给单位管理员
                            //_noticeService.AddNoticeList(
                            //    _noticeService.GetInstManagerIdsbyAppId(application.ApplicationId), 45,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });

                            break;

                        case ApplicationConsultationResult.SUPPORT:
                            var project = AddProject(application, ac);
                            AddAnnualTask(project, ac);
                            application.Status = ApplicationStatus.SUPPORT;

                            //院管理员导入咨询审议结果给予出库资助(临时使用,项目重构时修改)
                            //通知打点:发给普通用户
                            //_noticeService.AddNotice(
                            //    _noticeService.GetUserIdByApplicationId(application.ApplicationId), 23,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });
                            //通知打点:发给单位管理员
                            //_noticeService.AddNoticeList(
                            //    _noticeService.GetInstManagerIdsbyAppId(application.ApplicationId), 44,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });

                            //提醒项目负责人填写任务书(临时使用,项目重构时修改)
                            //通知打点:发给项目负责人
                            //_noticeService.AddNotice(
                            //    _noticeService.GetUserIdByApplicationId(application.ApplicationId), 25);

                            break;

                        case ApplicationConsultationResult.UNSUPPORT:
                            application.Status = ApplicationStatus.UNSUPPORT;

                            //院管理员导入咨询审议结果给不资助(临时使用,项目重构时修改)
                            //通知打点:发给普通用户
                            //_noticeService.AddNotice(
                            //    _noticeService.GetUserIdByApplicationId(application.ApplicationId), 22,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });
                            //通知打点:发给单位管理员
                            //_noticeService.AddNoticeList(
                            //    _noticeService.GetInstManagerIdsbyAppId(application.ApplicationId), 43,
                            //    new Dictionary<string, string> {
                            //        { "ApplicationName", application.ProjectName }
                            //    });

                            break;

                        default:
                            throw new OtherException("评审结果状态错误");
                        }
                    }

                    //项目评审意见
                    foreach (var item in consultations.OfType <AddProjectConsultationDTO>())
                    {
                        var pc = (ProjectConsultation)TypeConverter(item);
                        _ctx.Consultations.Add(pc);

                        var project = _ctx.Projects.FirstOrDefault(p => p.ProjectId == item.ProjectId);

                        switch (pc.Result)
                        {
                        case ProjectConsultationResult.CONTINUE:
                            AddAnnualTask(project, pc);
                            break;

                        case ProjectConsultationResult.SUSPEND:
                            project.Status = ProjectStatus.FINISH;
                            break;

                        default:
                            throw new OtherException("评审结果状态错误");
                        }
                    }

                    _ctx.SaveChanges();
                    transaction.Commit();
                    return(null);
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    throw e;
                }
            }
        }
Exemplo n.º 41
0
        private static IEnumerable <MethodDefinition> GetAdviceMethods(TypeDefinition adviceClassType)
        {
            Validator.ValidateAdviceClassType(adviceClassType);

            return(adviceClassType.Methods.Where(m => m.CustomAttributes.HasAttributeOfType <AdviceAttribute>()));
        }
Exemplo n.º 42
0
        /// <summary>
        /// Throws an Error if the Object is not Valid
        /// </summary>
        public virtual void Validate()
        {
            var context = new ValidationContext(this, serviceProvider: null, items: null);

            Validator.ValidateObject(this, context);
        }
        /// <summary>
        /// Gets all channels playing the specified game type. The search can be limited to a maximum number of results to speed
        /// up the operation as it can take a long time on large channels. This maximum number is a lower threshold and slightly
        /// more than the maximum number may be returned.
        /// </summary>
        /// <param name="gameType">The game type to search for</param>
        /// <param name="maxResults">The maximum number of results. Will be either that amount or slightly more</param>
        /// <returns>All channels with the specified game type</returns>
        public async Task <IEnumerable <ChannelModel> > GetChannelsByGameType(GameTypeSimpleModel gameType, uint maxResults = 1)
        {
            Validator.ValidateVariable(gameType, "gameType");

            return(await this.GetPagedNumberAsync <ChannelModel>("types/" + gameType.id + "/channels", maxResults));
        }
    /// <summary>
    /// Validates the form. If validation succeeds returns true, otherwise returns false.
    /// </summary>
    private bool Validate()
    {
        bool isValid = true;

        // Validate form fields
        string errMsg = new Validator().NotEmpty(txtKeyName.Text.Trim(), ResHelper.GetString("general.requirescodename"))
            .NotEmpty(txtKeyDisplayName.Text.Trim(), ResHelper.GetString("general.requiresdisplayname"))
            .IsIdentifier(txtKeyName.Text.Trim(), GetString("general.erroridentifierformat"))
            .Result;

        // Validate default value format
        if (!String.IsNullOrEmpty(DefaultValue))
        {
            switch (drpKeyType.SelectedValue)
            {
                case "double":
                    if (!ValidationHelper.IsDouble(DefaultValue))
                    {
                        lblDefValueError.Text = ResHelper.GetString("settings.validationdoubleerror");
                    }
                    break;

                case "int":
                    if (!ValidationHelper.IsInteger(DefaultValue))
                    {
                        lblDefValueError.Text = ResHelper.GetString("settings.validationinterror");
                    }
                    break;
            }

            if (!String.IsNullOrEmpty(lblDefValueError.Text))
            {
                lblDefValueError.Visible = true;
                isValid = false;
            }
        }

        if (!ucSettingsKeyControlSelector.IsValid())
        {
            errMsg = GetString("settingskeyedit.selectcustomcontrol");
        }

        if (String.IsNullOrEmpty(errMsg))
        {
            // Check if the code name is unique
            var key = SettingsKeyInfoProvider.GetSettingsKeyInfo(txtKeyName.Text.Trim());
            if ((key != null) && (key.KeyID != SettingsKeyID))
            {
                errMsg = GetString("general.codenameexists");
            }
        }

        // Set up error message
        if (!String.IsNullOrEmpty(errMsg))
        {
            ShowError(errMsg);
            isValid = false;
        }

        return isValid;
    }
Exemplo n.º 45
0
 public bool TryValidate(out ICollection <ValidationResult> results)
 {
     results = new List <ValidationResult>();
     return(Validator.TryValidateObject(this, new ValidationContext(this, serviceProvider: null, items: null), results, validateAllProperties: true));
 }
Exemplo n.º 46
0
 public virtual void Validate()
 {
     Validator.ValidateObject(this, new ValidationContext(this), validateAllProperties: true);
 }
Exemplo n.º 47
0
 private void ValidateFields()
 {
     Validator.ValidateIntRange(this.seats, Constants.MinSeats, Constants.MaxSeats, string.Format(Constants.NumberMustBeBetweenMinAndMax, SeatsProperty, Constants.MinSeats, Constants.MaxSeats));
 }
    /// <summary>
    /// Save button action.
    /// </summary>
    protected void ObjectManager_OnSaveData(object sender, SimpleObjectManagerEventArgs e)
    {
        // Template has to exist
        if (PageTemplate == null)
        {
            return;
        }

        // Limit text length
        txtTemplateCodeName.Text    = TextHelper.LimitLength(txtTemplateCodeName.Text.Trim(), 100, "");
        txtTemplateDisplayName.Text = TextHelper.LimitLength(txtTemplateDisplayName.Text.Trim(), 200, "");

        // Finds whether required fields are not empty
        string result = String.Empty;

        result = new Validator().NotEmpty(txtTemplateDisplayName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateDisplayName")).NotEmpty(txtTemplateCodeName.Text, GetString("Administration-PageTemplate_General.ErrorEmptyTemplateCodeName"))
                 .IsCodeName(txtTemplateCodeName.Text, GetString("general.invalidcodename"))
                 .Result;

        if ((result == String.Empty) && (SelectedPageType == PageTemplateTypeEnum.Aspx || SelectedPageType == PageTemplateTypeEnum.AspxPortal))
        {
            if (!FileSystemSelector.IsValid())
            {
                result = FileSystemSelector.ValidationError;
            }
        }

        // If name changed, check if new name is unique
        if ((result == String.Empty) && (CMSString.Compare(PageTemplate.CodeName, txtTemplateCodeName.Text, true) != 0))
        {
            if (PageTemplateInfoProvider.PageTemplateNameExists(txtTemplateCodeName.Text))
            {
                result = GetString("general.codenameexists");
            }
        }


        // Check dashboard prerequisites
        if ((PageTemplate.PageTemplateId > 0) && (SelectedPageType == PageTemplateTypeEnum.Dashboard))
        {
            // Check live site usage
            TreeProvider            tp         = new TreeProvider(CMSContext.CurrentUser);
            NodeSelectionParameters parameters = new NodeSelectionParameters()
            {
                ClassNames = TreeProvider.ALL_CLASSNAMES,
                SiteName   = TreeProvider.ALL_SITES,
                Columns    = "NodeID",
                Where      = String.Format("DocumentPageTemplateID = {0} OR NodeTemplateID = {0} OR NodeWireframeTemplateID = {0}", PageTemplate.PageTemplateId)
            };

            DataSet ds = tp.SelectNodes(parameters);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                result = GetString("template.dahsboardliveused");
            }

            // Check valid zones
            if (String.IsNullOrEmpty(result))
            {
                PageTemplateInstance inst = PageTemplate.TemplateInstance;
                if (inst != null)
                {
                    foreach (WebPartZoneInstance zone in inst.WebPartZones)
                    {
                        switch (zone.WidgetZoneType)
                        {
                        case WidgetZoneTypeEnum.Dashboard:
                        case WidgetZoneTypeEnum.None:
                            continue;
                        }

                        result = GetString("template.dashboardinvalidzone");
                        break;
                    }
                }
            }
        }

        if (String.IsNullOrEmpty(result))
        {
            // Update page template info
            PageTemplate.DisplayName = txtTemplateDisplayName.Text;
            PageTemplate.CodeName    = txtTemplateCodeName.Text;
            PageTemplate.Description = txtTemplateDescription.Text;
            PageTemplate.CategoryID  = Convert.ToInt32(categorySelector.Value);

            if (SelectedPageType == PageTemplateTypeEnum.MVC)
            {
                // MVC template
                PageTemplate.IsPortal = false;
                PageTemplate.FileName = String.Empty;

                PageTemplate.ShowAsMasterTemplate     = false;
                PageTemplate.PageTemplateCloneAsAdHoc = false;

                PageTemplate.PageTemplateDefaultController = txtController.Text;
                PageTemplate.PageTemplateDefaultAction     = txtAction.Text;
            }
            else if (SelectedPageType == PageTemplateTypeEnum.Portal)
            {
                // Portal template of various types
                PageTemplate.IsPortal = true;
                PageTemplate.FileName = String.Empty;

                // Save inherit levels
                if (!chkShowAsMasterTemplate.Checked)
                {
                    PageTemplate.InheritPageLevels = ValidationHelper.GetString(lvlElem.Value, "");
                }
                else
                {
                    PageTemplate.InheritPageLevels = "/";
                }

                // Show hide inherit levels radio buttons
                PageTemplate.ShowAsMasterTemplate     = chkShowAsMasterTemplate.Checked;
                PageTemplate.PageTemplateCloneAsAdHoc = chkAdHoc.Checked;
            }
            else
            {
                // ASPX page templates
                PageTemplate.IsPortal = false;
                PageTemplate.FileName = FileSystemSelector.Value.ToString();

                PageTemplate.ShowAsMasterTemplate     = false;
                PageTemplate.PageTemplateCloneAsAdHoc = false;

                PageTemplate.InheritPageLevels = "";
            }

            PageTemplate.PageTemplateType = SelectedPageType;

            // Set ad-hoc status
            PageTemplate.IsReusable = pageTemplateIsReusable;
            if (pageTemplateIsReusable)
            {
                PageTemplate.PageTemplateNodeGUID = Guid.Empty;
            }

            PageTemplate.WebParts = pageTemplateWebParts;

            try
            {
                // Save the template and update the header
                PageTemplateInfoProvider.SetPageTemplateInfo(PageTemplate);
                ScriptHelper.RegisterStartupScript(this, typeof(string), "pageTemplateSaveScript", ScriptHelper.GetScript("RefreshContent()"));
                ShowChangesSaved();
            }
            catch (UnauthorizedAccessException ex)
            {
                ShowError(ResHelper.GetStringFormat("general.sourcecontrolerror", ex.Message));
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
        }
        else
        {
            rfvTemplateDisplayName.Visible = false;
            rfvTemplateCodeName.Visible    = false;

            ShowError(result);
        }
    }
 private void cmb_Validating(object sender, CancelEventArgs e)
 {
     Validator.ObaveznoPoljeCmb(sender as ComboBox, e, errorProvider, Properties.Resources.ObaveznoPolje);
 }
Exemplo n.º 50
0
 protected override void Validate()
 {
     base.Validate();
     Validator.CheckRange("cpid", cpid, -1, null);
     Validator.CheckRange("price", price, -1, null);
 }
Exemplo n.º 51
0
 protected sealed override bool ValidateFields(out string message)
 {
     return(Validator.ValidateName(_view.NozzleName, out message));
 }
Exemplo n.º 52
0
 public IEnumerable <ValidationError> Validate()
 {
     return(Validator.Validate <PaymentTokenRequest, PaymentTokenRequestValidator>(this));
 }
 public bool ShowHelpRequired(string[] args)
 {
     return(!Validator.IsArgumentValid(args));
 }
Exemplo n.º 54
0
 public ValidatorTest()
 {
     _validator = new Validator();
 }
Exemplo n.º 55
0
        protected void convertButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (inputTextBox.Text.Trim(' ').Length == 0)
                {
                    throw new NothingWillComeOfNothingException();
                }
                else if (inputTextBox.Text.Trim(' ') == ".")
                {
                    throw new IsNaNException();
                }
                else
                {
                    // clear resultLabel
                    resultLabel.Text = "";

                    // instantiate Number object from user inputs
                    Number number = new Number(Convert.ToInt16(originDropDownList.SelectedValue),
                                               Number.MasterNumeralSystem.Take(Convert.ToInt16(originDropDownList.SelectedValue)).ToList(),
                                               originDropDownList.SelectedItem.Text,
                                               Convert.ToInt16(targetDropDownList.SelectedValue),
                                               Number.MasterNumeralSystem.Take(Convert.ToInt16(targetDropDownList.SelectedValue)).ToList(),
                                               inputTextBox.Text);

                    // prepare input for use
                    if (number.input[0] == '-')
                    {
                        number.input         = number.input.TrimStart('-');
                        number.inputNegative = true;
                    }
                    else
                    {
                        number.inputNegative = false;
                    }

                    number.input = number.input.TrimStart(' ', '0');

                    if (number.input.Contains('.'))
                    {
                        number.input = number.input.TrimEnd('0');
                    }

                    if (number.input == "." || number.input.Length == 0)
                    {
                        number.input = "0";
                    }

                    number.inputArray = number.input.ToCharArray();

                    // validate user input
                    if (Validator.ValidateInput(number))
                    {
                        // avoid rounding embarrassment
                        if (number.originBase == number.targetBase)
                        {
                            number.targetResult = number.input;
                        }
                        else
                        {
                            // convert input to decimal
                            number.inputAsDecimal = Converter.ConvertInputToDecimal(number);

                            // prepare inputAsDecimal for use, preventing scientific notation
                            number.inputAsDecimalString = number.inputAsDecimal.ToString(Formatter.Notation);
                            number.inputAsDecimalArray  = number.inputAsDecimalString.ToCharArray();

                            // convert decimal to target base
                            number.targetResult = Converter.ConvertDecimalToTarget(number);
                        }
                        // display results
                        resultLabel.Text = Formatter.FormatConversionForDisplay(number);
                    }
                }
            }
            // exception handling
            catch (NothingWillComeOfNothingException)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>Please fill out all required fields</span>";
            }
            catch (IsNaNException)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>Please enter a valid number</span>";
            }
            catch (OriginNumeralSystemLacksCharacterException ex)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>Please only enter characters that exist in the " + ex.NumeralSystemName + " numeral system</span>";
            }
            catch (TooManyPeriodsException)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>Please do not enter multiple periods</span>";
            }
            catch (NoDogsOnTheMoonException)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>The Base 1 (Unary) numeral system lacks fractions and the digit 0</span>";
            }
            catch (OverflowException)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>Input exceeds the maximum value of the C# long data type and cannot be processed</span>";
            }
            catch (Exception ex)
            {
                resultLabel.Text = "<span style='color:#B33A3A;'>The following error has occurred: " + ex.Message + "</span>";
            }
        }
Exemplo n.º 56
0
 /**
  * Helper method to validate the object we want to persist against the validation annotations.
  * Will throw a ValidationException upon failing.
  */
 private void Validate(ProjectPhase phase)
 {
     Validator.ValidateObject(phase, new ValidationContext(phase), true);
 }
Exemplo n.º 57
0
 private void ValidateRow(int value)
 {
     Validator.CheckIfInRange(value, 0, GlobalConstants.GridRowsCount, GlobalConstants.InvalidRowMsg);
 }
Exemplo n.º 58
0
 private void ValidateCol(int value)
 {
     Validator.CheckIfInRange(value, 0, GlobalConstants.GridColsCount, GlobalConstants.InvalidColMsg);
 }
Exemplo n.º 59
0
 public Adapter_DivToTable(IHtmlDivTechnical technical, Validator validator) : base(technical, validator)
 {
     validator.AssertTrue(() => technical.Id.Equals("table"));
 }
Exemplo n.º 60
0
        /// <summary>
        /// Validator checks if all the input fields are entered correctly and then processes to another view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SignUpBtn_Click(object sender, EventArgs e)
        {
            Validator validator  = new Validator();
            bool      validation = true;

            if (!validator.CheckName(name.Text))
            {
                displayMessage(GetString(Resource.String.Register_Name_Error));
                validation = false;
            }
            else
            {
                validation = true;
            }
            if (!validator.CheckSurname(surname.Text))
            {
                displayMessage(GetString(Resource.String.Register_Surname_Error));
                validation = false;
            }
            else
            {
                validation = true;
            }
            if (!validator.CheckNickname(username.Text))
            {
                displayMessage(GetString(Resource.String.Register_Nickname_Error));
                validation = false;
            }
            else
            {
                validation = true;
            }
            if (!validator.CheckPassword(password.Text))
            {
                displayMessage(GetString(Resource.String.Register_Password_Error));
                validation = false;
            }
            else
            {
                validation = true;
            }
            if (!validator.CheckEmail(email.Text))
            {
                displayMessage(GetString(Resource.String.Register_Email_Error));
                validation = false;
            }
            else
            {
                validation = true;
            }

            if (name.Text.Length != 0 && password.Text.Length != 0 && email.Text.Length != 0 && username.Text.Length != 0 &&
                surname.Text.Length != 0 && validation)
            {
                signUpComplete.Invoke(this, new OnSignUpEventArgs(name.Text, surname.Text, email.Text, username.Text, password.Text));
                this.Dismiss();
            }
            else
            {
                displayMessage(GetString(Resource.String.Register_Empty_Fields_Error));
            }
        }