public void ExercisingStatistics(User user)
        {
            Console.Clear();

            //var allExercisingAc = user.ListOfActivities.OfType<Exercising>().ToList();

            var allExercisingAc = user.ExercisingActivities;

            if (!ValidationHelpers.CheckIfListIsEmpty(allExercisingAc, "exercising statistics"))
            {
                return;
            }

            var totalalExercisingHours = allExercisingAc.Sum(hours => hours.TrackedTime.Minutes);
            var averageExercising      = allExercisingAc.Average(min => min.TrackedTime.Minutes);

            // Favourite type

            int running = allExercisingAc.Where(x => x.ExercisingType == ExercisingType.Running).Count();
            int general = allExercisingAc.Where(x => x.ExercisingType == ExercisingType.General).Count();
            int sport   = allExercisingAc.Where(x => x.ExercisingType == ExercisingType.Sport).Count();

            var exercisingDictionary = new Dictionary <ExercisingType, int>()
            {
                { ExercisingType.Running, running },
                { ExercisingType.General, general },
                { ExercisingType.Sport, sport },
            };
            var favoritetype = exercisingDictionary.FirstOrDefault(type => type.Value == exercisingDictionary.Values.Max()).Key.ToString();

            StringBuilder sb = new StringBuilder();

            sb.Append($"Total exercising hours: {totalalExercisingHours}\n")
            .Append($"Average time spent exercising: {averageExercising} min.\n")
            .Append($"Favourite type: {favoritetype}\n");

            Console.WriteLine(sb.ToString());
        }
Beispiel #2
0
        private async Task ValidateAndSetConsistencyLevelAsync(RequestMessage requestMessage)
        {
            // Validate the request consistency compatibility with account consistency
            // Type based access context for requested consistency preferred for performance
            Cosmos.ConsistencyLevel?consistencyLevel       = null;
            RequestOptions          promotedRequestOptions = requestMessage.RequestOptions;

            if (promotedRequestOptions != null && promotedRequestOptions.BaseConsistencyLevel.HasValue)
            {
                consistencyLevel = promotedRequestOptions.BaseConsistencyLevel;
            }
            else if (this.RequestedClientConsistencyLevel.HasValue)
            {
                consistencyLevel = this.RequestedClientConsistencyLevel;
            }

            if (consistencyLevel.HasValue)
            {
                if (!this.AccountConsistencyLevel.HasValue)
                {
                    this.AccountConsistencyLevel = await this.client.GetAccountConsistencyLevelAsync();
                }

                if (ValidationHelpers.IsValidConsistencyLevelOverwrite(this.AccountConsistencyLevel.Value, consistencyLevel.Value))
                {
                    // ConsistencyLevel compatibility with back-end configuration will be done by RequestInvokeHandler
                    requestMessage.Headers.Add(HttpConstants.HttpHeaders.ConsistencyLevel, consistencyLevel.Value.ToString());
                }
                else
                {
                    throw new ArgumentException(string.Format(
                                                    CultureInfo.CurrentUICulture,
                                                    RMResources.InvalidConsistencyLevel,
                                                    consistencyLevel.Value.ToString(),
                                                    this.AccountConsistencyLevel));
                }
            }
        }
        public void ReadingStatistics(User user)
        {
            Console.Clear();

            var allReadingAc = user.ListOfActivities.OfType <Reading>().ToList();

            if (!ValidationHelpers.CheckIfListIsEmpty(allReadingAc, "reading statistics"))
            {
                return;
            }

            var totalaReadingHours = allReadingAc.Sum(hours => hours.TrackedTime.Minutes);
            var averageReading     = allReadingAc.Average(min => min.TrackedTime.Minutes);
            var totalPages         = allReadingAc.Sum(pages => pages.Pages);

            // Favourite type

            int bellesLetters = allReadingAc.Where(x => x.ReadingType == ReadingType.BellesLettres).Count();
            int fiction       = allReadingAc.Where(x => x.ReadingType == ReadingType.Fiction).Count();
            int profesionlLit = allReadingAc.Where(x => x.ReadingType == ReadingType.ProfessionalLiterature).Count();

            var readingDictionary = new Dictionary <ReadingType, int>()
            {
                { ReadingType.BellesLettres, bellesLetters },
                { ReadingType.Fiction, fiction },
                { ReadingType.ProfessionalLiterature, profesionlLit },
            };
            var favoritetype = readingDictionary.FirstOrDefault(type => type.Value == readingDictionary.Values.Max()).Key.ToString();

            StringBuilder sb = new StringBuilder();

            sb.Append($"Total reading hours: {totalaReadingHours}\n")
            .Append($"Average time spent reading: {averageReading} min\n")
            .Append($"Total number of read pages: {totalPages}\n")
            .Append($"Favourite type: {favoritetype}\n");

            Console.WriteLine(sb.ToString());
        }
Beispiel #4
0
        /// <summary>
        /// Evaluates an expression
        /// </summary>
        /// <typeparam name="T">Type of result</typeparam>
        /// <param name="expression">JavaScript expression</param>
        /// <param name="documentName">Document name</param>
        /// <returns>Result of the expression</returns>
        /// <exception cref="System.ObjectDisposedException">Operation is performed on a disposed MSIE
        /// JavaScript engine.</exception>
        /// <exception cref="System.ArgumentException" />
        /// <exception cref="MsieJavaScriptEngine.NotSupportedTypeException">The type of return value
        /// is not supported.</exception>
        /// <exception cref="MsieJavaScriptEngine.JsRuntimeException">JavaScript runtime error.</exception>
        public T Evaluate <T>(string expression, string documentName)
        {
            VerifyNotDisposed();

            if (string.IsNullOrWhiteSpace(expression))
            {
                throw new ArgumentException(
                          string.Format(CommonStrings.Common_ArgumentIsEmpty, "expression"), "expression");
            }

            Type returnValueType = typeof(T);

            if (!ValidationHelpers.IsSupportedType(returnValueType))
            {
                throw new NotSupportedTypeException(
                          string.Format(CommonStrings.Runtime_ReturnValueTypeNotSupported, returnValueType.FullName));
            }

            string uniqueDocumentName = _documentNameManager.GetUniqueName(documentName);
            object result             = _jsEngine.Evaluate(expression, uniqueDocumentName);

            return(TypeConverter.ConvertToType <T>(result));
        }
        public void OtherHobbiesStatistics(User user)
        {
            Console.Clear();

            //var allOtherHobbies = user.ListOfActivities.OfType<OtherHobbies>().ToList();

            var allOtherHobbies = user.OtherHobbiesActivities;

            if (!ValidationHelpers.CheckIfListIsEmpty(allOtherHobbies, "other hobbies statistics"))
            {
                return;
            }

            var totalOtherHobbiesHours = allOtherHobbies.Sum(hours => hours.TrackedTime.Minutes);
            var namesOfHobbies         = allOtherHobbies.Select(names => names.Hobby).ToList();

            Console.WriteLine($"Total hours spent in your hobbies: {totalOtherHobbiesHours}");
            Console.WriteLine("Your hobbies:");
            foreach (var hobby in namesOfHobbies.Distinct())
            {
                Console.WriteLine($"-{hobby}");
            }
        }
        /// <summary>
        /// Validates this server after it has been loaded.
        /// </summary>
        /// <param name="validationLog">The validation log.</param>
        public virtual void Validate(IValidationLog validationLog)
        {
            logger.Debug("Validating server '{0}'", this.Name ?? string.Empty);

            // Everything must have a name
            if (string.IsNullOrEmpty(this.Name))
            {
                validationLog.AddError("The Server has no name specified.");
            }

            // Validate the children
            foreach (var child in this.Children)
            {
                child.Validate(validationLog);
            }

            // Check if there are any duplicated children
            ValidationHelpers.CheckForDuplicateItems(this.Children, validationLog, "child");
            var projects = this.Children
                           .SelectMany(c => c.ListProjects());

            ValidationHelpers.CheckForDuplicateItems(projects, validationLog, "project");
        }
        public async Task GivenSearchRequest_StudyInstancesLevel_MatchResult()
        {
            DicomDataset matchInstance = await PostDicomFileAsync(new DicomDataset()
            {
                { DicomTag.Modality, "MRI" },
            });

            var studyId = matchInstance.GetSingleValue <string>(DicomTag.StudyInstanceUID);

            await PostDicomFileAsync(new DicomDataset()
            {
                { DicomTag.StudyInstanceUID, studyId },
                { DicomTag.Modality, "CT" },
            });

            using DicomWebAsyncEnumerableResponse <DicomDataset> response = await _client.QueryStudyInstanceAsync(studyId, "Modality=MRI");

            Assert.Equal(KnownContentTypes.ApplicationDicomJson, response.ContentHeaders.ContentType.MediaType);
            DicomDataset[] datasets = await response.ToArrayAsync();

            Assert.Single(datasets);
            ValidationHelpers.ValidateResponseDataset(QueryResource.StudyInstances, matchInstance, datasets[0]);
        }
Beispiel #8
0
        public OAuthValidation()
        {
            Define(oa => oa.ProviderKey).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.OAuthEntity_ProviderKey));

            Define(oa => oa.UserKey).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.OAuthEntity_UserKey));

            Define(oa => oa.User);

            ValidateInstance.By((oauth, context) => {
                var isValid = true;

                var service = EngineContext.Current.Resolve <IOAuthService>();

                if (service.Get(oauth.ProviderKey, oauth.UserKey, true, false).IsDuplicate(oauth))
                {
                    context.AddInvalid(ValidationHelpers.DuplicateValues(Tuple.Create(Members.OAuthEntity_ProviderKey, (object)oauth.ProviderKey), Tuple.Create(Members.OAuthEntity_UserKey, (object)oauth.UserKey)));

                    isValid = false;
                }

                return(isValid);
            });
        }
Beispiel #9
0
        public UserValidation()
        {
            Define(u => u.Email).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.UserEntity_Email)).And.IsEmail().WithMessage(ValidationHelpers.InvalidEmail(Members.UserEntity_Email));

            Define(u => u.OAuths);

            Define(u => u.Roles);

            ValidateInstance.By((user, context) => {
                var isValid = true;

                var service = EngineContext.Current.Resolve <IUserService>();

                if (service.Get(user.Email, true, false).IsDuplicate(user))
                {
                    context.AddInvalid <UserEntity, string>(ValidationHelpers.DuplicateValue(Members.UserEntity_Email, user.Email), u => u.Email);

                    isValid = false;
                }

                return(isValid);
            });
        }
        public bool WizardValidation(string selectedPage)
        {
            bool valResults = true;

            if (selectedPage == "exportConfig")
            {
                if (!string.IsNullOrWhiteSpace(ExportConfigFileLocation))
                {
                    valResults = LoadSettingsFromConfig();
                }
            }
            else if (selectedPage == "exportLocation")
            {
                valResults = ValidationHelpers.IsTextControlNotEmpty(labelFolderPathValidation, textBoxExportLocation);
            }
            else if (selectedPage == "executeExport")
            {
                valResults = ValidationHelpers.IsTextControlNotEmpty(labelSchemaLocationFileValidation, textBoxSchemaLocation) &&
                             ValidationHelpers.IsTextControlNotEmpty(labelExportConnectionValidation, labelTargetConnectionString);
            }

            return(valResults);
        }
        public void GivenInvalidUidValue_WhenResponseIsBuilt_ThenItShouldNotThrowException()
        {
            // Create a DICOM dataset with invalid UID value.
            var dicomDataset = new DicomDataset()
            {
#pragma warning disable CS0618 // Type or member is obsolete
                AutoValidate = false,
#pragma warning restore CS0618 // Type or member is obsolete
            };

            dicomDataset.Add(DicomTag.SOPClassUID, "invalid");

            _storeResponseBuilder.AddFailure(dicomDataset, failureReasonCode: 500);

            StoreResponse response = _storeResponseBuilder.BuildResponse(studyInstanceUid: null);

            Assert.NotNull(response);
            Assert.NotNull(response.Dataset);

            ValidationHelpers.ValidateFailedSopSequence(
                response.Dataset,
                (null, "invalid", 500));
        }
        public void ChangePassword(int userId, string oldPassword, string newPassword)
        {
            var user = db.GetUserById(userId);

            if (user.Password == oldPassword && oldPassword != newPassword)
            {
                if (ValidationHelpers.ValidatePassword(newPassword) == null)
                {
                    MessageHelepers.Message("Password should not be shorter than 6 characters, should contain at least one capital letter" +
                                            "and should contain at least one number", ConsoleColor.Red);
                    Thread.Sleep(3000);
                    return;
                }
            }
            else
            {
                MessageHelepers.Message("You entered your old password wrong or you new password cannot be your old password!", ConsoleColor.Red);
                Thread.Sleep(3000);
                return;
            }
            user.Password = newPassword;
            db.UpdateUser(user);
            MessageHelepers.Message("You succesfully changed your password!", ConsoleColor.Green);
        }
        public QueuedMailValidation()
        {
            Define(qm => qm.FromEmail).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.QueuedMailEntity_FromEmail)).And.IsEmail().WithMessage(ValidationHelpers.InvalidEmail(Members.QueuedMailEntity_FromEmail));

            Define(qm => qm.FromName);

            Define(qm => qm.ToEmail).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.QueuedMailEntity_ToEmail)).And.IsEmail().WithMessage(ValidationHelpers.InvalidEmail(Members.QueuedMailEntity_ToEmail));

            Define(qm => qm.ToName);

            Define(qm => qm.Cc).Satisfy(e => e.All(PatternValidator.IsValidEmail)).WithMessage(ValidationHelpers.InvalidEmail(Members.QueuedMailEntity_Cc));

            Define(qm => qm.Bcc).Satisfy(e => e.All(PatternValidator.IsValidEmail)).WithMessage(ValidationHelpers.InvalidEmail(Members.QueuedMailEntity_Bcc));

            Define(qm => qm.Subject);

            Define(qm => qm.Body).MaxLength();

            Define(qm => qm.Importance);

            Define(qm => qm.SendTries);

            Define(qm => qm.SentDateUtc);
        }
Beispiel #14
0
        /// <summary>
        /// Calls a JavaScript function using the specified engine. If <typeparamref name="T"/> is
        /// not a scalar type, the function is assumed to return a string of JSON that can be
        /// parsed as that type.
        /// </summary>
        /// <typeparam name="T">Type returned by function</typeparam>
        /// <param name="engine">Engine to execute function with</param>
        /// <param name="function">Name of the function to execute</param>
        /// <param name="args">Arguments to pass to function</param>
        /// <returns>Value returned by function</returns>
        public static T CallFunctionReturningJson <T>(this IJsEngine engine, string function, params object[] args)
        {
            if (ValidationHelpers.IsSupportedType(typeof(T)))
            {
                // Type is supported directly (ie. a scalar type like string/int/bool)
                // Just execute the function directly.
                return(engine.CallFunction <T>(function, args));
            }
            // The type is not a scalar type. Assume the function will return its result as
            // JSON.
            var resultJson = engine.CallFunction <string>(function, args);

            try
            {
                return(JsonConvert.DeserializeObject <T>(resultJson));
            }
            catch (JsonReaderException ex)
            {
                throw new ReactException(string.Format(
                                             "{0} did not return valid JSON: {1}.\n\n{2}",
                                             function, ex.Message, resultJson
                                             ));
            }
        }
        public async Task GivenSearchRequest_AllStudyLevel_MatchResult()
        {
            DicomDataset matchInstance = await PostDicomFileAsync(new DicomDataset()
            {
                { DicomTag.StudyDate, "20190101" },
            });

            DicomDataset unMatchedInstance = await PostDicomFileAsync(new DicomDataset()
            {
                { DicomTag.StudyDate, "20190102" },
            });

            var studyId = matchInstance.GetSingleValue <string>(DicomTag.StudyInstanceUID);

            using DicomWebAsyncEnumerableResponse <DicomDataset> response = await _client.QueryStudyAsync("StudyDate=20190101");

            DicomDataset[] datasets = await response.ToArrayAsync();

            Assert.NotEmpty(datasets);
            DicomDataset testDataResponse = datasets.FirstOrDefault(ds => ds.GetSingleValue <string>(DicomTag.StudyInstanceUID) == studyId);

            Assert.NotNull(testDataResponse);
            ValidationHelpers.ValidateResponseDataset(QueryResource.AllStudies, matchInstance, testDataResponse);
        }
Beispiel #16
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            WebServiceInputActivity webServiceReceive = obj as WebServiceInputActivity;

            if (webServiceReceive == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(WebServiceInputActivity).FullName), "obj");
            }

            if (Helpers.IsActivityLocked(webServiceReceive))
            {
                return(validationErrors);
            }

            if (webServiceReceive.IsActivating)
            {
                if (WebServiceActivityHelpers.GetPreceedingActivities(webServiceReceive).GetEnumerator().MoveNext() == true)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_ActivationActivityNotFirst), ErrorNumbers.Error_ActivationActivityNotFirst);
                    error.PropertyName = "IsActivating";
                    validationErrors.Add(error);
                    return(validationErrors);
                }

                if (WebServiceActivityHelpers.IsInsideLoop(webServiceReceive, null))
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_ActivationActivityInsideLoop), ErrorNumbers.Error_ActivationActivityInsideLoop);
                    error.PropertyName = "IsActivating";
                    validationErrors.Add(error);
                    return(validationErrors);
                }
            }
            else
            {
                if (WebServiceActivityHelpers.GetPreceedingActivities(webServiceReceive, true).GetEnumerator().MoveNext() == false)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_WebServiceReceiveNotMarkedActivate), ErrorNumbers.Error_WebServiceReceiveNotMarkedActivate);
                    error.PropertyName = "IsActivating";
                    validationErrors.Add(error);
                    return(validationErrors);
                }
            }

            ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

            if (typeProvider == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
            }

            Type interfaceType = null;

            if (webServiceReceive.InterfaceType != null)
            {
                interfaceType = typeProvider.GetType(webServiceReceive.InterfaceType.AssemblyQualifiedName);
            }

            if (interfaceType == null)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "InterfaceType"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "InterfaceType";
                validationErrors.Add(error);
            }
            else if (!interfaceType.IsInterface)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_InterfaceTypeNotInterface, "InterfaceType"), ErrorNumbers.Error_InterfaceTypeNotInterface);
                error.PropertyName = "InterfaceType";
                validationErrors.Add(error);
            }
            else
            {
                // Validate method
                if (String.IsNullOrEmpty(webServiceReceive.MethodName))
                {
                    validationErrors.Add(ValidationError.GetNotSetValidationError("MethodName"));
                }
                else
                {
                    MethodInfo methodInfo = Helpers.GetInterfaceMethod(interfaceType, webServiceReceive.MethodName);

                    if (methodInfo == null)
                    {
                        ValidationError error = new ValidationError(SR.GetString(SR.Error_MethodNotExists, "MethodName", webServiceReceive.MethodName), ErrorNumbers.Error_MethodNotExists);
                        error.PropertyName = "MethodName";
                        validationErrors.Add(error);
                    }
                    else
                    {
                        ValidationErrorCollection parameterTypeErrors = WebServiceActivityHelpers.ValidateParameterTypes(methodInfo);
                        if (parameterTypeErrors.Count > 0)
                        {
                            foreach (ValidationError parameterTypeError in parameterTypeErrors)
                            {
                                parameterTypeError.PropertyName = "MethodName";
                            }
                            validationErrors.AddRange(parameterTypeErrors);
                        }
                        else
                        {
                            List <ParameterInfo> inputParameters, outParameters;
                            WebServiceActivityHelpers.GetParameterInfo(methodInfo, out inputParameters, out outParameters);

                            // Check to see if all input parameters have a valid binding.
                            foreach (ParameterInfo paramInfo in inputParameters)
                            {
                                string paramName             = paramInfo.Name;
                                string parameterPropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(webServiceReceive.GetType(), paramName);

                                Type   paramType  = paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType;
                                object paramValue = null;
                                if (webServiceReceive.ParameterBindings.Contains(paramName))
                                {
                                    if (webServiceReceive.ParameterBindings[paramName].IsBindingSet(WorkflowParameterBinding.ValueProperty))
                                    {
                                        paramValue = webServiceReceive.ParameterBindings[paramName].GetBinding(WorkflowParameterBinding.ValueProperty);
                                    }
                                    else
                                    {
                                        paramValue = webServiceReceive.ParameterBindings[paramName].GetValue(WorkflowParameterBinding.ValueProperty);
                                    }
                                }

                                if (!paramType.IsPublic || !paramType.IsSerializable)
                                {
                                    ValidationError validationError = new ValidationError(SR.GetString(SR.Error_TypeNotPublicSerializable, paramName, paramType.FullName), ErrorNumbers.Error_TypeNotPublicSerializable);
                                    validationError.PropertyName = parameterPropertyName;
                                    validationErrors.Add(validationError);
                                }
                                else if (!webServiceReceive.ParameterBindings.Contains(paramName) || paramValue == null)
                                {
                                    ValidationError validationError = ValidationError.GetNotSetValidationError(paramName);
                                    validationError.PropertyName = parameterPropertyName;
                                    validationErrors.Add(validationError);
                                }
                                else
                                {
                                    AccessTypes access = AccessTypes.Read;
                                    if (paramInfo.ParameterType.IsByRef)
                                    {
                                        access |= AccessTypes.Write;
                                    }

                                    ValidationErrorCollection variableErrors = ValidationHelpers.ValidateProperty(manager, webServiceReceive, paramValue,
                                                                                                                  new PropertyValidationContext(webServiceReceive.ParameterBindings[paramName], null, paramName), new BindValidationContext(paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType, access));
                                    foreach (ValidationError validationError in variableErrors)
                                    {
                                        validationError.PropertyName = parameterPropertyName;
                                    }
                                    validationErrors.AddRange(variableErrors);
                                }
                            }

                            if (webServiceReceive.ParameterBindings.Count > inputParameters.Count)
                            {
                                validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_AdditionalBindingsFound), ErrorNumbers.Warning_AdditionalBindingsFound, true));
                            }

                            bool foundMatchingResponse = false;
                            foreach (Activity succeedingActivity in WebServiceActivityHelpers.GetSucceedingActivities(webServiceReceive))
                            {
                                if ((succeedingActivity is WebServiceOutputActivity && ((WebServiceOutputActivity)succeedingActivity).InputActivityName == webServiceReceive.Name) ||
                                    (succeedingActivity is WebServiceFaultActivity && ((WebServiceFaultActivity)succeedingActivity).InputActivityName == webServiceReceive.Name))
                                {
                                    foundMatchingResponse = true;
                                    break;
                                }
                            }

                            // If the method has out parameters or is the method has a return value,
                            // check to see if there are any corresponding WebServiceResponse activities.
                            if ((outParameters.Count > 0 || methodInfo.ReturnType != typeof(void)) && !foundMatchingResponse)
                            {
                                validationErrors.Add(new ValidationError(SR.GetString(SR.Error_WebServiceResponseNotFound), ErrorNumbers.Error_WebServiceResponseNotFound));
                            }
                        }
                    }
                }
            }
            return(validationErrors);
        }
Beispiel #17
0
        public SubscriptionValidation()
        {
            Define(s => s.Email).NotNullableAndNotEmpty().WithMessage(ValidationHelpers.Required(Members.SubscriptionEntity_Email)).And.IsEmail().WithMessage(ValidationHelpers.InvalidEmail(Members.SubscriptionEntity_Email));

            Define(s => s.Status);

            Define(s => s.SubscribDateUtc);

            Define(s => s.ConfirmDateUtc);

            Define(s => s.CancelDateUtc);

            ValidateInstance.By((subscription, context) => {
                var isValid = true;

                var service = EngineContext.Current.Resolve <ISubscriptionService>();

                if (service.Get(subscription.Email, true, false).IsDuplicate(subscription))
                {
                    context.AddInvalid <SubscriptionEntity, string>(ValidationHelpers.DuplicateValue(Members.SubscriptionEntity_Email, subscription.Email), s => s.Email);

                    isValid = false;
                }

                return(isValid);
            });
        }
Beispiel #18
0
 /// <summary>
 /// Validate Config properties
 /// </summary>
 public override void Validate()
 {
     base.Validate();
     ValidationHelpers.ValidateRequiredProp(nameof(RedisConnectionString), RedisConnectionString);
     ValidationHelpers.ValidateRequiredProp(nameof(SlackAlertRefreshTokenChannel), SlackAlertRefreshTokenChannel);
 }
        static void Main(string[] args)
        {
            //UserData();
            while (true)
            {
                int userChoice = menus.LogInMenu();
                Console.Clear();
                switch (userChoice)
                {
                case 1:
                    Console.Write("Enter username: "******"Enter password: "******"Enter the folowing to register:");

                    Console.WriteLine("First name:");
                    string firstName = Console.ReadLine();
                    Console.WriteLine("Last name:");
                    string lastName = Console.ReadLine();
                    Console.WriteLine("Age:");
                    int age = ValidationHelpers.ParseNumber(Console.ReadLine(), 120);
                    Console.WriteLine("Username:"******"Password:"******"You succesfully registered!", ConsoleColor.Green);

                    currentUser = user;
                    if (currentUser == null)
                    {
                        continue;
                    }
                    break;

                case 3:
                    Environment.Exit(0);
                    break;
                }
                if (currentUser == null)
                {
                    continue;
                }
                bool isLoggedIn = true;
                while (isLoggedIn)
                {
                    Console.WriteLine($"Hi {currentUser.FirstName} choose one of the following?");
                    int          choice          = menus.MainMenu();
                    ActivityType currentActivity = (ActivityType)choice;
                    Console.Clear();
                    switch (choice)
                    {
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        appServices.TrackingTime(currentActivity, currentUser, userService);
                        break;

                    case 5:
                        if (!ValidationHelpers.CheckIfListIsEmpty(currentUser.ListOfActivities, "statistics"))
                        {
                            continue;
                        }
                        int statisticsMenu = menus.StatisticsMenu();
                        userService.SeeStatistics(currentUser, statisticsMenu);
                        break;

                    case 6:
                        int accountMenu = menus.AccountMenu();
                        if (userService.AccountSettings(currentUser.Id, accountMenu, currentUser))
                        {
                            isLoggedIn = !isLoggedIn;
                        }
                        break;

                    case 7:
                        isLoggedIn = !isLoggedIn;
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Beispiel #20
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            InvokeWebServiceActivity invokeWebService = obj as InvokeWebServiceActivity;

            if (invokeWebService == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(InvokeWebServiceActivity).FullName), "obj");
            }

            if (invokeWebService.ProxyClass == null)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "ProxyClass"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "ProxyClass";
                validationErrors.Add(error);
            }
            else
            {
                ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
                }

                Type proxyClassType = invokeWebService.ProxyClass;

                // Validate method
                if (invokeWebService.MethodName == null || invokeWebService.MethodName.Length == 0)
                {
                    validationErrors.Add(ValidationError.GetNotSetValidationError("MethodName"));
                }
                else
                {
                    MethodInfo methodInfo = proxyClassType.GetMethod(invokeWebService.MethodName);
                    if (methodInfo == null)
                    {
                        ValidationError error = new ValidationError(SR.GetString(SR.Error_MethodNotExists, "MethodName", invokeWebService.MethodName), ErrorNumbers.Error_MethodNotExists);
                        error.PropertyName = "MethodName";
                        validationErrors.Add(error);
                    }
                    else
                    {
                        ArrayList paramInfos = new ArrayList(methodInfo.GetParameters());
                        if (methodInfo.ReturnType != typeof(void))
                        {
                            paramInfos.Add(methodInfo.ReturnParameter);
                        }

                        foreach (ParameterInfo paramInfo in paramInfos)
                        {
                            string paramName = paramInfo.Name;
                            if (paramInfo.Position == -1)
                            {
                                paramName = "(ReturnValue)";
                            }

                            object paramValue = null;
                            if (invokeWebService.ParameterBindings.Contains(paramName))
                            {
                                if (invokeWebService.ParameterBindings[paramName].IsBindingSet(WorkflowParameterBinding.ValueProperty))
                                {
                                    paramValue = invokeWebService.ParameterBindings[paramName].GetBinding(WorkflowParameterBinding.ValueProperty);
                                }
                                else
                                {
                                    paramValue = invokeWebService.ParameterBindings[paramName].GetValue(WorkflowParameterBinding.ValueProperty);
                                }
                            }
                            if (!invokeWebService.ParameterBindings.Contains(paramName) || paramValue == null)
                            {
                                ValidationError validationError = ValidationError.GetNotSetValidationError(paramName);
                                if (InvokeWebServiceActivity.ReservedParameterNames.Contains(paramName))
                                {
                                    validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWebService.GetType(), paramName);
                                }
                                validationError.PropertyName = paramName;
                                validationErrors.Add(validationError);
                            }
                            else
                            {
                                AccessTypes access = AccessTypes.Read;
                                if (paramInfo.IsOut || paramInfo.IsRetval)
                                {
                                    access = AccessTypes.Write;
                                }
                                else if (paramInfo.ParameterType.IsByRef)
                                {
                                    access |= AccessTypes.Write;
                                }

                                ValidationErrorCollection variableErrors = ValidationHelpers.ValidateProperty(manager, invokeWebService, paramValue,
                                                                                                              new PropertyValidationContext(invokeWebService.ParameterBindings[paramName], null, paramName), new BindValidationContext(paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : paramInfo.ParameterType, access));
                                if (InvokeWebServiceActivity.ReservedParameterNames.Contains(paramName))
                                {
                                    foreach (ValidationError validationError in variableErrors)
                                    {
                                        validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWebService.GetType(), paramName);
                                    }
                                }
                                validationErrors.AddRange(variableErrors);
                            }
                        }

                        if (invokeWebService.ParameterBindings.Count > paramInfos.Count)
                        {
                            validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_AdditionalBindingsFound), ErrorNumbers.Warning_AdditionalBindingsFound, true));
                        }
                    }
                }
            }
            return(validationErrors);
        }
 private static bool IsView(ObjectIdentifier id)
 {
     return(id.HasName && ValidationHelpers.IsView(id.Parts.Last()));
 }
        internal static TagBuilder GenerateValidationSummary(
            ViewContext viewContext,
            bool excludePropertyErrors,
            bool isValidationSummaryAll,// اضافه کردن توسط حسام محمودی برای سازگاری با AjaxForm
            string message,
            string headerTag,
            object htmlAttributes)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }
            ViewDataDictionary viewData = viewContext.ViewData;

            if (!viewContext.ClientValidationEnabled && viewData.ModelState.IsValid)
            {
                return((TagBuilder)null);
            }
            ModelStateEntry modelStateEntry1;

            if (excludePropertyErrors && (!viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out modelStateEntry1) || modelStateEntry1.Errors.Count == 0))
            {
                return((TagBuilder)null);
            }
            TagBuilder tagBuilder1;

            if (string.IsNullOrEmpty(message))
            {
                tagBuilder1 = (TagBuilder)null;
            }
            else
            {
                if (string.IsNullOrEmpty(headerTag))
                {
                    headerTag = viewContext.ValidationSummaryMessageElement;
                }
                tagBuilder1 = new TagBuilder(headerTag);
                tagBuilder1.InnerHtml.SetContent(message);
            }
            bool flag = false;
            IList <ModelStateEntry> modelStateList = ValidationHelpers.GetModelStateList(viewData, excludePropertyErrors);
            TagBuilder tagBuilder2 = new TagBuilder("ul");

            foreach (ModelStateEntry modelStateEntry2 in (IEnumerable <ModelStateEntry>)modelStateList)
            {
                for (int index = 0; index < modelStateEntry2.Errors.Count; ++index)
                {
                    string messageOrDefault = ValidationHelpers.GetModelErrorMessageOrDefault(modelStateEntry2.Errors[index]);
                    if (!string.IsNullOrEmpty(messageOrDefault))
                    {
                        TagBuilder tagBuilder3 = new TagBuilder("li");
                        tagBuilder3.InnerHtml.SetContent(messageOrDefault);
                        tagBuilder2.InnerHtml.AppendLine((IHtmlContent)tagBuilder3);
                        flag = true;
                    }
                }
            }
            if (!flag)
            {
                tagBuilder2.InnerHtml.AppendHtml("<li style=\"display:none\"></li>");
                tagBuilder2.InnerHtml.AppendLine();
            }
            TagBuilder tagBuilder4 = new TagBuilder("div");

            tagBuilder4.MergeAttributes <string, object>(GetHtmlAttributeDictionaryOrNull(htmlAttributes));
            if (viewData.ModelState.IsValid)
            {
                tagBuilder4.AddCssClass(HtmlHelper.ValidationSummaryValidCssClassName);
            }
            else
            {
                tagBuilder4.AddCssClass(HtmlHelper.ValidationSummaryCssClassName);
            }
            if (tagBuilder1 != null)
            {
                tagBuilder4.InnerHtml.AppendLine((IHtmlContent)tagBuilder1);
            }
            tagBuilder4.InnerHtml.AppendHtml((IHtmlContent)tagBuilder2);
            if (viewContext.ClientValidationEnabled && !excludePropertyErrors)
            {
                // تغیر توسط حسام محمودی برای سازگاری با AjaxForm
                //tagBuilder4.MergeAttribute("data-valmsg-summary", "true");
                tagBuilder4.MergeAttribute("data-valmsg-summary", isValidationSummaryAll.ToString().ToLower());
            }
            return(tagBuilder4);
        }
        public override void ExecuteResource(string resourceName, Type type)
        {
            VerifyNotDisposed();

            if (resourceName == null)
            {
                throw new ArgumentNullException(
                          nameof(resourceName),
                          string.Format(CoreStrings.Common_ArgumentIsNull, nameof(resourceName))
                          );
            }

            if (type == null)
            {
                throw new ArgumentNullException(
                          nameof(type),
                          string.Format(CoreStrings.Common_ArgumentIsNull, nameof(type))
                          );
            }

            if (string.IsNullOrWhiteSpace(resourceName))
            {
                throw new ArgumentException(
                          string.Format(CoreStrings.Common_ArgumentIsEmpty, nameof(resourceName)),
                          nameof(resourceName)
                          );
            }

            if (!ValidationHelpers.CheckDocumentNameFormat(resourceName))
            {
                throw new ArgumentException(
                          string.Format(CoreStrings.Usage_InvalidResourceNameFormat, resourceName),
                          nameof(resourceName)
                          );
            }

#if NET40
            Assembly assembly = type.Assembly;
#else
            Assembly assembly = type.GetTypeInfo().Assembly;
#endif
            string nameSpace          = type.Namespace;
            string resourceFullName   = nameSpace != null ? nameSpace + "." + resourceName : resourceName;
            string uniqueDocumentName = GetUniqueDocumentName(resourceFullName, false);

            lock (_executionSynchronizer)
            {
                try
                {
                    var source = new ResourceScriptSource(uniqueDocumentName, resourceFullName, assembly);
                    _jsEngine.Execute(source);
                }
                catch (OriginalJavaScriptException e)
                {
                    throw WrapJavaScriptException(e);
                }
                catch (NullReferenceException)
                {
                    throw;
                }
            }
        }
Beispiel #24
0
 private static bool IsValidName(ObjectIdentifier name)
 {
     return(name.HasName && ValidationHelpers.IsStoredProcedure(name.Parts.Last()));
 }
Beispiel #25
0
        protected void ValidateParameters()
        {
            if (this.DnsSettings != null && string.IsNullOrEmpty(this.VNetName))
            {
                throw new ArgumentException(Resources.VNetNameRequiredWhenSpecifyingDNSSettings);
            }

            if (this.ParameterSetName.Contains("Linux") && string.IsNullOrEmpty(this.LinuxUser))
            {
                throw new ArgumentException(Resources.SpecifyLinuxUserWhenCreatingLinuxVMs);
            }

            if (this.ParameterSetName.Contains("Linux") && !ValidationHelpers.IsLinuxPasswordValid(this.Password))
            {
                throw new ArgumentException(Resources.PasswordNotComplexEnough);
            }

            if (this.ParameterSetName.Contains("Windows") && !ValidationHelpers.IsWindowsPasswordValid(this.Password))
            {
                throw new ArgumentException(Resources.PasswordNotComplexEnough);
            }

            if (this.ParameterSetName.Contains("Linux"))
            {
                bool valid = false;
                if (string.IsNullOrEmpty(this.Name))
                {
                    valid = ValidationHelpers.IsLinuxHostNameValid(this.ServiceName); // uses servicename if name not specified
                }
                else
                {
                    valid = ValidationHelpers.IsLinuxHostNameValid(this.Name);
                }
                if (valid == false)
                {
                    throw new ArgumentException(Resources.InvalidHostName);
                }
            }

            if (string.IsNullOrEmpty(this.Name) == false)
            {
                if (this.ParameterSetName.Contains("Windows") && !ValidationHelpers.IsWindowsComputerNameValid(this.Name))
                {
                    throw new ArgumentException(Resources.InvalidComputerName);
                }
            }
            else
            {
                if (this.ParameterSetName.Contains("Windows") && !ValidationHelpers.IsWindowsComputerNameValid(this.ServiceName))
                {
                    throw new ArgumentException(Resources.InvalidComputerName);
                }
            }

            if (!string.IsNullOrEmpty(this.Location) && !string.IsNullOrEmpty(this.AffinityGroup))
            {
                throw new ArgumentException(Resources.EitherLocationOrAffinityGroupBeSpecified);
            }

            if (String.IsNullOrEmpty(this.VNetName) == false && (String.IsNullOrEmpty(this.Location) && String.IsNullOrEmpty(this.AffinityGroup)))
            {
                throw new ArgumentException(Resources.VNetNameCanBeSpecifiedOnlyOnInitialDeployment);
            }
        }
Beispiel #26
0
        protected void ValidateParameters()
        {
            if (this.DnsSettings != null && string.IsNullOrEmpty(this.VNetName))
            {
                throw new ArgumentException(Resources.VNetNameRequiredWhenSpecifyingDNSSettings);
            }

            if (!string.IsNullOrEmpty(this.VNetName) && (this.SubnetNames == null || this.SubnetNames.Length == 0))
            {
                WriteWarning(Resources.SubnetShouldBeSpecifiedIfVnetPresent);
            }

            if (this.ParameterSetName.Contains(LinuxParamSet) && this.Password != null && !ValidationHelpers.IsLinuxPasswordValid(this.Password))
            {
                throw new ArgumentException(Resources.PasswordNotComplexEnough);
            }

            if (this.ParameterSetName.Contains(WindowsParamSet) && this.Password != null && !ValidationHelpers.IsWindowsPasswordValid(this.Password))
            {
                throw new ArgumentException(Resources.PasswordNotComplexEnough);
            }

            if (this.ParameterSetName.Contains(LinuxParamSet))
            {
                bool valid = false;
                if (string.IsNullOrEmpty(this.Name))
                {
                    valid = ValidationHelpers.IsLinuxHostNameValid(this.ServiceName); // uses servicename if name not specified
                }
                else
                {
                    valid = ValidationHelpers.IsLinuxHostNameValid(this.Name);
                }
                if (valid == false)
                {
                    throw new ArgumentException(Resources.InvalidHostName);
                }
            }

            if (string.IsNullOrEmpty(this.Name) == false)
            {
                if (this.ParameterSetName.Contains(WindowsParamSet) && !ValidationHelpers.IsWindowsComputerNameValid(this.Name))
                {
                    throw new ArgumentException(Resources.InvalidComputerName);
                }
            }
            else
            {
                if (this.ParameterSetName.Contains(WindowsParamSet) && !ValidationHelpers.IsWindowsComputerNameValid(this.ServiceName))
                {
                    throw new ArgumentException(Resources.InvalidComputerName);
                }
            }

            if (!string.IsNullOrEmpty(this.Location) && !string.IsNullOrEmpty(this.AffinityGroup))
            {
                throw new ArgumentException(Resources.EitherLocationOrAffinityGroupBeSpecified);
            }
        }
 public override ResourceSet CreateResourceSet(ref ResourceSetDescription description)
 {
     ValidationHelpers.ValidateResourceSet(_gd, ref description);
     return(new D3D11ResourceSet(ref description));
 }
Beispiel #28
0
 private void TabSourceDataLocationTextChanged(object sender, EventArgs e)
 {
     ValidationHelpers.IsTextControlNotEmpty(labelFolderPathValidation, tbSourceDataLocation);
 }
        private void OnGUISceneCheck(VRC_SceneDescriptor scene)
        {
            CheckUploadChanges(scene);

#if !VRC_SDK_VRCSDK2 && !VRC_SDK_VRCSDK3
            bool isSdk3Scene = false;
#elif VRC_SDK_VRCSDK2 && !VRC_SDK_VRCSDK3
            bool isSdk3Scene = false;
#elif !VRC_SDK_VRCSDK2 && VRC_SDK_VRCSDK3
            bool isSdk3Scene = true; //Do we actually use this variable anywhere?
#else
            bool isSdk3Scene = scene as VRCSceneDescriptor != null;
#endif

            List <VRC_EventHandler> sdkBaseEventHandlers =
                new List <VRC_EventHandler>(Object.FindObjectsOfType <VRC_EventHandler>());
#if VRC_SDK_VRCSDK2
            if (isSdk3Scene == false)
            {
                for (int i = sdkBaseEventHandlers.Count - 1; i >= 0; --i)
                {
                    if (sdkBaseEventHandlers[i] as VRCSDK2.VRC_EventHandler)
                    {
                        sdkBaseEventHandlers.RemoveAt(i);
                    }
                }
            }
#endif
            if (sdkBaseEventHandlers.Count > 0)
            {
                _builder.OnGUIError(scene,
                                    "You have Event Handlers in your scene that are not allowed in this build configuration.",
                                    delegate
                {
                    List <Object> gos = sdkBaseEventHandlers.ConvertAll(item => (Object)item.gameObject);
                    Selection.objects = gos.ToArray();
                },
                                    delegate
                {
                    foreach (VRC_EventHandler eh in sdkBaseEventHandlers)
                    {
#if VRC_SDK_VRCSDK2
                        GameObject go = eh.gameObject;
                        if (isSdk3Scene == false)
                        {
                            if (VRC_SceneDescriptor.Instance as VRCSDK2.VRC_SceneDescriptor != null)
                            {
                                go.AddComponent <VRCSDK2.VRC_EventHandler>();
                            }
                        }
#endif
                        Object.DestroyImmediate(eh);
                    }
                });
            }

            Vector3 g = Physics.gravity;
            if (Math.Abs(g.x) > float.Epsilon || Math.Abs(g.z) > float.Epsilon)
            {
                _builder.OnGUIWarning(scene,
                                      "Gravity vector is not straight down. Though we support different gravity, player orientation is always 'upwards' so things don't always behave as you intend.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }
            if (g.y > 0)
            {
                _builder.OnGUIWarning(scene,
                                      "Gravity vector is not straight down, inverted or zero gravity will make walking extremely difficult.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }
            if (Math.Abs(g.y) < float.Epsilon)
            {
                _builder.OnGUIWarning(scene,
                                      "Zero gravity will make walking extremely difficult, though we support different gravity, player orientation is always 'upwards' so this may not have the effect you're looking for.",
                                      delegate { SettingsService.OpenProjectSettings("Project/Physics"); }, null);
            }

            if (CheckFogSettings())
            {
                _builder.OnGUIWarning(
                    scene,
                    "Fog shader stripping is set to Custom, this may lead to incorrect or unnecessary shader variants being included in the build. You should use Automatic unless you change the fog mode at runtime.",
                    delegate { SettingsService.OpenProjectSettings("Project/Graphics"); },
                    delegate
                {
                    EnvConfig.SetFogSettings(
                        new EnvConfig.FogSettings(EnvConfig.FogSettings.FogStrippingMode.Automatic));
                });
            }

            if (scene.autoSpatializeAudioSources)
            {
                _builder.OnGUIWarning(scene,
                                      "Your scene previously used the 'Auto Spatialize Audio Sources' feature. This has been deprecated, press 'Fix' to disable. Also, please add VRC_SpatialAudioSource to all your audio sources. Make sure Spatial Blend is set to 3D for the sources you want to spatialize.",
                                      null,
                                      delegate { scene.autoSpatializeAudioSources = false; }
                                      );
            }

            AudioSource[] audioSources = Object.FindObjectsOfType <AudioSource>();
            foreach (AudioSource a in audioSources)
            {
                if (a.GetComponent <ONSPAudioSource>() != null)
                {
                    _builder.OnGUIWarning(scene,
                                          "Found audio source(s) using ONSP, this is deprecated. Press 'fix' to convert to VRC_SpatialAudioSource.",
                                          delegate { Selection.activeObject = a.gameObject; },
                                          delegate
                    {
                        Selection.activeObject = a.gameObject;
                        AutoAddSpatialAudioComponents.ConvertONSPAudioSource(a);
                    }
                                          );
                    break;
                }
                else if (a.GetComponent <VRC_SpatialAudioSource>() == null)
                {
                    string msg =
                        "Found 3D audio source with no VRC Spatial Audio component, this is deprecated. Press 'fix' to add a VRC_SpatialAudioSource.";
                    if (IsAudioSource2D(a))
                    {
                        msg =
                            "Found 2D audio source with no VRC Spatial Audio component, this is deprecated. Press 'fix' to add a (disabled) VRC_SpatialAudioSource.";
                    }

                    _builder.OnGUIWarning(scene, msg,
                                          delegate { Selection.activeObject = a.gameObject; },
                                          delegate
                    {
                        Selection.activeObject = a.gameObject;
                        AutoAddSpatialAudioComponents.AddVRCSpatialToBareAudioSource(a);
                    }
                                          );
                    break;
                }
            }

            if (VRCSdkControlPanel.HasSubstances())
            {
                _builder.OnGUIWarning(scene,
                                      "One or more scene objects have Substance materials. This is not supported and may break in game. Please bake your Substances to regular materials.",
                                      () => { Selection.objects = VRCSdkControlPanel.GetSubstanceObjects(); },
                                      null);
            }

#if VRC_SDK_VRCSDK2
            foreach (VRC_DataStorage ds in Object.FindObjectsOfType <VRC_DataStorage>())
            {
                VRCSDK2.VRC_ObjectSync os = ds.GetComponent <VRCSDK2.VRC_ObjectSync>();
                if (os != null && os.SynchronizePhysics)
                {
                    _builder.OnGUIWarning(scene, ds.name + " has a VRC_DataStorage and VRC_ObjectSync, with SynchronizePhysics enabled.",
                                          delegate { Selection.activeObject = os.gameObject; }, null);
                }
            }
#endif

            string vrcFilePath = UnityWebRequest.UnEscapeURL(EditorPrefs.GetString("lastVRCPath"));
            if (!string.IsNullOrEmpty(vrcFilePath) &&
                ValidationHelpers.CheckIfAssetBundleFileTooLarge(ContentType.World, vrcFilePath, out int fileSize))
            {
                _builder.OnGUIWarning(scene,
                                      ValidationHelpers.GetAssetBundleOverSizeLimitMessageSDKWarning(ContentType.World, fileSize), null,
                                      null);
            }

            foreach (GameObject go in Object.FindObjectsOfType <GameObject>())
            {
                if (go.transform.parent == null)
                {
                    // check root game objects
#if UNITY_ANDROID
                    IEnumerable <Shader> illegalShaders = VRCSDK2.Validation.WorldValidation.FindIllegalShaders(go);
                    foreach (Shader s in illegalShaders)
                    {
                        _builder.OnGUIWarning(scene, "World uses unsupported shader '" + s.name + "'. This could cause low performance or future compatibility issues.", null, null);
                    }
#endif
                }
                else
                {
                    // Check sibling game objects
                    for (int idx = 0; idx < go.transform.parent.childCount; ++idx)
                    {
                        Transform t = go.transform.parent.GetChild(idx);
                        if (t == go.transform)
                        {
                            continue;
                        }

#if VRC_SDK_VRCSDK2
                        bool allowedType = (t.GetComponent <VRCSDK2.VRC_ObjectSync>() ||
                                            t.GetComponent <VRCSDK2.VRC_SyncAnimation>() ||
                                            t.GetComponent <VRC_SyncVideoPlayer>() ||
                                            t.GetComponent <VRC_SyncVideoStream>());
                        if (t.name != go.transform.name || allowedType)
                        {
                            continue;
                        }
#else
                        if (t.name != go.transform.name)
                        {
                            continue;
                        }
#endif

                        string    path = t.name;
                        Transform p    = t.parent;
                        while (p != null)
                        {
                            path = p.name + "/" + path;
                            p    = p.parent;
                        }

                        _builder.OnGUIWarning(scene,
                                              "Sibling objects share the same path, which may break network events: " + path,
                                              delegate
                        {
                            List <Object> gos = new List <Object>();
                            for (int c = 0; c < go.transform.parent.childCount; ++c)
                            {
                                if (go.transform.parent.GetChild(c).name == go.name)
                                {
                                    gos.Add(go.transform.parent.GetChild(c).gameObject);
                                }
                            }
                            Selection.objects = gos.ToArray();
                        },
                                              delegate
                        {
                            List <Object> gos = new List <Object>();
                            for (int c = 0; c < go.transform.parent.childCount; ++c)
                            {
                                if (go.transform.parent.GetChild(c).name == go.name)
                                {
                                    gos.Add(go.transform.parent.GetChild(c).gameObject);
                                }
                            }
                            Selection.objects = gos.ToArray();
                            for (int i = 0; i < gos.Count; ++i)
                            {
                                gos[i].name = gos[i].name + "-" + i.ToString("00");
                            }
                        });
                        break;
                    }
                }
            }

            // detect dynamic materials and prefabs with identical names (since these could break triggers)
            VRC_Trigger[]     triggers  = Tools.FindSceneObjectsOfTypeAll <VRC_Trigger>();
            List <GameObject> prefabs   = new List <GameObject>();
            List <Material>   materials = new List <Material>();

#if VRC_SDK_VRCSDK2
            AssetExporter.FindDynamicContent(ref prefabs, ref materials);
#elif VRC_SDK_VRCSDK3
            AssetExporter.FindDynamicContent(ref prefabs, ref materials);
#endif

            foreach (VRC_Trigger t in triggers)
            {
                foreach (VRC_Trigger.TriggerEvent triggerEvent in t.Triggers)
                {
                    foreach (VRC_EventHandler.VrcEvent e in triggerEvent.Events.Where(evt =>
                                                                                      evt.EventType == VRC_EventHandler.VrcEventType.SpawnObject))
                    {
                        GameObject go =
                            AssetDatabase.LoadAssetAtPath(e.ParameterString, typeof(GameObject)) as GameObject;
                        if (go == null)
                        {
                            continue;
                        }
                        foreach (GameObject existing in prefabs)
                        {
                            if (go == existing || go.name != existing.name)
                            {
                                continue;
                            }
                            _builder.OnGUIWarning(scene,
                                                  "Trigger prefab '" + AssetDatabase.GetAssetPath(go).Replace(".prefab", "") +
                                                  "' has same name as a prefab in another folder. This may break the trigger.",
                                                  delegate { Selection.objects = new Object[] { go }; },
                                                  delegate
                            {
                                AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(go),
                                                          go.name + "-" + go.GetInstanceID());
                                AssetDatabase.Refresh();
                                e.ParameterString = AssetDatabase.GetAssetPath(go);
                            });
                        }
                    }

                    foreach (VRC_EventHandler.VrcEvent e in triggerEvent.Events.Where(evt =>
                                                                                      evt.EventType == VRC_EventHandler.VrcEventType.SetMaterial))
                    {
                        Material mat = AssetDatabase.LoadAssetAtPath <Material>(e.ParameterString);
                        if (mat == null || mat.name.Contains("(Instance)"))
                        {
                            continue;
                        }
                        foreach (Material existing in materials)
                        {
                            if (mat == existing || mat.name != existing.name)
                            {
                                continue;
                            }
                            _builder.OnGUIWarning(scene,
                                                  "Trigger material '" + AssetDatabase.GetAssetPath(mat).Replace(".mat", "") +
                                                  "' has same name as a material in another folder. This may break the trigger.",
                                                  delegate { Selection.objects = new Object[] { mat }; },
                                                  delegate
                            {
                                AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(mat),
                                                          mat.name + "-" + mat.GetInstanceID());
                                AssetDatabase.Refresh();
                                e.ParameterString = AssetDatabase.GetAssetPath(mat);
                            });
                        }
                    }
                }
            }
        }
Beispiel #30
0
 public override (bool Success, string ErrorMessages) CheckValid()
 {
     return(ValidationHelpers.ValidateObject(this.Data));
 }