示例#1
0
        /// <summary>
        /// Validates the objects fields content
        /// </summary>
        /// <param name="validationType">Validation level to use on this model</param>
        /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
        public override void Validate(Validations validationType = Validations.Weak) 
        {
            base.Validate(validationType);

            if (validationType == Validations.Weak)
            {
                if (string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName))
                {
                    throw new Exceptions.OrderFieldBadFormatException("Both First name and last name are missing or empty - at least one should be specified");
                }
            }
            else
            {
                InputValidators.ValidateValuedString(FirstName, "First Name");
                InputValidators.ValidateValuedString(LastName, "Last Name");
                InputValidators.ValidatePhoneNumber(Phone); // make sure phone exists and has a value (addition to validation of BaseAddress)
            }

            InputValidators.ValidateValuedString(Address1, "Address 1");
            InputValidators.ValidateValuedString(City, "City");

            if(string.IsNullOrEmpty(Country) && string.IsNullOrEmpty(CountryCode))
            {
                throw new Exceptions.OrderFieldBadFormatException("Both Country or Country Code fields are missing - at least one should be speicified");
            }
        }
示例#2
0
 /// <summary>
 /// Creates the mediator class used to send order data to Riskified
 /// </summary>
 /// <param name="env">The Riskified environment to send to</param>
 /// <param name="authToken">The merchant's auth token</param>
 /// <param name="shopDomain">The merchant's shop domain</param>
 /// <param name="validationMode">Validation mode to use</param>
 public OrdersGateway(RiskifiedEnvironment env, string authToken, string shopDomain, Validations validationMode)
 {
     _riskifiedBaseWebhookUrl = EnvironmentsUrls.GetEnvUrl(env);
     _authToken = authToken;
     _shopDomain = shopDomain;
     _validationMode = validationMode;
 }
        private bool RunValidation(string empUName, string empEmail, string empPhone, string empPwd)
        {
            bool result = true;
            Validations validations = new Validations();
            bool usernameCorrect = validations.UsernameValidation(empUName);
            if (!usernameCorrect)
            {
                txtEmpSUUsername.Text = "Invalid Username";
                result = false;
            }

            bool emailCorrect = validations.EmailValidation(empEmail);
            if (!emailCorrect)
            {
                txtEmpSUEmail.Text = "Invalid Email";
                result = false;
            }

            bool phoneCorrect = validations.PhoneValidation(empPhone);
            if (!phoneCorrect)
            {
                txtEmpSUPhone.Text = "Invalid Phone Number";
                result = false;
            }

            bool passwordCorrect = validations.PasswordValidation(empPwd);
            if (!usernameCorrect)
            {
                txtEmpSUPassword.Text = "Invalid Password";
                result = false;
            }
           
            
            return result;
        }
示例#4
0
        void EnableBestPracticeEnforcement(FeatureConfigurationContext context)
        {
            var validations = new Validations(context.Settings.Get<Conventions>());

            context.Pipeline.Register(
                "EnforceSendBestPractices",
                new EnforceSendBestPracticesBehavior(validations),
                "Enforces send messaging best practices");

            context.Pipeline.Register(
                "EnforceReplyBestPractices",
                new EnforceReplyBestPracticesBehavior(validations),
                "Enforces reply messaging best practices");

            context.Pipeline.Register(
                "EnforcePublishBestPractices",
                new EnforcePublishBestPracticesBehavior(validations),
                "Enforces publish messaging best practices");

            context.Pipeline.Register(
                "EnforceSubscribeBestPractices",
                new EnforceSubscribeBestPracticesBehavior(validations),
                "Enforces subscribe messaging best practices");

            context.Pipeline.Register(
                "EnforceUnsubscribeBestPractices",
                new EnforceUnsubscribeBestPracticesBehavior(validations),
                "Enforces unsubscribe messaging best practices");
        }
示例#5
0
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);
            InputValidators.ValidateObjectNotNull(Fulfillments, "Fulfillments");
            Fulfillments.ToList().ForEach(item => item.Validate(validationType));

        }
示例#6
0
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Should use weak validations or strong</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     InputValidators.ValidateValuedString(RefundId, "Refund ID");
     InputValidators.ValidateZeroOrPositiveValue(Amount, "No Charge Amount");
     InputValidators.ValidateCurrency(Currency);
     InputValidators.ValidateValuedString(Reason, "No Charge Reason");
 }
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Should use weak validations or strong</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     if (validationType != Validations.Weak)
     {
         InputValidators.ValidateValuedString(PaymentStatus, "Payment Status");
     }
 }
 public void Validate(Validations validationType = Validations.Weak)
 {
     InputValidators.ValidateValuedString(RefundId, "Refund ID");
     InputValidators.ValidateDateNotDefault(RefundedAt, "Refunded At");
     InputValidators.ValidateZeroOrPositiveValue(Amount, "Refund Amount");
     InputValidators.ValidateCurrency(Currency);
     InputValidators.ValidateValuedString(Reason, "Refund Reason");
 }
示例#9
0
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);

            InputValidators.ValidateObjectNotNull(AuthorizationError, "Authorization Error");
            AuthorizationError.Validate(validationType);


        }
示例#10
0
 public void Validate(Validations validationType = Validations.Weak)
 {
     InputValidators.ValidateObjectNotNull(Customer, "Customer");
     Customer.Validate(validationType);
     if(StartingPrice != null)
     {
         InputValidators.ValidateZeroOrPositiveValue((float)StartingPrice, "Starting price");
     }
 }
		public WinRegularExpressionValidator(string id, Control controlToValidate,Validations validation , string errorMessage,WindowsErrorProvider parent)
		{
			this.id = id;
			this.controlToValidate = controlToValidate;
			this.errorMessage = errorMessage;
			this.validationExpression = "";
			this.validation = validation;
			this.parent = parent;
			AddEvents();
		}
		public WinRegularExpressionValidator(string id, Control controlToValidate,string validationExpression,WindowsErrorProvider parent)
		{
			this.id = id;
			this.controlToValidate = controlToValidate;
			this.validation = Validations.UserDefined;
			this.validationExpression = validationExpression;
			this.errorMessage = "Invalid!.";
			this.parent = parent;
			AddEvents();
		}
示例#13
0
        public void Validate(Validations validationType = Validations.Weak)
        {
            InputValidators.ValidateValuedString(Network, "Network");
            InputValidators.ValidateValuedString(PublicUsername, "Public Username");

            if(!string.IsNullOrEmpty(Email))
            {
                InputValidators.ValidateEmail(Email);
            }
        }
示例#14
0
        protected void btnApply_Click(object sender, EventArgs e)
        {
            string fileName = Path.GetFileName(CvApply.PostedFile.FileName);

            string Jobid = Request.QueryString["id"];
            string Empid = Request.QueryString["empId"];

            int JobidParsed = int.Parse(Jobid);
            int EmpidParsed = int.Parse(Empid);

            fileName = DateTime.Now.ToString() + fileName;

            fileName = fileName.Replace("/", " ").Replace("'\'", "").Replace(" ", "").Replace("-", "").Replace(":", "").Replace(";", "");

            CvApply.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);

            JobApplication UserAppliedForJob = new JobApplication();

            UserAppliedForJob.FullName = txtAppFullname.Text;
            UserAppliedForJob.ContactNumber = txtAppContactNumber.Text;
            Validations validations = new Validations();

            UserAppliedForJob.Email = txtEmail.Text;
            bool isValid = validations.EmailValidation(UserAppliedForJob.Email);
            if (!isValid)
            {
                txtEmail.Text = "Invalid Email";
            }
            UserAppliedForJob.Experience = txtRelvExp.Text;
            UserAppliedForJob.CoverLetter = txtCoverLetter.Text;
            UserAppliedForJob.UploadCvPath = fileName;
            UserAppliedForJob.JobIdApplied = JobidParsed;
            UserAppliedForJob.EmpidApplied = EmpidParsed;
            if (Session["JobseekerID"] != null)
            {
                UserAppliedForJob.JSId = (int)Session["JobseekerID"];
            }
            else
            {
                // all guests have jobseeker id of 1
                int noID = 1;
                UserAppliedForJob.JSId = noID;
            }

            if (isValid)
            {
                BLLRecruiterWebsiteManager ProcessJobApp = new BLLRecruiterWebsiteManager();

                bool check;

                check = ProcessJobApp.InsertJobApplication(UserAppliedForJob);

                Response.Redirect("~/index.aspx");
            }
        }
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="isWeak">Should use weak validations or strong</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     if (validationType != Validations.Weak)
     {
         //InputValidators.ValidateAvsResultCode(AvsResultCode);
         InputValidators.ValidateCvvResultCode(CvvResultCode);
         InputValidators.ValidateCreditCard(CreditCardNumber);
     }
     
     //InputValidators.ValidateValuedString(CreditCardBin, "Credit Card Bin");
     InputValidators.ValidateValuedString(CreditCardCompany, "Credit Card Company");
 }
		public void Add(string id, Control controlToValidate,Validations validation , string errorMessage,WindowsErrorProvider parent)
		{
			if(!list.ContainsKey(id))
			{
				WinRegularExpressionValidator validator = new WinRegularExpressionValidator(id,controlToValidate,validation,errorMessage,this.parent);
				list.Add(id,validator);
			}
			else
			{
				throw new Exception("Item already exists in the collection.");
			}
		}
示例#17
0
        public void Validate(Validations validationType = Validations.Weak)
        {
            InputValidators.ValidateValuedString(FulfillmentId, "Fulfillment Id");
            InputValidators.ValidateDateNotDefault(CreatedAt.Value, "Created At");
            InputValidators.ValidateObjectNotNull(Status, "Status");
            

            if(LineItems != null)
            {
                LineItems.ToList().ForEach(item => item.Validate(validationType));
            }

            
        }
示例#18
0
        /// <summary>
        /// Validates the objects fields content
        /// </summary>
        /// <param name="validationType">Validation level to use on this model</param>
        /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
        public virtual void Validate(Validations validationType = Validations.Weak)
        {
            // optional fields validations
            if(!string.IsNullOrEmpty(Phone))
            {
                InputValidators.ValidatePhoneNumber(Phone);
            }

            if (!string.IsNullOrEmpty(CountryCode))
            {
                InputValidators.ValidateCountryOrProvinceCode(CountryCode);
            }

            if (!string.IsNullOrEmpty(ProvinceCode))
            {
                InputValidators.ValidateCountryOrProvinceCode(ProvinceCode);
            }
        }
示例#19
0
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Validation level to use on this Model</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     // optional fields validations
     if (!string.IsNullOrEmpty(Email))
     {
         InputValidators.ValidateEmail(Email);
     }
     if (!string.IsNullOrEmpty(Phone))
     {
         InputValidators.ValidatePhoneNumber(Phone);
     }
     if (Social != null)
     {
         Social.Validate(validationType);
     }
     if (Social==null && string.IsNullOrEmpty(Email) && string.IsNullOrEmpty(Phone))
     {
         throw new Exceptions.OrderFieldBadFormatException("All recipient fields are missing - at least one should be specified");
     }
 }
示例#20
0
        /// <summary>
        /// Validates the objects fields content
        /// </summary>
        /// <param name="validationType">Validation level to use on this Model</param>
        /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
        public void Validate(Validations validationType = Validations.Weak)
        {
            if (validationType == Validations.Weak)
            {
                if(string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName))
                {
                    throw new Exceptions.OrderFieldBadFormatException("Both First name and last name are missing or empty - at least one should be specified");
                }
            }
            else
            {
                InputValidators.ValidateValuedString(FirstName, "First Name");
                InputValidators.ValidateValuedString(LastName, "Last Name");
            }

            // optional fields validations
            if (!string.IsNullOrEmpty(Email))
            {
                InputValidators.ValidateEmail(Email);
            }
            if (OrdersCount.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(OrdersCount.Value, "Orders Count");
            }
            if (CreatedAt.HasValue)
            {
                InputValidators.ValidateDateNotDefault(CreatedAt.Value, "Created At");
            }
            if(Social != null)
            {
                Social.ToList().ForEach(item => item.Validate(validationType));
            }
            if (Address != null)
            {
                Address.Validate(validationType);
            }
        }
示例#21
0
        /// <summary>
        /// Stage 1, Add cable to continue or welder to destroy frame.
        /// </summary>
        /// <param name="interaction"></param>
        private void InitialStateInteraction(HandApply interaction)
        {
            if (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Cable) &&
                Validations.HasUsedAtLeast(interaction, 5))
            {
                //add 5 cables
                ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                          "You start adding cables to the frame...",
                                                          $"{interaction.Performer.ExpensiveName()} starts adding cables to the frame...",
                                                          "You add cables to the frame.",
                                                          $"{interaction.Performer.ExpensiveName()} adds cables to the frame.",
                                                          () =>
                {
                    Inventory.ServerConsume(interaction.HandSlot, 5);
                    stateful.ServerChangeState(cablesAddedState);

                    //sprite change
                    spriteRender.sprite = boxCable;
                    ServerChangeSprite(SpriteStates.BoxCable);
                });
            }
            else if (Validations.HasUsedActiveWelder(interaction))
            {
                //deconsruct
                ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                          "You start deconstructing the frame...",
                                                          $"{interaction.Performer.ExpensiveName()} starts deconstructing the frame...",
                                                          "You deconstruct the frame.",
                                                          $"{interaction.Performer.ExpensiveName()} deconstructs the frame.",
                                                          () =>
                {
                    Spawn.ServerPrefab(CommonPrefabs.Instance.Metal, SpawnDestination.At(gameObject), 5);
                    Despawn.ServerSingle(gameObject);
                });
            }
        }
示例#22
0
 public bool WillInteract(MouseDrop interaction, NetworkSide side)
 {
     if (side == NetworkSide.Server && IsClosed)
     {
         return(false);
     }
     if (!Validations.CanInteract(interaction.PerformerPlayerScript, side))
     {
         return(false);
     }
     if (!Validations.IsAdjacent(interaction.Performer, interaction.DroppedObject))
     {
         return(false);
     }
     if (!Validations.IsAdjacent(interaction.Performer, gameObject))
     {
         return(false);
     }
     if (interaction.Performer == interaction.DroppedObject)
     {
         return(false);
     }
     return(true);
 }
示例#23
0
        public bool WillInteract(HandApply interaction, NetworkSide side)
        {
            if (DefaultWillInteract.HandApply(interaction, side) == false)
            {
                return(false);
            }

            if (Validations.HasItemTrait(interaction.HandObject, CommonTraits.Instance.Wrench))
            {
                return(true);
            }

            if (Validations.HasItemTrait(interaction.HandObject, CommonTraits.Instance.Welder))
            {
                return(true);
            }

            if (interaction.HandObject == null)
            {
                return(true);
            }

            return(false);
        }
示例#24
0
        public UpdateExampleResponse Process(UpdateExampleRequest request)
        {
            try
            {
                var example = _repository.Get(request.Id);

                example.UpdateProperty1(request.Property1);
                if (example.IsValid())
                {
                    _repository.Save(example);
                    return(new UpdateExampleResponse(true));
                }
                else
                {
                    return(new UpdateExampleResponse(false, example.Errors));
                }
            }
            catch (Exception ex)
            {
                var validations = new Validations();
                validations.AddError(ErrorCode.Unexpected, "Unable to update example model.");
                return(new UpdateExampleResponse(false, validations));
            }
        }
        public bool WillInteract(HandApply interaction, NetworkSide side)
        {
            if (DefaultWillInteract.Default(interaction, side) == false)
            {
                return(false);
            }

            if (Validations.HasItemTrait(interaction.HandObject, CommonTraits.Instance.Cable))
            {
                return(true);
            }

            if (Validations.HasItemTrait(interaction.HandObject, CommonTraits.Instance.Screwdriver))
            {
                return(true);
            }

            if (Validations.HasItemTrait(interaction.HandObject, CommonTraits.Instance.Wirecutter))
            {
                return(true);
            }

            return(false);
        }
    /// <summary>
    /// Returns the slot in storage which is the best fit for the item.
    /// The BestSlots list will be scanned through in order. Returns the
    /// first slot in the BestSlots list for which toCheck has the
    /// indicated trait (ignored if trait is left blank) and can be put into the slot. If none of the BestSlots
    /// will fit this item, returns the first slot in storage which can hold the item.
    /// Returns null if the item cannot fit in any slots in storage.
    /// </summary>
    /// <param name="toCheck"></param>
    /// <param name="storage"></param>
    /// <param name="mustHaveUISlot">if true (default), will only return slots
    /// which are linked to a UI slot</param>
    /// <returns></returns>
    public ItemSlot GetBestSlot(Pickupable toCheck, ItemStorage storage, bool mustHaveUISlot = true)
    {
        if (toCheck == null || storage == null)
        {
            Logger.LogTrace("Cannot get best slot, toCheck or storage was null", Category.Inventory);
            return(null);
        }

        var side      = CustomNetworkManager.IsServer ? NetworkSide.Server : NetworkSide.Client;
        var itemAttrs = toCheck.GetComponent <ItemAttributes>();

        if (itemAttrs == null)
        {
            Logger.LogTraceFormat("Item {0} has no ItemAttributes, thus it will be put in the" +
                                  " first available slot.", Category.Inventory, toCheck);
        }
        else
        {
            //find the best slot
            var best = BestSlots.FirstOrDefault(tsm =>
                                                (!mustHaveUISlot || storage.GetNamedItemSlot(tsm.Slot)?.LocalUISlot != null) &&
                                                Validations.CanFit(storage.GetNamedItemSlot(tsm.Slot), toCheck, side) &&
                                                (tsm.Trait == null || itemAttrs.HasTrait(tsm.Trait)));
            if (best != null)
            {
                return(storage.GetNamedItemSlot(best.Slot));
            }
        }

        Logger.LogTraceFormat("Item {0} did not fit in any BestSlots, thus will" +
                              " be placed in first available slot.", Category.Inventory, toCheck);

        return(storage.GetItemSlots().FirstOrDefault(slot =>
                                                     (!mustHaveUISlot || slot.LocalUISlot != null) &&
                                                     Validations.CanFit(slot, toCheck, side)));
    }
示例#27
0
    public RightClickableResult GenerateRightClickOptions()
    {
        if (!canPickup)
        {
            return(null);
        }
        var interaction = HandApply.ByLocalPlayer(gameObject);

        if (interaction.TargetObject != gameObject)
        {
            return(null);
        }
        if (interaction.HandObject != null)
        {
            return(null);
        }
        if (!Validations.CanApply(interaction.PerformerPlayerScript, interaction.TargetObject, NetworkSide.Client, true, ReachRange.Standard, isPlayerClick: false))
        {
            return(null);
        }

        return(RightClickableResult.Create()
               .AddElement("PickUp", RightClickInteract));
    }
示例#28
0
        /// Method Name     : UpdateCustomerVerificationData
        /// Author          : Pratik Soni
        /// Creation Date   : 23 Jan 2018
        /// Purpose         : To update the verification code and codevalidtill date in CRM
        /// Revision        :
        /// </summary>
        /// <returns> </returns>
        private ServiceResponse <Customer> UpdateCustomerVerificationData(string customerID)
        {
            ServiceResponse <Customer> updateResponse;

            DTO.CustomerVerification dtoCustomerVerification;
            DTO.Customer             dtoCustomer;
            int verificationCode = codeGenerator.GetVerificationCode(6);

            dtoCustomerVerification = GetUpdateVerificationRequestBody(verificationCode);
            updateResponse          = crmCustomerDetails.PutCustomerVerificationData(customerID, General.ConvertToJson <DTO.CustomerVerification>(dtoCustomerVerification));
            if (updateResponse.Message != null)
            {
                return(updateResponse);
            }

            if (Validations.IsValid(updateResponse.Information) && updateResponse.Information == resourceManager.GetString("CRM_STATUS_204"))
            {
                dtoCustomer = General.ConvertFromJson <Customer>(General.ConvertToJson <DTO.CustomerVerification>(dtoCustomerVerification));
                return(new ServiceResponse <Customer> {
                    Data = dtoCustomer
                });
            }
            return(updateResponse);
        }
示例#29
0
 /// <summary>
 /// Gets the entity with the specified ID.
 /// </summary>
 /// <param name="entityId">The ID of the entity.</param>
 /// <returns>
 /// The entity.
 /// </returns>
 public IEntity Retrieve(Guid entityId)
 {
     // Root-level node?
     if (EntityHelper.IsRoot(entityId))
     {
         return(new EntityRoot()
         {
             Id = entityId,
             Path = new[] { entityId },
             Name = EntityHelper.GetNameForRoot(entityId),
             Icon = EntityHelper.GetIconForRoot(entityId)
         });
     }
     else
     {
         // Specific entities (e.g., forms or layouts).
         return(Folders.Retrieve(entityId) as IEntity
                ?? Forms.Retrieve(entityId) as IEntity
                ?? ConfiguredForms.Retrieve(entityId) as IEntity
                ?? Layouts.Retrieve(entityId) as IEntity
                ?? Validations.Retrieve(entityId) as IEntity
                ?? DataValues.Retrieve(entityId) as IEntity);
     }
 }
示例#30
0
        //GridFund_ItemCommand event is use for two command name edit and delete
        protected void GridFund_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            string EnvelopedNumber, DID;

            //if  command name is EditDonation donation it will get the id of particuar
            //row to edit the donation and redirecte it to newdonation screen to update that donation
            if (e.CommandName == "EditDonation")
            {
                if (e.Item is GridDataItem)
                {
                    GridDataItem item = (GridDataItem)e.Item;
                    EnvelopedNumber = (item["Envelopenumber"].Text.ToString());
                    DID             = item["DID"].Text.ToString().Trim();

                    Response.Redirect("~/UserScreens/NewDonation.aspx?DID=" + DID);
                }
            }
            //If command name is delete it will get the id that donation which needs to be deleted by calling DELETEDonation
            //it will successfully get deleted
            else if (e.CommandName == "Delete")
            {
                GridDataItem item = (GridDataItem)e.Item;
                objd.Envelopenumber = (item["Envelopenumber"].Text.ToString());
                objd.FundName       = (item["FundName"].Text.ToString());
                no_of_rows_affected = objd.DELETEDonation();
                if (no_of_rows_affected == 1)
                {
                    Validations.showMessage(lblErrorMsg, "Donation " + Validations.RecordDeleted, "");
                    BindGrid();
                }
                else
                {
                    Validations.showMessage(lblErrorMsg, "Donation " + Validations.Err_RefDelete, "Error");
                }
            }
        }
示例#31
0
    public bool WillInteract(HandApply interaction, NetworkSide side)
    {
        if (!canPickup)
        {
            return(false);
        }
        //we need to be the target
        if (interaction.TargetObject != gameObject)
        {
            return(false);
        }
        //hand needs to be empty for pickup
        if (interaction.HandObject != null)
        {
            return(false);
        }
        //instead of the base logic, we need to use extended range check for CanApply
        if (!Validations.CanApply(interaction, side, true, ReachRange.Standard, isPlayerClick: true))
        {
            return(false);
        }

        return(true);
    }
示例#32
0
        /// <summary>
        /// the user gets to enter the property values of a movie, and than gets and Movie object returned
        /// </summary>
        /// <returns>a Movie object</returns>
        public static Movie Movie()
        {
            Console.Write("Name of the Item: ");
            string name = Console.ReadLine();

            Console.Write("Relese year of the Item: ");
            string input      = Console.ReadLine();
            int    releseYear = Validations.ParseInt(input);

            releseYear = Validations.TryAgain(releseYear);

            Console.Write("Genre of the Item: ");
            string genre = Console.ReadLine();

            Console.Write("Number of copies of the Item: ");
            input = Console.ReadLine();
            int numberOfCopies = Validations.ParseInt(input);

            numberOfCopies = Validations.TryAgain(numberOfCopies);

            Console.Write("Duration (minutes) of the Movie: ");
            input = Console.ReadLine();
            int duration = Validations.ParseInt(input);

            duration = Validations.TryAgain(duration);

            Console.Write("Age limit of the Movie: ");
            input = Console.ReadLine();
            int ageLimit = Validations.ParseInt(input);

            ageLimit = Validations.TryAgain(ageLimit);

            Movie movie = Factory.CreateMovie(name, releseYear, genre, numberOfCopies, duration, ageLimit);

            return(movie);
        }
示例#33
0
        public void ProcessCustomInteraction(GameObject Player,
                                             RequestHackingInteraction.InteractionWith InteractionType,
                                             uint Referenceobject, int PanelInputID, int PanelOutputID)
        {
            PlayerScript PlayerScript = Player.GetComponent <PlayerScript>();

            if (Validations.CanInteract(PlayerScript, NetworkSide.Server) == false)
            {
                return;
            }
            switch (InteractionType)
            {
            case RequestHackingInteraction.InteractionWith.CutWire:

                if (Validations.HasItemTrait(PlayerScript.DynamicItemStorage.GetActiveHandSlot().ItemObject,
                                             CommonTraits.Instance.Wirecutter) == false)
                {
                    return;
                }


                Cable Cable = null;
                foreach (var cable in Cables)
                {
                    if (cable?.cableCoilID == Referenceobject)
                    {
                        Cable = cable;
                        break;
                    }
                }

                if (Cable == null)
                {
                    Logger.LogWarning("No cable was found for cutting", Category.Interaction);
                    return;
                }

                Connections[Cable.PanelOutput].Remove(Cable);
                Cables.Remove(Cable);
                var Spawned = Spawn.ServerPrefab(OnePeaceCoil.gameObject).GameObject;


                var Hand = PlayerScript.DynamicItemStorage.GetBestHand(Spawned.GetComponent <Stackable>());
                if (Hand == null)
                {
                    Spawned.GetComponent <CustomNetTransform>().AppearAtPositionServer(PlayerScript.WorldPos - this.GetComponent <RegisterTile>().WorldPositionServer);
                }
                else
                {
                    Inventory.ServerAdd(Spawned, Hand);
                }


                OnChangeServer.Invoke();
                break;

            case RequestHackingInteraction.InteractionWith.Cable:
                //Please cable do not Spare thing

                if (Validations.HasItemTrait(PlayerScript.DynamicItemStorage.GetActiveHandSlot().ItemObject,
                                             CommonTraits.Instance.Cable) == false)
                {
                    return;
                }

                LocalPortData LocalPortOutput = null;
                foreach (var kPortData in DictionaryCurrentPorts)
                {
                    if (kPortData.Value.LocalID == PanelOutputID)
                    {
                        LocalPortOutput = kPortData.Value;
                    }
                }


                LocalPortData LocalPortInput = null;

                foreach (var kPortData in DictionaryCurrentPorts)
                {
                    if (kPortData.Value.LocalID == PanelInputID)
                    {
                        LocalPortInput = kPortData.Value;
                    }
                }


                foreach (var cable in Cables)
                {
                    if (LocalPortInput.LocalAction == cable.PanelInput &&
                        LocalPortOutput.LocalAction == cable.PanelOutput)
                    {
                        return;                                 //Cable Already at position
                    }
                }



                var stackable = PlayerScript.DynamicItemStorage.GetActiveHandSlot().Item.GetComponent <Stackable>();

                stackable.ServerConsume(1);

                var insertCable = new Cable();
                CableID++;
                insertCable.cableCoilID = CableID;
                Cables.Add(insertCable);

                insertCable.PanelInput  = LocalPortInput.LocalAction;
                insertCable.PanelOutput = LocalPortOutput.LocalAction;

                if (Connections.ContainsKey(insertCable.PanelOutput) == false)
                {
                    Connections[insertCable.PanelOutput] = new List <Cable>();
                }

                Connections[insertCable.PanelOutput].Add(insertCable);

                OnChangeServer.Invoke();
                break;
            }
        }
示例#34
0
    /// <summary>
    /// Server:
    /// Allow items to be stored by clicking on bags with item in hand
    /// and clicking items with bag in hand if CanClickPickup is enabled
    /// </summary>
    public void ServerPerformInteraction(PositionalHandApply interaction)
    {
        if (allowedToInteract == false)
        {
            return;
        }
        // See which item needs to be stored
        if (Validations.IsTarget(gameObject, interaction))
        {
            // Add hand item to this storage
            Inventory.ServerTransfer(interaction.HandSlot, itemStorage.GetBestSlotFor(interaction.HandObject));
        }
        // See if this item can click pickup
        else if (canClickPickup)
        {
            bool       pickedUpSomething = false;
            Pickupable pickup;
            switch (pickupMode)
            {
            case PickupMode.Single:

                // Don't pick up items which aren't set as CanPickup
                pickup = interaction.TargetObject.GetComponent <Pickupable>();
                if (pickup == null || pickup.CanPickup == false)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer, "There's nothing to pickup!");
                    return;
                }

                // Store the clicked item
                var slot = itemStorage.GetBestSlotFor(interaction.TargetObject);
                if (slot == null)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer,
                                                 $"The {interaction.TargetObject.ExpensiveName()} doesn't fit!");
                    return;
                }

                Inventory.ServerAdd(interaction.TargetObject, slot);
                break;

            case PickupMode.Same:
                if (interaction.TargetObject == null ||
                    interaction.TargetObject.Item() == null)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer, "There's nothing to pickup!");
                    return;
                }

                // Get all items of the same type on the tile and try to store them
                var itemsOnTileSame =
                    MatrixManager.GetAt <ItemAttributesV2>(interaction.WorldPositionTarget.To2Int().To3Int(), true);

                if (itemsOnTileSame.Count == 0)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer, "There's nothing to pickup!");
                    return;
                }

                foreach (var item in itemsOnTileSame)
                {
                    // Don't pick up items which aren't set as CanPickup
                    pickup = item.gameObject.GetComponent <Pickupable>();
                    if (pickup == null || pickup.CanPickup == false)
                    {
                        continue;
                    }

                    // Only try to add it if it matches the target object's traits
                    if (item.HasAllTraits(interaction.TargetObject.Item().GetTraits()))
                    {
                        // Try to add each item to the storage
                        // Can't break this loop when it fails because some items might not fit and
                        // there might be stacks with space still
                        if (Inventory.ServerAdd(item.gameObject, itemStorage.GetBestSlotFor(item.gameObject)))
                        {
                            pickedUpSomething = true;
                        }
                    }
                }

                Chat.AddExamineMsgFromServer(interaction.Performer,
                                             $"You put everything you could in the {gameObject.ExpensiveName()}.");
                break;

            case PickupMode.All:
                // Get all items on the tile and try to store them
                var itemsOnTileAll =
                    MatrixManager.GetAt <ItemAttributesV2>(interaction.WorldPositionTarget.To2Int().To3Int(), true);

                if (itemsOnTileAll.Count == 0)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer, "There's nothing to pickup!");
                    return;
                }

                foreach (var item in itemsOnTileAll)
                {
                    // Don't pick up items which aren't set as CanPickup
                    pickup = item.gameObject.GetComponent <Pickupable>();
                    if (pickup == null || pickup.CanPickup == false)
                    {
                        continue;
                    }

                    // Try to add each item to the storage
                    // Can't break this loop when it fails because some items might not fit and
                    // there might be stacks with space still
                    if (Inventory.ServerAdd(item.gameObject, itemStorage.GetBestSlotFor(item.gameObject)))
                    {
                        pickedUpSomething = true;
                    }
                }

                if (pickedUpSomething)
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer,
                                                 $"You put everything you could in the {gameObject.ExpensiveName()}.");
                }
                else
                {
                    Chat.AddExamineMsgFromServer(interaction.Performer, "There's nothing to pickup!");
                }

                break;

            case PickupMode.DropClick:
                if (canQuickEmpty)
                {
                    // Drop all items that are inside this storage
                    var slots = itemStorage.GetItemSlots();
                    if (slots == null)
                    {
                        Chat.AddExamineMsgFromServer(interaction.Performer, "It's already empty!");


                        return;
                    }
                    if (PlayerManager.PlayerScript == null)
                    {
                        return;
                    }
                    if (Validations.IsInReachDistanceByPositions(PlayerManager.PlayerScript.registerTile.WorldPosition, interaction.WorldPositionTarget) == false)
                    {
                        return;
                    }
                    if (MatrixManager.IsPassableAtAllMatricesOneTile(interaction.WorldPositionTarget.RoundToInt(), CustomNetworkManager.Instance._isServer) == false)
                    {
                        return;
                    }

                    PlayerManager.PlayerScript.playerNetworkActions.CmdDropAllItems(itemStorage.GetIndexedItemSlot(0)
                                                                                    .ItemStorageNetID, interaction.WorldPositionTarget);


                    Chat.AddExamineMsgFromServer(interaction.Performer, $"You start dumping out the {gameObject.ExpensiveName()}.");
                }

                break;
            }
        }
    }
示例#35
0
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);

            if (CountryCode != null) InputValidators.ValidateCountryOrProvinceCode(CountryCode);
        }
示例#36
0
 /// <summary>
 /// Allow honking when barely conscious
 /// </summary>
 public bool WillInteract(HandActivate interaction, NetworkSide side)
 {
     return(Validations.CanInteract(interaction.Performer, side, true) &&
            allowUse);
 }
示例#37
0
 /// <summary>
 ///     Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Should use weak validations or strong</param>
 /// <exception cref="Exceptions.OrderFieldBadFormatException">
 ///     throws an exception if one of the parameters doesn't match the expected
 ///     format
 /// </exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     InputValidators.ValidateZeroOrPositiveValue(Price.GetValueOrDefault(), "Price");
     InputValidators.ValidateValuedString(Title, "Title");
 }
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);

            // All properties are optional, so we only validated when they're filled.

            if (LineItems != null)
            {
                LineItems.ToList().ForEach(item => item.Validate(validationType));
            }


            if (ShippingAddress != null)
            {
                ShippingLines.ToList().ForEach(item => item.Validate(validationType));
            }

            if (PaymentDetails != null && PaymentDetails.Length > 0)
            {
                PaymentDetails.ToList().ForEach(item => item.Validate(validationType));
            }

            if (NoChargeAmount != null)
            {
                NoChargeAmount.Validate(validationType);
            }

            if (validationType == Validations.Weak)
            {
                if (BillingAddress != null)
                {
                    BillingAddress.Validate(validationType);
                }
                else if (ShippingAddress != null)
                {
                    ShippingAddress.Validate(validationType);
                }
            }
            else
            {
                if (BillingAddress != null)
                {
                    BillingAddress.Validate(validationType);
                }
                if (ShippingAddress != null)
                {
                    ShippingAddress.Validate(validationType);
                }
            }

            if (Customer != null)
            {
                Customer.Validate(validationType);
            }
            if (!string.IsNullOrEmpty(Email))
            {
                InputValidators.ValidateEmail(Email);
            }
            if (!string.IsNullOrEmpty(CustomerBrowserIp))
            {
                InputValidators.ValidateIp(CustomerBrowserIp);
            }
            if (!string.IsNullOrEmpty(Currency))
            {
                InputValidators.ValidateCurrency(Currency);
            }
            if (TotalPrice.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalPrice.Value, "Total Price");
            }

            if (CreatedAt != null)
            {
                InputValidators.ValidateDateNotDefault(CreatedAt.Value, "Created At");
            }
            if (UpdatedAt != null)
            {
                InputValidators.ValidateDateNotDefault(UpdatedAt.Value, "Updated At");
            }

            if (DiscountCodes != null && DiscountCodes.Length > 0)
            {
                DiscountCodes.ToList().ForEach(item => item.Validate(validationType));
            }
            if (TotalPriceUsd.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalPriceUsd.Value, "Total Price USD");
            }
            if (TotalDiscounts.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalDiscounts.Value, "Total Discounts");
            }
            if (ClosedAt.HasValue)
            {
                InputValidators.ValidateDateNotDefault(ClosedAt.Value, "Closed At");
            }

            if (Decision != null)
            {
                Decision.Validate(validationType);
            }
        }
示例#39
0
 /// The smart way:
 ///  <inheritdoc cref="IsInReach(Vector3,float)"/>
 public bool IsInReach(RegisterTile otherObject, bool isServer, float interactDist = interactionDistance)
 {
     return(Validations.IsInReach(registerTile, otherObject, isServer, interactDist));
 }
示例#40
0
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);

            // All properties are optional, so we only validated when they're filled.
            
            if(LineItems != null)
            {
                LineItems.ToList().ForEach(item => item.Validate(validationType));
            }

            
            if(ShippingAddress != null)
            {
                ShippingLines.ToList().ForEach(item => item.Validate(validationType));
            }
            
            if (PaymentDetails != null)
            {
                PaymentDetails.Validate(validationType);
            }

            if(NoChargeAmount != null)
            {
                NoChargeAmount.Validate(validationType);
            }

            if (validationType == Validations.Weak)
            {
                if (BillingAddress != null)
                {
                    BillingAddress.Validate(validationType);
                }
                else if(ShippingAddress != null)
                {
                    ShippingAddress.Validate(validationType);
                }
            }
            else
            {
                if(BillingAddress != null)
                {
                    BillingAddress.Validate(validationType);
                }
                if(ShippingAddress != null)
                {
                    ShippingAddress.Validate(validationType);
                }
            }

            if(Customer != null)
            {
                Customer.Validate(validationType);
            }
            if(!string.IsNullOrEmpty(Email))
            {
                InputValidators.ValidateEmail(Email);
            }
            if (!string.IsNullOrEmpty(CustomerBrowserIp))
            {
                InputValidators.ValidateIp(CustomerBrowserIp);
            }
            if (!string.IsNullOrEmpty(Currency))
            {
                InputValidators.ValidateCurrency(Currency);
            }
            if (TotalPrice.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalPrice.Value, "Total Price");
            }
           
            if(CreatedAt != null)
            {
                InputValidators.ValidateDateNotDefault(CreatedAt.Value, "Created At");
            }
            if (UpdatedAt != null)
            {
                InputValidators.ValidateDateNotDefault(UpdatedAt.Value, "Updated At");
            }

            if (DiscountCodes != null && DiscountCodes.Length > 0)
            {
                DiscountCodes.ToList().ForEach(item => item.Validate(validationType));
            }
            if (TotalPriceUsd.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalPriceUsd.Value, "Total Price USD");
            }
            if (TotalDiscounts.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalDiscounts.Value, "Total Discounts");
            }
            if (ClosedAt.HasValue)
            {
                InputValidators.ValidateDateNotDefault(ClosedAt.Value, "Closed At");
            }

            if (Decision != null)
            {
                Decision.Validate(validationType);
            }

        }
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Should use weak validations or strong</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public void Validate(Validations validationType = Validations.Weak)
 {
     InputValidators.ValidateValuedString(Gateway, "Gateway");
     InputValidators.ValidateZeroOrPositiveValue(Amount, "Amount");
 }
示例#42
0
        /// <summary>
        /// Validates the objects fields content
        /// </summary>
        /// <param name="isWeak">Should use weak validations or strong</param>
        /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
        public override void Validate(Validations validationType = Validations.Weak)
        {
            base.Validate(validationType);
            InputValidators.ValidateObjectNotNull(LineItems, "Line Items");
            LineItems.ToList().ForEach(item => item.Validate(validationType));
            InputValidators.ValidateObjectNotNull(ShippingLines, "Shipping Lines");
            ShippingLines.ToList().ForEach(item => item.Validate(validationType));
            if(PaymentDetails == null && NoChargeAmount == null)
            {
                throw new Exceptions.OrderFieldBadFormatException("Both PaymentDetails and NoChargeDetails are missing - at least one should be specified");
            }
            if(PaymentDetails != null)
            {
                PaymentDetails.Validate(validationType);
            }
            else 
            {
                NoChargeAmount.Validate(validationType);
            }

            if (validationType == Validations.Weak)
            {
                if (BillingAddress == null && ShippingAddress == null)
                {
                    throw new Exceptions.OrderFieldBadFormatException("Both shipping and billing addresses are missing - at least one should be specified");
                }

                if (BillingAddress != null)
                {
                    BillingAddress.Validate(validationType);
                }
                else
                {
                    ShippingAddress.Validate(validationType);
                }
            }
            else
            {
                InputValidators.ValidateObjectNotNull(BillingAddress, "Billing Address");
                BillingAddress.Validate(validationType);
                InputValidators.ValidateObjectNotNull(ShippingAddress, "Shipping Address");
                ShippingAddress.Validate(validationType);
            }

            InputValidators.ValidateObjectNotNull(Customer, "Customer");
            Customer.Validate(validationType);
            InputValidators.ValidateEmail(Email);
            InputValidators.ValidateIp(CustomerBrowserIp);
            InputValidators.ValidateCurrency(Currency);
            InputValidators.ValidateZeroOrPositiveValue(TotalPrice.Value, "Total Price");
            InputValidators.ValidateValuedString(Gateway, "Gateway");
            InputValidators.ValidateDateNotDefault(CreatedAt.Value, "Created At");
            InputValidators.ValidateDateNotDefault(UpdatedAt.Value, "Updated At");
            
            // optional fields validations
            if(DiscountCodes != null && DiscountCodes.Length > 0)
            {
                DiscountCodes.ToList().ForEach(item => item.Validate(validationType));
            }
            if(TotalPriceUsd.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalPriceUsd.Value, "Total Price USD");
            }
            if (TotalDiscounts.HasValue)
            {
                InputValidators.ValidateZeroOrPositiveValue(TotalDiscounts.Value, "Total Discounts");
            }
            if (ClosedAt.HasValue)
            {
                InputValidators.ValidateDateNotDefault(ClosedAt.Value, "Closed At");
            }
        }
示例#43
0
 public virtual void Validate(Validations validationType = Validations.Weak)
 {
     
     InputValidators.ValidateValuedString(Id, "Merchant Order ID");
 }
示例#44
0
 /// <summary>
 /// Validates the objects fields content
 /// </summary>
 /// <param name="validationType">Validation level of the model</param>
 /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
 public override void Validate(Validations validationType = Validations.Weak)
 {
     base.Validate(validationType);
     InputValidators.ValidateObjectNotNull(this.Decision, "Decision");
     this.Decision.Validate(validationType);
 }
示例#45
0
 public override void Validate(Validations validationType = Validations.Weak)
 {
     base.Validate(validationType);
     InputValidators.ValidateObjectNotNull(Refunds, "Refunds");
     Refunds.ToList().ForEach(item => item.Validate(validationType));
 }
示例#46
0
        /// <summary>
        /// Validates the objects fields content
        /// </summary>
        /// <param name="validationType">Validation level to use on this model</param>
        /// <exception cref="OrderFieldBadFormatException">throws an exception if one of the parameters doesn't match the expected format</exception>
        public virtual void Validate(Validations validationType = Validations.Weak)
        {
            InputValidators.ValidateValuedString(Title, "Title");
            InputValidators.ValidateZeroOrPositiveValue(Price.Value, "Price");
            InputValidators.ValidatePositiveValue(QuantityPurchased.Value, "Quantity Purchased");

            // optional fields validations
            if (ProductId != null)
            {
                InputValidators.ValidateValuedString(ProductId, "Product Id");
            }

            if (Seller != null)
            {
                Seller.Validate(validationType);
            }
        }
示例#47
0
 /// <summary>
 /// Checks if the drag can be performed by this dragger
 /// </summary>
 /// <param name="dragger">player attempting the drag</param>
 /// <returns></returns>
 public bool CanBeginDrag(GameObject dragger)
 {
     return(Validations.CanApply(dragger, gameObject, NetworkSide.Client, allowDragWhileSoftCrit,
                                 draggerMustBeAdjacent ? ReachRange.Standard : ReachRange.Unlimited));
 }
示例#48
0
    private static bool ServerPerformTransfer(InventoryMove toPerform, Pickupable pickupable)
    {
        //transfer from one slot to another
        var toSlot   = toPerform.ToSlot;
        var fromSlot = toPerform.FromSlot;

        if (toSlot == null)
        {
            Logger.LogTraceFormat("Attempted to transfer {0} to another slot but target slot was null." +
                                  " Move will not be performed.", Category.Inventory, pickupable.name);
            return(false);
        }

        if (toSlot.Item != null)
        {
            // Check if the items can be stacked
            var stackableTarget = toSlot.Item.GetComponent <Stackable>();
            if (stackableTarget != null && stackableTarget.CanAccommodate(pickupable.gameObject))
            {
                toSlot.Item.GetComponent <Stackable>().ServerCombine(pickupable.GetComponent <Stackable>());
                return(true);
            }

            switch (toPerform.ReplacementStrategy)
            {
            case ReplacementStrategy.DespawnOther:
                Logger.LogTraceFormat("Attempted to transfer from slot {0} to slot {1} which already had something in it." +
                                      " Item in slot will be despawned first.", Category.Inventory, fromSlot, toSlot);
                ServerDespawn(toSlot);
                break;

            case ReplacementStrategy.DropOther:
                Logger.LogTraceFormat("Attempted to transfer from slot {0} to slot {1} which already had something in it." +
                                      " Item in slot will be dropped first.", Category.Inventory, fromSlot, toSlot);
                ServerDrop(toSlot);
                break;

            case ReplacementStrategy.Cancel:
            default:
                Logger.LogTraceFormat("Attempted to transfer from slot {0} to slot {1} which already had something in it." +
                                      " Transfer will not be performed.", Category.Inventory, fromSlot, toSlot);
                return(false);
            }
        }

        if (pickupable.ItemSlot == null)
        {
            Logger.LogTraceFormat("Attempted to transfer {0} to target slot but item is not in a slot." +
                                  " transfer will not be performed.", Category.Inventory, pickupable.name);
            return(false);
        }


        if (fromSlot == null)
        {
            Logger.LogTraceFormat("Attempted to transfer {0} to target slot but from slot was null." +
                                  " transfer will not be performed.", Category.Inventory, pickupable.name);
            return(false);
        }

        if (!Validations.CanFit(toSlot, pickupable, NetworkSide.Server, true) && toPerform.IgnoreConstraints == false)
        {
            Logger.LogTraceFormat("Attempted to transfer {0} to slot {1} but slot cannot fit this item." +
                                  " transfer will not be performed.", Category.Inventory, pickupable.name, toSlot);
            return(false);
        }

        pickupable._SetItemSlot(null);
        fromSlot._ServerRemoveItem();

        pickupable._SetItemSlot(toSlot);
        toSlot._ServerSetItem(pickupable);

        foreach (var onMove in pickupable.GetComponents <IServerInventoryMove>())
        {
            onMove.OnInventoryMoveServer(toPerform);
        }

        return(true);
    }
示例#49
0
 public override void Validate(Validations validationType = Validations.Weak)
 {
     base.Validate(validationType);
 }
示例#50
0
    private static bool ServerPerformAdd(InventoryMove toPerform, Pickupable pickupable)
    {
        // item is not currently in inventory, it should be moved into inventory system into
        // the indicated slot.

        if (pickupable.ItemSlot != null)
        {
            Logger.LogTraceFormat("Attempted to add {0} to inventory but item is already in slot {1}." +
                                  " Move will not be performed.", Category.Inventory, pickupable.name, pickupable.ItemSlot);
            return(false);
        }

        var toSlot = toPerform.ToSlot;

        if (toSlot == null)
        {
            Logger.LogTraceFormat("Attempted to add {0} to inventory but target slot was null." +
                                  " Move will not be performed.", Category.Inventory, pickupable.name);
            return(false);
        }

        if (toSlot.Item != null)
        {
            var stackableTarget = toSlot.Item.GetComponent <Stackable>();
            if (stackableTarget != null && stackableTarget.CanAccommodate(pickupable.gameObject))
            {
                toSlot.Item.GetComponent <Stackable>().ServerCombine(pickupable.GetComponent <Stackable>());
                return(true);
            }
            else
            {
                switch (toPerform.ReplacementStrategy)
                {
                case ReplacementStrategy.DespawnOther:
                    Logger.LogTraceFormat("Attempted to add {0} to inventory but target slot {1} already had something in it." +
                                          " Item in slot will be despawned first.", Category.Inventory, pickupable.name, toSlot);
                    ServerDespawn(toSlot);
                    break;

                case ReplacementStrategy.DropOther:
                    Logger.LogTraceFormat("Attempted to add {0} to inventory but target slot {1} already had something in it." +
                                          " Item in slot will be dropped first.", Category.Inventory, pickupable.name, toSlot);
                    ServerDrop(toSlot);
                    break;

                case ReplacementStrategy.Cancel:
                default:
                    Logger.LogTraceFormat("Attempted to add {0} to inventory but target slot {1} already had something in it." +
                                          " Move will not be performed.", Category.Inventory, pickupable.name, toSlot);
                    return(false);
                }
            }
        }

        if (!Validations.CanFit(toSlot, pickupable, NetworkSide.Server, true) && toPerform.IgnoreConstraints == false)
        {
            Logger.LogTraceFormat("Attempted to add {0} to slot {1} but slot cannot fit this item." +
                                  " transfer will not be performed.", Category.Inventory, pickupable.name, toSlot);
            return(false);
        }

        // go poof, it's in inventory now.
        pickupable.GetComponent <CustomNetTransform>().DisappearFromWorldServer(true);

        // no longer inside any PushPull
        pickupable.GetComponent <ObjectBehaviour>().parentContainer = null;
        pickupable.GetComponent <RegisterTile>().UpdatePositionServer();

        // update pickupable's item and slot's item
        pickupable._SetItemSlot(toSlot);
        toSlot._ServerSetItem(pickupable);

        foreach (var onMove in pickupable.GetComponents <IServerInventoryMove>())
        {
            onMove.OnInventoryMoveServer(toPerform);
        }

        return(true);
    }
示例#51
0
        private async void Transaction(string transtype)
        {
            var validate = new Validations();

            if (validate.ValidateDouble(txtAmount.Text) == false)
            {
                txtAmount.Focus();
                errorProvider1.SetError(txtAmount, "Invalid Amount");
                MessageBox.Show("Invalid Amount");
            }

            else
            {
                var tempTrans = new Transaction();
                var status    = false;
                tempTrans.Amount     = Convert.ToDecimal(txtAmount.Text);
                tempTrans.CustomerNo = lblCustomerNo.Text;
                tempTrans.TransType  = transactiontype;
                tempTrans.SenderName = txtFirstname.Text + " " + txtLastname.Text;
                tempTrans.TransDate  = Convert.ToDateTime(lblDate.Text);


                if (transtype != "transfer")
                {
                    tempTrans.ReceipientAccNo = customerDetail.AccountNumber;
                    if (transtype == "deposit")
                    {
                        lblBalance.Text = (Convert.ToDecimal(lblBalance.Text) + Convert.ToDecimal(txtAmount.Text)).ToString();
                    }
                    else
                    {
                        lblBalance.Text = (Convert.ToDecimal(lblBalance.Text) - Convert.ToDecimal(txtAmount.Text)).ToString();
                    }
                    customerDetail.Balance = Convert.ToDecimal(lblBalance.Text);
                }
                else
                {
                    tempTrans.ReceipientAccNo = txtAccountnumber.Text;
                    var Receiver    = new Customer();
                    var repo        = new CustomerController();
                    var NewCustomer = repo.GetCustomerDetails();


                    NewCustomer.ForEach(item =>
                    {
                        if (tempTrans.ReceipientAccNo == item.AccountNumber)
                        {
                            Receiver = item;
                            status   = true;
                        }
                    });

                    if (status == false)
                    {
                        MessageBox.Show("The Account Number does not Exist");
                    }
                    else
                    {
                        lblBalance.Text        = (Convert.ToDecimal(lblBalance.Text) - Convert.ToDecimal(txtAmount.Text)).ToString();
                        Receiver.Balance      += Convert.ToDecimal(txtAmount.Text);
                        customerDetail.Balance = Convert.ToDecimal(lblBalance.Text);
                        var newCustomer = new CustomerController();

                        newCustomer.EditCustomerDetail(await SubmitChanges(Receiver));
                    }
                }

                if ((transtype == "transfer" && status == true) || (transtype != "transfer"))
                {
                    var updateCustomer = new CustomerController();
                    updateCustomer.EditCustomerDetail(await SubmitChanges(customerDetail));


                    var Repo = new TransactionController();
                    Repo.AddTransaction(tempTrans);
                    if (transtype == "deposit")
                    {
                        MessageBox.Show("You have Deposited : " + tempTrans.Amount + " t0 " + tempTrans.ReceipientAccNo);
                    }
                    else if (transtype == "withdraw")
                    {
                        MessageBox.Show("You have Withdrawn : " + tempTrans.Amount + " from " + tempTrans.SenderName);
                    }
                    else if (transtype == "transfer")
                    {
                        MessageBox.Show("You have Transferd : " + tempTrans.Amount + " t0 " + tempTrans.ReceipientAccNo);
                    }
                    updateCustomer.GetCustomerDetails();
                    this.Close();
                }
            }
        }
示例#52
0
 /// The smart way:
 ///  <inheritdoc cref="IsPositionReachable(Vector3, bool, float, GameObject)"/>
 public bool IsRegisterTileReachable(RegisterTile otherObject, bool isServer, float interactDist = interactionDistance, GameObject context = null)
 {
     return(Validations.IsReachableByRegisterTiles(registerTile, otherObject, isServer, interactDist, context: context));
 }
示例#53
0
 ///     Checks if the player is within reach of something
 /// <param name="otherPosition">The position of whatever we are trying to reach</param>
 /// <param name="interactDist">Maximum distance of interaction between the player and other objects</param>
 public bool IsInReach(Vector3 otherPosition, bool isServer, float interactDist = interactionDistance)
 {
     return(Validations.IsInReach(isServer ? registerTile.WorldPositionServer : registerTile.WorldPositionClient, otherPosition, interactDist));
 }
示例#54
0
 ///     Checks if the player is within reach of something
 /// <param name="otherPosition">The position of whatever we are trying to reach</param>
 /// <param name="isServer">True if being executed on server, false otherwise</param>
 /// <param name="interactDist">Maximum distance of interaction between the player and other objects</param>
 /// <param name="context">If not null, will ignore collisions caused by this gameobject</param>
 public bool IsPositionReachable(Vector3 otherPosition, bool isServer, float interactDist = interactionDistance, GameObject context = null)
 {
     return(Validations.IsReachableByPositions(isServer ? registerTile.WorldPositionServer : registerTile.WorldPositionClient, otherPosition, isServer, interactDist, context: context));
 }
示例#55
0
 private bool CPFValido(string cpf)
 {
     return(Validations.ValidateCPF(cpf));
 }
        public void ServerPerformInteraction(HandApply interaction)
        {
            if (state == CameraAssemblyState.Unwelded)
            {
                if (Validations.HasUsedActiveWelder(interaction))
                {
                    //Weld onto wall
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start welding the camera assembly onto the wall...",
                                                              $"{interaction.Performer.ExpensiveName()} starts welding the camera assembly onto the wall...",
                                                              "You weld the camera assembly onto the wall.",
                                                              $"{interaction.Performer.ExpensiveName()} welds the camera assembly onto the wall.",
                                                              () =>
                    {
                        SetState(CameraAssemblyState.Welded);
                    });

                    return;
                }

                if (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Wrench))
                {
                    //Wrench from wall
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start wrenching the camera assembly from the wall...",
                                                              $"{interaction.Performer.ExpensiveName()} starts wrenching the camera assembly from the wall...",
                                                              "You wrench the camera assembly from the wall.",
                                                              $"{interaction.Performer.ExpensiveName()} wrenchs the camera assembly from the wall.",
                                                              () =>
                    {
                        Spawn.ServerPrefab(securityCameraItemPrefab, registerTile.WorldPositionServer,
                                           transform.parent);

                        _ = Despawn.ServerSingle(gameObject);
                    });

                    return;
                }

                return;
            }

            if (state == CameraAssemblyState.Welded)
            {
                if (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Cable))
                {
                    //Add cable
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start adding cable to the camera assembly...",
                                                              $"{interaction.Performer.ExpensiveName()} starts adding cable to the camera assembly...",
                                                              "You add cable to the camera assembly.",
                                                              $"{interaction.Performer.ExpensiveName()} adds cable to the camera assembly.",
                                                              () =>
                    {
                        Inventory.ServerConsume(interaction.HandSlot, 1);
                        SetState(CameraAssemblyState.Wired);
                    });

                    return;
                }

                if (Validations.HasUsedActiveWelder(interaction))
                {
                    //Unweld from wall
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start unwelding the camera assembly from the wall...",
                                                              $"{interaction.Performer.ExpensiveName()} starts unwelding the camera assembly from the wall...",
                                                              "You unweld the camera assembly onto the wall.",
                                                              $"{interaction.Performer.ExpensiveName()} unwelds the camera assembly from the wall.",
                                                              () =>
                    {
                        SetState(CameraAssemblyState.Unwelded);
                    });

                    return;
                }

                return;
            }

            if (state == CameraAssemblyState.Wired)
            {
                if (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Screwdriver))
                {
                    //Screwdrive shut
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start closing the panel on the camera assembly...",
                                                              $"{interaction.Performer.ExpensiveName()} starts closing the panel on the camera assembly...",
                                                              "You close the panel on the camera assembly.",
                                                              $"{interaction.Performer.ExpensiveName()} closes the panel on the camera assembly.",
                                                              () =>
                    {
                        var result = Spawn.ServerPrefab(securityCameraPrefab, registerTile.WorldPositionServer,
                                                        transform.parent);

                        if (result.Successful)
                        {
                            result.GameObject.GetComponent <Directional>().FaceDirection(directional.CurrentDirection);
                            result.GameObject.GetComponent <SecurityCamera>().SetUp(interaction.PerformerPlayerScript);
                        }

                        _ = Despawn.ServerSingle(gameObject);
                    });

                    return;
                }

                if (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Wirecutter))
                {
                    //Cut cable
                    ToolUtils.ServerUseToolWithActionMessages(interaction, 2f,
                                                              "You start cutting the cable from the camera assembly...",
                                                              $"{interaction.Performer.ExpensiveName()} starts cutting the cable from the camera assembly...",
                                                              "You cut the cable from the camera assembly.",
                                                              $"{interaction.Performer.ExpensiveName()} cuts the cable from the camera assembly.",
                                                              () =>
                    {
                        Spawn.ServerPrefab(CommonPrefabs.Instance.SingleCableCoil, registerTile.WorldPositionServer, transform.parent);
                        SetState(CameraAssemblyState.Welded);
                    });
                }
            }
        }
示例#57
0
    /// <summary>
    /// Client:
    /// Allow items to be stored by clicking on bags with item in hand
    /// and clicking items with bag in hand if CanClickPickup is enabled
    /// </summary>
    public bool WillInteract(PositionalHandApply interaction, NetworkSide side)
    {
        if (allowedToInteract == false)
        {
            return(false);
        }
        // Use default interaction checks
        if (DefaultWillInteract.Default(interaction, side) == false)
        {
            return(false);
        }

        // See which item needs to be stored
        if (Validations.IsTarget(gameObject, interaction))
        {
            // We're the target
            // If player's hands are empty let Pickupable handle the interaction
            if (interaction.HandObject == null)
            {
                return(false);
            }

            // There's something in the player's hands
            // Check if item from the hand slot fits in this storage sitting in the world
            if (Validations.CanPutItemToStorage(interaction.PerformerPlayerScript,
                                                itemStorage, interaction.HandObject, side, examineRecipient: interaction.Performer) == false)
            {
                Chat.AddExamineMsgToClient($"The {interaction.HandObject.ExpensiveName()} doesn't fit!");
                return(false);
            }

            return(true);
        }
        else if (canClickPickup)
        {
            // If we can click pickup then try to store the target object
            switch (pickupMode)
            {
            case PickupMode.Single:
                // See if there's an item to pickup
                if (interaction.TargetObject == null ||
                    interaction.TargetObject.Item() == null)
                {
                    Chat.AddExamineMsgToClient("There's nothing to pickup!");
                    return(false);
                }

                if (!Validations.CanPutItemToStorage(interaction.PerformerPlayerScript,
                                                     itemStorage, interaction.TargetObject, side, examineRecipient: interaction.Performer))
                {
                    // In Single pickup mode if the target item doesn't
                    // fit then don't interact
                    Chat.AddExamineMsgToClient($"The {interaction.TargetObject.ExpensiveName()} doesn't fit!");
                    return(false);
                }

                break;

            case PickupMode.Same:
                if (interaction.TargetObject == null)
                {
                    // If there's nothing to compare then don't interact
                    Chat.AddExamineMsgToClient("There's nothing to pickup!");
                    return(false);
                }

                break;
            }

            // In Same and All pickup modes other items on the
            // tile could still be picked up, so we interact
            return(true);
        }
        else
        {
            // We're not the target and we can't click pickup so don't do anything
            return(false);
        }
    }
示例#58
0
        public static int Run(ConfigFile c, string cmd = "", string filename = "")
        {
            configFile = c;

            if (!String.IsNullOrWhiteSpace(cmd))
            {
                try
                {
                    Validate = new PlainTextResultWriter(Console.Out, Console.Out, Console.Out, Console.Out, configFile.Validate.Outputs.StandardOutputDelimiter);
                    string sql = cmd;
                    db           = new SqliteDb(configFile.Db.DbName, true, null, configFile.Extract.Delimiter, configFile.Db.LogFile).Init();
                    SqliteStatus = db.ExecuteQuery(sql, Validate, "Command line query");
                }

                catch (Exception e)
                {
                    Console.WriteLine("Something went wrong trying to read the input command. Try again... " + e.Message);
                }
            }

            else if (!String.IsNullOrWhiteSpace(filename))
            {
                try
                {
                    Validate = new PlainTextResultWriter(Console.Out, Console.Out, Console.Out, Console.Out, configFile.Validate.Outputs.StandardOutputDelimiter);
                    string sql = GetSqlContents(filename);
                    db           = new SqliteDb(configFile.Db.DbName, true, null, configFile.Extract.Delimiter, configFile.Db.LogFile).Init();
                    SqliteStatus = db.ExecuteQuery(sql, Validate, "Command line file execution");
                }

                catch (Exception e)
                {
                    Console.WriteLine("Something went wrong trying to read the input file. Try again... " + e.Message);
                }
            }

            else
            {
                try
                {
                    Validate  = new PlainTextResultWriter(Console.Out, Console.Out, Console.Out, Console.Out);
                    Transform = new PlainTextResultWriter(Console.Out, Console.Out, Console.Out, Console.Out);
                    Load      = new PlainTextResultWriter(Console.Out, Console.Out, Console.Out, Console.Out);
                    Validations validator = null;
                    SqliteStatus = 0;
                    string sql;
                    db = new SqliteDb(configFile.Db.DbName, configFile.Db.UseExistingDb, null, configFile.Extract.Delimiter, configFile.Db.LogFile).Init();

                    // NPS_TODO add error outputting for when these fail to load
                    if (configFile.Steps.Validate)
                    {
                        Validate = ConfigFileInit.InitValidateFromConfig(configFile);
                    }
                    if (configFile.Steps.Transform)
                    {
                        Transform = ConfigFileInit.InitTransformFromConfig(configFile);
                    }
                    if (configFile.Steps.Load)
                    {
                        Load = ConfigFileInit.InitLoadFromConfig(configFile, db);
                    }

                    DirectoryInfo schemaDirInfo      = new DirectoryInfo(configFile.Extract.Schemas);
                    DirectoryInfo sourceFilesDirInfo = new DirectoryInfo(configFile.Extract.Source);
                    DirectoryInfo validationDirInfo  = new DirectoryInfo(configFile.Validate.ValidationSource);
                    DirectoryInfo loadDirInfo        = new DirectoryInfo(configFile.Load.LoadSource);
                    DirectoryInfo seedDirInfo        = new DirectoryInfo(configFile.Extract.SeedData);
                    SchemaFile    schemaFile         = null;
                    SqliteModeler modeler            = null;


                    Validate.BeginOutput("");

                    if (configFile.Steps.Extract)
                    {
                        //NPS_TODO: Add check to see if we need to do this on reuse db
                        sql          = new SqliteModeler().CreateGeneralErrorWarningDdl();
                        SqliteStatus = db.ModifyDdlFromSqlString(sql);
                        Validate.WriteVerbose(SqliteStatus.ToString() + ":" + sql + "||" + db.LastError);

                        // load seed data
                        if (seedDirInfo.Exists)
                        {
                            foreach (var seedFile in seedDirInfo.GetFiles("*.sql"))
                            {
                                //NPS_TODO: Add check to see if we need to do this on reuse db
                                currentStep  = SetCurrentStep("Reading seed data from " + seedFile.Name, Validate);
                                SqliteStatus = db.ExecuteQuery(File.ReadAllText(seedFile.FullName), Validate);
                            }
                        }
                    }
                    foreach (var file in schemaDirInfo.GetFiles("*.json"))
                    {
                        //NPS_TODO: See if Scheme has already been created
                        // create schemafile object
                        currentStep = SetCurrentStep("Reading schema file: " + file.Name, Validate);
                        schemaFile  = JsonConvert.DeserializeObject <SchemaFile>(File.ReadAllText(file.FullName));

                        Validate.BeginContext(schemaFile.Name, Globals.ResultWriterDestination.stdOut);
                        if (configFile.Validate.Outputs.Warnings && (configFile.Validate.Outputs.StandardOutputConnectionString != configFile.Validate.Outputs.WarningsOutputConnectionString))
                        {
                            if (Validate.ResultMode == "delimited")
                            {
                                Validate.Write(schemaFile.Name, Globals.ResultWriterDestination.Warning);
                            }
                            else if (Validate.ResultMode == "json")
                            {
                                Validate.BeginContext(schemaFile.Name, Globals.ResultWriterDestination.Warning);
                            }
                        }


                        // create SQLiteModeler
                        currentStep = SetCurrentStep("Setting schema file: " + file.Name, Validate);
                        modeler     = new SqliteModeler().SetSchemaFile(schemaFile);

                        // create SQL from schemafile
                        currentStep = SetCurrentStep("Creating DDL...", Validate);
                        sql         = modeler.CreateDdl(true).Ddl;

                        // execute DDL in schemafile
                        currentStep  = SetCurrentStep("Modifying SQLite DB with DDL...", Validate);
                        SqliteStatus = db.ModifyDdlFromSqlString(sql);
                        Validate.WriteVerbose(SqliteStatus.ToString() + ":" + sql);

                        // create SQL from schemafile
                        currentStep = SetCurrentStep("Creating DDL...", Validate);
                        sql         = modeler.CreateErrorDdl().ErrorDdl;

                        // execute DDL in schemafile
                        currentStep  = SetCurrentStep("Modifying SQLite DB with Error DDL...", Validate);
                        SqliteStatus = db.ModifyDdlFromSqlString(sql);
                        Validate.WriteVerbose(SqliteStatus.ToString() + ":" + sql);

                        // find linked flat file
                        var      files    = GetFullFilePath(sourceFilesDirInfo, schemaFile.Flatfile, Validate);
                        Flatfile flatfile = null;

                        if (configFile.Steps.Extract)
                        {
                            foreach (var f in files)
                            {
                                var  reuseDbSql     = "SELECT * FROM FileAudit WHERE FileName = '" + f + "';";
                                bool shouldReadFile = true;
                                if (configFile.Db.UseExistingDb && db.QueryHasResults(reuseDbSql))
                                {
                                    shouldReadFile = false;
                                }

                                if (f != String.Empty && shouldReadFile)
                                {
                                    //import flat file
                                    currentStep = SetCurrentStep("Importing flatfile " + f + "...", Validate);

                                    //NPS_TODO: setup File
                                    flatfile = new Flatfile(f, schemaFile.Name, schemaFile.Delimiter.ToString(), "\"", true, null, schemaFile);
                                    int linesRead = 0;
                                    SqliteStatus = db.ImportDelimitedFile(flatfile, out linesRead, configFile, true);
                                    // NPS_TODO: Make linenum optional in configfile

                                    currentStep = SetCurrentStep("Finished reading flatfile " + f + "...", Validate);
                                    var auditSql = "INSERT INTO FileAudit VALUES ('" + f + "', CURRENT_TIMESTAMP, " + schemaFile.Fields.Count + ", " + linesRead + ");";
                                    SqliteStatus = db.ExecuteQuery(auditSql, Validate);
                                }
                            }

                            if (files.Count == 0)
                            {
                                SqliteStatus = db.ExecuteQuery("INSERT INTO GeneralErrors VALUES ('File Missing', 'None', '" + schemaFile.Name + "', 'Error', 'Failed to find file matching " + schemaFile.Flatfile + "');", Validate);
                                Validate.EndContext(Globals.ResultWriterDestination.stdOut);
                                continue; // no files, continue the loop so no validation happens
                            }
                            else
                            {
                                var metadataSql = "";
                                // NPS_TODO: Handle Derivations flag
                                // DERIVATIONS
                                foreach (var schemaField in flatfile.Schemafile.Fields.Where(x => x.ColumnType == ColumnType.Derived).Select(x => x))
                                {
                                    var derivationSql = "UPDATE " + flatfile.Tablename + " SET " + schemaField.Name + " = " + schemaField.Derivation + ";";
                                    SqliteStatus = db.ExecuteQuery(derivationSql, Validate);
                                }
                                foreach (var schemaField in schemaFile.Fields)
                                {
                                    metadataSql = "INSERT INTO TableMetadata VALUES ('" + schemaFile.Name + "', '" + schemaField.Name + "', '" + schemaField.DataType + "');";
                                    // finding numeric precision/scale for sql server
                                    // with cte as (select length(b)-1 as precision, length(b) - instr(b, '.') as scale from foo) select case when
                                    // max(precision) - min(scale) >= 38 then 38 else max(precision) end as precision, max(scale) from cte;
                                    SqliteStatus = db.ExecuteQuery(metadataSql, Validate);
                                }
                                metadataSql  = "INSERT INTO TableMetadata VALUES ('" + schemaFile.Name + "', 'LineNum', 'int');";
                                SqliteStatus = db.ExecuteQuery(metadataSql, Validate);
                            }
                        }

                        #region Validate

                        // file level validations
                        if (configFile.Steps.Validate)
                        {
                            validator   = new Validations(configFile.Validate.SchemaErrorSettings, db, Validate, (code => SqliteStatus = code), configFile.Validate, schemaFile.Name);
                            currentStep = SetCurrentStep("Validating file", Validate);

                            foreach (var schemaField in schemaFile.Fields)
                            {
                                validator.ValidateFields(schemaField, schemaFile.Name, Validate);
                            }

                            if (schemaFile.SummarizeResults)
                            {
                                validator.PrintSummaryResults(schemaFile.Name, Globals.ResultWriterDestination.stdOut);
                                if (configFile.Validate.Outputs.Warnings)
                                {
                                    validator.PrintSummaryResults(schemaFile.Name, Globals.ResultWriterDestination.Warning);
                                }
                            }

                            validator.PrintDetailResults(schemaFile.Name, Globals.ResultWriterDestination.stdOut);
                            if (configFile.Validate.Outputs.Warnings)
                            {
                                validator.PrintDetailResults(schemaFile.Name, Globals.ResultWriterDestination.Warning);
                            }
                        }

                        Validate.EndContext(Globals.ResultWriterDestination.stdOut);
                        if (Validate.ResultMode == "json" && configFile.Validate.Outputs.Warnings &&
                            (configFile.Validate.Outputs.StandardOutputConnectionString != configFile.Validate.Outputs.WarningsOutputConnectionString))
                        {
                            Validate.EndContext(Globals.ResultWriterDestination.Warning);
                        }
                    } // end for each flat file

                    //
                    // Custom validation checks
                    // Possibly cross file / multi table joins
                    //
                    if (configFile.Steps.Validate && !string.IsNullOrWhiteSpace(configFile.Validate.ValidationSource))
                    {
                        string ctx = "Custom Data Validation Checks";
                        // Perhaps we have no flatfiles but do have a db and custom validations - in this case validator would be null
                        if (validator == null)
                        {
                            validator = new Validations(configFile.Validate.SchemaErrorSettings, db, Validate, (code => SqliteStatus = code), configFile.Validate, "GeneralErrors");
                        }
                        Validate.BeginContext(ctx, Globals.ResultWriterDestination.stdOut);
                        if (configFile.Validate.Outputs.Warnings && (configFile.Validate.Outputs.StandardOutputConnectionString != configFile.Validate.Outputs.WarningsOutputConnectionString))
                        {
                            if (Validate.ResultMode == "delimited")
                            {
                                Validate.Write(ctx, Globals.ResultWriterDestination.Warning);
                            }
                            else if (Validate.ResultMode == "json")
                            {
                                Validate.BeginContext(ctx, Globals.ResultWriterDestination.Warning);
                            }
                        }

                        foreach (var validationFile in validationDirInfo.GetFiles("*.sql"))
                        {
                            currentStep = SetCurrentStep("Getting contents from: " + validationFile.Name, Validate);
                            validator.ValidateCustom(validationFile, configFile.Validate.QueryErrorLimit, configFile.Validate.Outputs.Warnings);
                        }
                        Validate.EndContext(Globals.ResultWriterDestination.stdOut);
                        if (Validate.ResultMode == "json" && configFile.Validate.Outputs.Warnings &&
                            (configFile.Validate.Outputs.StandardOutputConnectionString != configFile.Validate.Outputs.WarningsOutputConnectionString))
                        {
                            Validate.EndContext(Globals.ResultWriterDestination.Warning);
                        }
                    }
                    if (configFile.Steps.Validate)
                    {
                        validator.PrintGeneralIssues(Globals.ResultWriterDestination.stdOut);
                        if (configFile.Validate.Outputs.Warnings)
                        {
                            validator.PrintGeneralIssues(Globals.ResultWriterDestination.Warning);
                        }
                    }

                    Validate.EndOutput("");
                    #endregion Validate

                    Load.BeginOutput("");
                    if (configFile.Steps.Load)
                    {
                        foreach (var loadFile in loadDirInfo.GetFiles("*.sql"))
                        {
                            currentStep = SetCurrentStep("Getting contents from: " + loadFile.Name, Validate);
                            string context = String.Empty;
                            sql     = GetSqlContents(loadFile.FullName);
                            context = loadFile.Name;

                            SqliteStatus = db.ExecuteQuery(sql, Load, context);
                        }
                    }
                }
                catch (Exception e)
                {
                    Validate.WriteStd("ERROR on step: " + currentStep);
                    Validate.WriteError("[ERROR] " + DateTime.Now);
                    Validate.WriteError("[ERROR MSG] " + e.Message);
                    if (db != null && !string.IsNullOrWhiteSpace(db.LastError))
                    {
                        Validate.WriteError("[DB MSG] " + db.LastError);
                    }

                    Validate.WriteError(e.StackTrace);
                    return(SqliteStatus);
                }
                finally
                {
                    db.Close();
                    Validate.Dispose();
                }
            }
            return(SqliteStatus);
        }
示例#59
0
        /// <summary>
        /// Client Side interaction
        /// </summary>
        /// <param name="interaction"></param>
        /// <param name="side"></param>
        /// <returns></returns>
        public bool WillInteract(HandApply interaction, NetworkSide side)
        {
            if (!DefaultWillInteract.Default(interaction, side))
            {
                return(false);
            }

            if (!Validations.IsTarget(gameObject, interaction))
            {
                return(false);
            }

            //different logic depending on state
            if (CurrentState == initialState)
            {
                //wrench the airlock or deconstruct
                return(Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Wrench) ||
                       Validations.HasUsedActiveWelder(interaction));
            }
            else if (CurrentState == wrenchedState)
            {
                //add 1 cables or unwrench the airlock
                return((Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Cable) && Validations.HasUsedAtLeast(interaction, 1)) ||
                       Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Wrench) || (Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.GlassSheet) &&
                                                                                                   Validations.HasUsedAtLeast(interaction, 1) && !glassAdded && airlockWindowedToSpawn));
            }
            else if (CurrentState == cablesAddedState)
            {
                //add airlock electronics or cut cables
                return(Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Wirecutter) ||
                       Validations.HasUsedComponent <AirlockElectronics>(interaction));
            }
            else if (CurrentState == electronicsAddedState)
            {
                //screw in or pry off airlock electronics
                return(Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Screwdriver) ||
                       Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Crowbar));
            }

            return(false);
        }
示例#60
0
        private void WrireConf(string Server)
        {
        Validations MyValidation = new Validations();   
        string enkTwest = MyValidation.Getpassword(Server);
        string AppPath = Application.StartupPath;
        if (File.Exists(AppPath + @"\accconf.ncf"))
            File.Delete(AppPath + @"\accconf.ncf");
        using (StreamWriter writer =
        new StreamWriter(AppPath + @"\accconf.ncf", true))
            {

            writer.WriteLine(enkTwest);

            }
        }