public ValueBuilder(CultureInfo cultureInfo, ITypeConverter typeConverter) { // register custom BooleanTypeConverter, this might be a bad idea. TypeConverterAttribute converterAttribute = new TypeConverterAttribute(typeof(CustomBooleanConverter)); _typeDescriptorProvider = TypeDescriptor.AddAttributes(typeof(bool), converterAttribute); this._typeConverter = typeConverter; this._culture = cultureInfo; this._errorCollector = null; this._targetType = new Stack<Type>(); this._errorHandlers = new Stack<EventHandler<ErrorEventArg>>(); this.ResolveInterfaceType += (sender, args) => { if (args.RealType != null) return; if (typeof(IEnumerable) == args.InterfaceType) args.RealType = typeof(List<object>); else { Type[] genArgs; if (args.InterfaceType.IsOfGenericType(typeof(IEnumerable<>), out genArgs)) args.RealType = typeof(List<>).MakeGenericType(genArgs); if (args.InterfaceType.IsOfGenericType(typeof(IList<>), out genArgs)) args.RealType = typeof(List<>).MakeGenericType(genArgs); else if (args.InterfaceType.IsOfGenericType(typeof(IDictionary<,>), out genArgs)) args.RealType = typeof(Dictionary<,>).MakeGenericType(genArgs); else if (args.InterfaceType.IsOfGenericType(typeof(ILookup<,>), out genArgs)) args.RealType = typeof(Lookup<,>).MakeGenericType(genArgs); } }; }
public void ShouldNotRecordPaymentsIfDevelopmentYearIsBeforeOriginYear() { var collector = new ErrorCollector(); var block = new OriginBlock(1990, collector); block[1989] = 3; Assert.Equal(0, block[1989]); }
public BuildSymbolTablesVisitor(IGlobalScopeHelper helper, ErrorCollector errorCollector, Dictionary<string, HappyNamespaceTracker> rootNamespaces) : base(VisitorMode.VisitNodeAndChildren) { _errorCollector = errorCollector; _getGlobalGetter = helper.GetGlobalScopeGetter; _setGlobalGetter = helper.GetGlobalScopeSetter; _rootNamespaces = rootNamespaces; }
public AstAnalyzer(HappyLanguageContext languageContext) : base(VisitorMode.VisitNodeAndChildren) { _languageContext = languageContext; _errorCollector = new ErrorCollector(languageContext.ErrorSink); _runtimeContextExp = Expression.Parameter(typeof(HappyRuntimeContext), RuntimeContextIdentifier); _globalScopeExp = this.PropertyOrFieldGet("Globals", _runtimeContextExp); }
public AnalysisContext(ErrorCollector errorCollector, HappyLanguageContext languageContext, Expression runtimeContextExpression, Expression globalScopeExpression) { this.ErrorCollector = errorCollector; this.GlobalScopeExpression = globalScopeExpression; this.RuntimeContextExpression = runtimeContextExpression; this.LanguageContext = languageContext; this.ScopeStack = new Stack<HappySymbolTable>(); }
public DynamicallyCompiledLibraries(ErrorCollector collector) { this.collector = collector; var name = "DynamicallyCompiledLibraries" + GetHashCode(); var assembly_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run); CompilationUnit.MakeDebuggable(assembly_builder); var module_builder = assembly_builder.DefineDynamicModule(name, true); unit = new CompilationUnit(module_builder, true); }
public void ShouldRecordErrorIfDevelopmentYearIsBeforeOriginYear() { var collector = new ErrorCollector(); Assert.False(collector.ContainsErrors); var block = new OriginBlock(1990, collector); block[1989] = 3; Assert.True(collector.ContainsErrors); }
public void ShouldRecordErrorIfNotEnoughColumnsToExtractFrom() { var collector = new ErrorCollector(); Assert.False(collector.ContainsErrors); var mapper = new Mapper<DefaultOrderTargetType>(collector); mapper.Map(new[] {"hello", "4"}); Assert.True(collector.ContainsErrors); Console.WriteLine(collector.ToString()); // if you're interested }
public void ShouldRecordErrorIfUnableToParseTheInput() { var collector = new ErrorCollector(); Assert.False(collector.ContainsErrors); var mapper = new Mapper<SpecifiedOrderTargetType>(collector); mapper.Map(new[] {"4,787a", "hello" }); Assert.True(collector.ContainsErrors); Console.WriteLine(collector.ToString()); // if you're interested }
public HappyScriptCode Analyze(Module module, SourceUnit sourceUnit) { Init(); //This List<Expression> becomes the global scope initializer var rootNamespaces = LoadAllAssemblies(module.LoadDirectives); ExpandoObject importScope = new ExpandoObject(); foreach (HappyNamespaceTracker tracker in rootNamespaces.Values) DynamicObjectHelpers.SetMember(importScope, tracker.Name, tracker); #if WRITE_AST AstWriter writer = new AstWriter(Console.Out); module.WriteString(writer); #endif var getRuntimeContextExpr = Expression.Dynamic(_languageContext.CreateGetMemberBinder(RuntimeContextIdentifier, false), typeof(object), _globalScopeExp); UnaryExpression runtimeContextExpression = Expression.Convert(getRuntimeContextExpr, typeof(HappyRuntimeContext)); var errorCollector = new ErrorCollector(_languageContext.ErrorSink); _analysisContext = new AnalysisContext(errorCollector, _languageContext, runtimeContextExpression, _globalScopeExp); RunAllVisitors(module, rootNamespaces); List<Expression> body = new List<Expression>(); //Initialize globals using (_scopeStack.TrackPush(module.SymbolTable)) { foreach (VariableDef def in module.GlobalDefStatements.SelectMany(defStmt => defStmt.VariableDefs)) { Expression initialValue = def.InitializerExpression != null ? ExpressionAnalyzer.Analyze(_analysisContext, def.InitializerExpression) : Expression.Constant(null, typeof(object)); HappySymbolBase symbol = module.SymbolTable.Items[def.Name.Text]; body.Add(symbol.GetSetExpression(initialValue)); } } body.AddRange(module.Functions.Select( func => _analysisContext.PropertyOrFieldSet(func.Name.Text, _globalScopeExp, FunctionAnalyzer.Analzye(_analysisContext, func)))); //At this point analysis has completed and all of our stacks should be empty DebugAssert.AreEqual(0, _scopeStack.Count, "scope stack not empty after analysis"); //Add an empty expression--prevents an exception by Expression.Lambda when body is empty. //This allows compilation of empty template sets. if(body.Count == 0) body.Add(Expression.Empty()); LambdaExpression globalScopeInitializer = Expression.Lambda(typeof(Action<IDynamicMetaObjectProvider>), Expression.Block(body), new[] { _globalScopeExp }); HappyScriptCode output = new HappyScriptCode(sourceUnit, globalScopeInitializer.Compile()); return output; }
private static bool Discover(string directory, int trim, string github, string output_root, ErrorCollector collector) { var success = true; foreach (var path in Directory.EnumerateDirectories(directory)) { success &= Discover(path, trim, github, output_root, collector); } foreach (var file in Directory.EnumerateFiles(directory, "*.o_0")) { var file_fragment = file.Substring(trim, file.Length - 4 - trim); var uri = file_fragment.Replace(Path.DirectorySeparatorChar, '/'); var output_filename = Path.Combine(output_root, "doc-" + file_fragment.Replace(Path.DirectorySeparatorChar, '-') + ".xml"); var parser = Parser.Open(file); var doc = parser.DocumentFile(collector, uri, github); if (doc != null) { doc.Save(output_filename); } else { success = false; } } return success; }
internal static Type CheckReflectedMethod(ErrorCollector collector, AstNode where, List <MethodInfo> methods, List <expression> arguments, Type return_type, ref bool success) { /* If there are no candidate methods, don't bother checking the types. */ if (methods.Count == 0) { return(0); } /* Find all the methods that match the needed type. */ var candidate_methods = from method in methods where (TypeFromClrType(method.ReturnType) & return_type) != 0 select method; Type candiate_return = 0; foreach (var method in !candidate_methods.Any() ? methods : candidate_methods) { candiate_return |= TypeFromClrType(method.ReturnType); } /* Produce an error for the union of all the types. */ if (!candidate_methods.Any()) { collector.ReportExpressionTypeError(where, return_type, candiate_return); return(0); } /* Check that the arguments match the union of the parameters of all the methods. This means that we might still not have a valid method, but we can check again during codegen. */ for (var it = 0; it < arguments.Count; it++) { Type candidate_parameter_type = 0; foreach (var method in methods) { var param_type = method.IsStatic ? method.GetParameters()[it].ParameterType : (it == 0 ? method.ReflectedType : method.GetParameters()[it - 1].ParameterType); candidate_parameter_type |= TypeFromClrType(param_type); } arguments[it].EnsureType(collector, candidate_parameter_type, ref success, true); } return(candiate_return); }
public void Analyse(ErrorCollector collector) { var environment = new Environment(FileName, StartRow, StartColumn, EndRow, EndColumn, null, false); var queue = new List <AstTypeableNode>(); PropagateEnvironment(collector, queue, environment); var sorted_nodes = new SortedDictionary <int, Dictionary <AstTypeableNode, bool> >(); foreach (var element in queue) { if (!sorted_nodes.ContainsKey(element.Environment.Priority)) { sorted_nodes[element.Environment.Priority] = new Dictionary <AstTypeableNode, bool>(); } sorted_nodes[element.Environment.Priority][element] = true; } foreach (var items in sorted_nodes.Values) { foreach (var element in items.Keys) { element.MakeTypeDemands(collector); } } }
internal Type EnsureIntrinsic(ErrorCollector collector, AstNode node, Type type, bool must_unbox, ref bool success) { if (Intrinsics.ContainsKey(node)) { var intrinsic = Intrinsics[node]; var original_type = intrinsic.Item1; var result = original_type & type; if (result == 0) { success = false; collector.ReportExpressionTypeError(node, original_type, type); } else { Intrinsics[node] = new Tuple <Type, bool>(result, intrinsic.Item2 & must_unbox); } return(result); } else { Intrinsics[node] = new Tuple <Type, bool>(type, must_unbox); return(type); } }
internal static void ReflectMethod(ErrorCollector collector, AstNode where, string type_name, string method_name, int arity, List <System.Reflection.MethodInfo> methods) { var reflected_type = System.Type.GetType(type_name, false); if (reflected_type == null) { collector.RawError(where, "No such type " + type_name + " found. Perhaps you are missing an assembly reference."); } else { foreach (var method in reflected_type.GetMethods()) { var adjusted_arity = method.GetParameters().Length + (method.IsStatic ? 0 : 1); if (method.Name == method_name && adjusted_arity == arity && !method.IsGenericMethod && !method.IsGenericMethodDefinition && AllInParameteres(method)) { methods.Add(method); } } if (methods.Count == 0) { collector.RawError(where, "The type " + type_name + " has no public method named " + method_name + " which takes " + arity + " parameters."); } } }
/// <summary> /// Set Global Error /// </summary> /// <param name="error"></param> public static void SetGlobalError(ErrorCollector error) { HttpContext.Current.Session[SessionNames.Error] = error; }
private static bool AssignValue( object target, ArgumentRecord record, object value, string arg, ErrorCollector collector) { if( record.PropertyType.IsArray ) { if( ( record.ArgumentAttribute.ArgumentOptions & ArgumentOptions.Unique ) != 0 && record.ArrayValues.Contains( value ) ) { collector( String.Format( CultureInfo.InvariantCulture, "Duplicate value specified for the {0} argument. Value was '{1}'.", arg, value ), arg ); return false; } record.ArrayValues.Add( value ); } else { if( record.ValueSet ) { if( ( record.ArgumentAttribute.ArgumentOptions & ArgumentOptions.AtMostOnce ) != 0 ) { collector( String.Format( CultureInfo.InvariantCulture, "The {0} argument has already been specified and can be assigned only once.", arg ), arg ); return false; } if( ( record.ArgumentAttribute.ArgumentOptions & ArgumentOptions.AtMostOnce ) == 0 ) return true; } try { record.SetValue( target, value ); } catch( Exception ex ) { collector( ex.Message, arg ); } } return true; }
public async Task <ActionResult> Register(RegisterViewModel model) { if (UserManager.IsAuthenticated()) { return(AppVar.GetAuthenticationError("You are already authenticated.", "")); } if (ModelState.IsValid) { var errors = new ErrorCollector(); //External Validation. var validator = new DevUserValidator(model, errors, db); var validOtherConditions = validator.ValidateEveryValidations(); if (validOtherConditions) { model.UserName = model.UserName.Trim(); model.FirstName = model.FirstName.Trim(); model.LastName = model.LastName.Trim(); var user = UserManager.GetUserFromViewModel(model); // get user from view model. var result = await Manager.CreateAsync(user, model.Password); if (result.Succeeded) { if (AppVar.Setting.IsConfirmMailRequired && AppVar.Setting.IsFirstUserFound) { #region For every regular user. // First user already found. // mail needs to be confirmed and first user found. #region Send an email to the user about mail confirmation SendConfirmationEmail(user); #endregion #region Redirect to verify since registration //SignOutProgrammaticallyNonRedirect(); return(RedirectToActionPermanent("Verify")); #endregion #endregion } else if (!AppVar.Setting.IsFirstUserFound) { #region For first user / first admin user. // first user not found or email doesn't need to be checked. // first haven't found // This is for first user. #region Send an email to the user about mail confirmation SendConfirmationEmail(user); #endregion #endregion } CallCompleteRegistration(user.UserID, "Rookie"); // only will be called for first user. return(RedirectToActionPermanent("Verify")); } AddErrors(result); } } return(View("Register", model)); }
internal abstract void PropagateEnvironment(ErrorCollector collector, List <AstTypeableNode> queue, Environment environment);
public override Type EnsureType(ErrorCollector collector, Type type, ref bool success, bool must_unbox) { this.must_unbox |= must_unbox; restricted_type &= type; return(Target.EnsureType(collector, type, ref success, must_unbox)); }
public override Type EnsureType(ErrorCollector collector, Type type, ref bool success, bool must_unbox) { return(AnyType); }
public static Path GeneratePath(Cell cell, CellEntranceExit entrance, CellEntranceExit exit, ErrorCollector errors) { // A* Path path = null; bool complete = false; HashSet <Node> openNodes = new HashSet <Node>(); List <Node> closedNodes = new List <Node>(); Vector2Int target = exit.Position + (exit.Side.Opposite().Vector()) * 2; Node startNode = new Node(entrance); SetCost(startNode, target); openNodes.Add(startNode); int depth = 0; while (openNodes.Count > 0 && complete == false && depth < 100000f) { Node node = GetLowestCostNode(openNodes); openNodes.Remove(node); closedNodes.Add(node); List <Node> newNodes = PerformStep(cell, node, target); foreach (Node newNode in newNodes) { if (IsComplete(newNode, target)) { if (newNode.directionCombo < MINIMUM_COMBO) { continue; } path = CreatePath(newNode, exit); complete = true; } else { openNodes.Add(newNode); } } //closedNodes.Add(); depth++; } if (!complete) { errors.Add(new System.Exception("Could not generate a path! " + startNode.position + " -> " + target)); path = new Path(); path.nodes = closedNodes; } return(path); }
public override void EnsureType(ErrorCollector collector, Type type) { }
public abstract void CreateChild(ErrorCollector collector, string name, string root);
public ResolveSymbolsVisitor(ErrorCollector errorCollector) : base(VisitorMode.VisitNodeAndChildren) { _errorCollector = errorCollector; }
public static void LoadProjectPageFromClipboard() { var collector = new ErrorCollector(); var project = Project.current; ProjectPage page = null; try { var text = SDL.SDL_GetClipboardText(); var compressedBytes = Convert.FromBase64String(text.Trim()); using (var deflateStream = new DeflateStream(new MemoryStream(compressedBytes), CompressionMode.Decompress)) { using (var ms = new MemoryStream()) { deflateStream.CopyTo(ms); var bytes = ms.GetBuffer(); var index = 0; if (DataUtils.ReadLine(bytes, ref index) != "YAFC" || DataUtils.ReadLine(bytes, ref index) != "ProjectPage") { throw new InvalidDataException(); } var version = new Version(DataUtils.ReadLine(bytes, ref index) ?? ""); if (version > YafcLib.version) { collector.Error("String was created with the newer version of YAFC (" + version + "). Data may be lost.", ErrorSeverity.Important); } DataUtils.ReadLine(bytes, ref index); // reserved 1 if (DataUtils.ReadLine(bytes, ref index) != "") // reserved 2 but this time it is requried to be empty { throw new NotSupportedException("Share string was created with future version of YAFC (" + version + ") and is incompatible"); } page = JsonUtils.LoadFromJson <ProjectPage>(new ReadOnlySpan <byte>(bytes, index, (int)ms.Length - index), project, collector); } } } catch (Exception ex) { collector.Exception(ex, "Clipboard text does not contain valid YAFC share string", ErrorSeverity.Critical); } if (page != null) { var existing = project.FindPage(page.guid); if (existing != null) { MessageBox.Show((haveChoice, choice) => { if (!haveChoice) { return; } if (choice) { project.RecordUndo().pages.Remove(existing); } else { page.GenerateNewGuid(); } project.RecordUndo().pages.Add(page); MainScreen.Instance.SetActivePage(page); }, "Page already exists", "Looks like this page already exists with name '" + existing.name + "'. Would you like to replace it or import as copy?", "Replace", "Import as copy"); } else { project.RecordUndo().pages.Add(page); MainScreen.Instance.SetActivePage(page); } } if (collector.severity > ErrorSeverity.None) { ErrorListPanel.Show(collector); } }
public override void EnsureType(ErrorCollector collector, Type type) { Target.EnsureType(collector, type); }
public abstract void CreateChild(ErrorCollector collector, string name, string root, ref bool success);
public SemanticVisitor(ErrorCollector errorCollector) : base(VisitorMode.VisitNodeAndChildren) { _errorCollector = errorCollector; }
public override void CreateChild(ErrorCollector collector, string name, string root, ref bool success) { Children[name] = new JunkInfo(); }
//[CompressFilter(Order = 1)] public async Task <ActionResult> Register(RegisterViewModel model) { var errors = new ErrorCollector(); //External Validation. var validOtherConditions = await UserManager.ExternalUserValidation(model, _db, errors); if (ModelState.IsValid && validOtherConditions) { var user = UserManager.GetUserFromViewModel(model); // get user from view model. var result = await Manager.CreateAsync(user, model.Password); if (result.Succeeded) { SignInProgrammatically(user, false); if (model.Role == -1) { } RoleManager.AddTempRoleInfo(user, model.Role); if (AppVar.Setting.IsConfirmMailRequired && AppVar.Setting.IsFirstUserFound) { // mail needs to be confirmed. // first user is already registered #region Send an email to the user about mail confirmation var code = Manager.GenerateEmailConfirmationToken(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code, codeHashed = user.GeneratedGuid }, Request.Url.Scheme); var mailString = MailHtml.EmailConfirmHtml(user, callbackUrl); AppVar.Mailer.Send(user.Email, "Email Confirmation", mailString); #endregion #region Sign out because registration is not complete return(SignOutProgrammatically()); #endregion } if (!AppVar.Setting.IsFirstUserFound) { // first user is not registered yet #region Send an email to the user about mail confirmation var code = Manager.GenerateEmailConfirmationToken(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code, codeHashed = user.GeneratedGuid }, Request.Url.Scheme); var mailString = MailHtml.EmailConfirmHtml(user, callbackUrl); AppVar.Mailer.Send(user.Email, "Email Confirmation", mailString); #endregion } CallCompleteRegistration(user.UserID); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form ViewBag.Roles = new SelectList(RoleManager.GetRoles(), "Id", "Name"); return(View(model)); }
public override void CreateChild(ErrorCollector collector, string name, string root, ref bool success) { Children[name] = new OpenNameInfo(Environment, root + "." + name); }
public DoB(ErrorCollector errorCollector) { _errorCollector = errorCollector; }
private static void PositionRandomly(Cell cell, CellEntranceExit entrance, ErrorCollector errors) { int x, y; bool searchX; switch (entrance.Side) { case Direction.NORTH: x = 0; y = (int)cell.Size - 1; searchX = true; break; case Direction.SOUTH: x = 0; y = 0; searchX = true; break; case Direction.WEST: x = 0; y = 0; searchX = false; break; case Direction.EAST: x = (int)cell.Size - 1; y = 0; searchX = false; break; default: return; } // Try to randomly place int tries = 0; while (tries < 10) { int count = 0; int index = Random.Range(EDGE_MARGIN, (int)(cell.Size - entrance.Width - EDGE_MARGIN)); for (int i = 0; i < entrance.Width; i++) { int x1 = x, y1 = y; if (searchX) { x1 += i + index; } else { y1 += i + index; } if (cell.Get(x1, y1) == 0) { count++; } else { break; } } if (count == entrance.Width) { SetPosition(cell, entrance, x, y, index, searchX); return; } tries++; } // Give up and just place it in the first possible spot for (int i = EDGE_MARGIN; i < cell.Size - entrance.Width - EDGE_MARGIN; i++) { int count = 0; for (int j = 0; j < entrance.Width; j++) { int x1 = x, y1 = y; if (searchX) { x1 += i + j; } else { y1 += i + j; } if (cell.Get(x1, y1) == 0) { count++; } else { break; } } if (count == entrance.Width) { SetPosition(cell, entrance, x, y, i, searchX); return; } } errors.Add(new System.Exception("Unable to place the EntranceExit.")); }
public bool Build(Type propertyType, AstNode astNode, out object value) { if (this._errorHandlers.Count > 0) throw new InvalidOperationException("This method is not reentrant."); if (this._errorCollector != null) this._errorCollector.Dispose(); this._errorCollector = new ErrorCollector(this); this._targetType.Push(propertyType); value = astNode.Visit(this); this._targetType.Pop(); return this._errorCollector.Count == 0; }
private void CreateRoad(Cell cell, CellEntranceExit entrance, CellEntranceExit exit, ErrorCollector errors) { Path path = PathGenerator.GeneratePath(cell, entrance, exit, errors); errors.GoBoom(); Road road = new Road(path); cell.AddRoad(road); }
public abstract void EnsureType(ErrorCollector collector, Type type);
private static bool Discover(string directory, int trim, string github, string output_root, ErrorCollector collector) { var success = true; foreach (var path in Directory.EnumerateDirectories(directory)) { success &= Discover(path, trim, github, output_root, collector); } foreach (var file in Directory.EnumerateFiles(directory, "*.o_0")) { var file_fragment = file.Substring(trim, file.Length - 4 - trim); var uri = file_fragment.Replace(Path.DirectorySeparatorChar, '/'); var output_filename = Path.Combine(output_root, "doc-" + file_fragment.Replace(Path.DirectorySeparatorChar, '-') + ".xml"); var parser = Parser.Open(file); var doc = parser.DocumentFile(collector, uri, github); if (doc != null) { doc.Save(output_filename); } else { success = false; } } return(success); }
public override void Build(ImGui gui) { gui.spacing = 3f; BuildHeader(gui, editingPage == null ? "Create new page" : "Edit page icon and name"); Build(gui, ref name, icon, s => { icon = s; Rebuild(); }); using (gui.EnterRow(0.5f, RectAllocator.RightRow)) { if (editingPage == null && gui.BuildButton("Create", active: !string.IsNullOrEmpty(name))) { callback?.Invoke(name, icon); Close(); } if (editingPage != null && gui.BuildButton("OK", active: !string.IsNullOrEmpty(name))) { if (editingPage.name != name || editingPage.icon != icon) { editingPage.RecordUndo(true).name = name; editingPage.icon = icon; } Close(); } if (gui.BuildButton("Cancel", SchemeColor.Grey)) { Close(); } if (editingPage != null && gui.BuildButton("Duplicate page", SchemeColor.Grey, active: !string.IsNullOrEmpty(name))) { var project = editingPage.owner; var collector = new ErrorCollector(); var serializedCopy = JsonUtils.Copy(editingPage, project, collector); if (collector.severity > ErrorSeverity.None) { ErrorListPanel.Show(collector); } if (serializedCopy != null) { serializedCopy.GenerateNewGuid(); serializedCopy.icon = icon; serializedCopy.name = name; project.RecordUndo().pages.Add(serializedCopy); MainScreen.Instance.SetActivePage(serializedCopy); Close(); } } gui.allocator = RectAllocator.LeftRow; if (editingPage != null && gui.BuildRedButton("Delete page") == ImGuiUtils.Event.Click) { Project.current.RecordUndo().pages.Remove(editingPage); Close(); } } }
protected virtual object Visit(Sequence sequence) { Type targetType = this._targetType.Peek(); object ret; if (targetType.IsArray) { Type elementType = targetType.GetElementType(); Array newArray = Array.CreateInstance(elementType, sequence.Elements.Length); this._targetType.Push(elementType); for (int elemNum = 0; elemNum < sequence.Elements.Length; elemNum++) { AstNode element = sequence.Elements[elemNum]; ValueError[] elementErrors = null; using (ErrorCollector errors = new ErrorCollector(this)) { object value = element.Visit(this); if (errors.Count == 0) newArray.SetValue(value, elemNum); elementErrors = errors.ToArray(); } this.RaiseError(elementErrors); } this._targetType.Pop(); ret = newArray; } else { Type realType; if (targetType.IsInterface) realType = OnResolveInterfaceType(targetType); else realType = targetType; ret = Activator.CreateInstance(realType); MethodInfo[] addMethods = realType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(a => StringComparer.InvariantCultureIgnoreCase.Equals(a.Name, "Add")) .ToArray(); for (int elemNum = 0; elemNum < sequence.Elements.Length; elemNum++) { List<ValueError> elementErrors = new List<ValueError>(); bool success = false; for (int addNum = 0; addNum < addMethods.Length; addNum++) { ParameterInfo[] addParams = addMethods[addNum].GetParameters(); if (addParams.Length != 1) continue; this._targetType.Push(addParams[0].ParameterType); using (ErrorCollector errors = new ErrorCollector(this)) { object value = sequence.Elements[elemNum].Visit(this); if (errors.Count == 0) { try { addMethods[addNum].Invoke(ret, new[] {value}); success = true; break; } catch (Exception ex) { this.RaiseError(new AddError(addMethods[addNum], new[] {value}, new[] {sequence.Elements[elemNum]}, ex)); } } elementErrors.AddRange(errors); } this._targetType.Pop(); } if (!success) { this.RaiseError(elementErrors); } } } return ret; }
internal abstract Environment PropagateEnvironment(ErrorCollector collector, List <AstTypeableNode> queue, Environment environment, ref bool success);
///<summary> /// Parases the command line and stores the values in the target object. ///</summary> ///<param name="target"> /// The object to populate from the command line. ///</param> ///<param name="arguments"> /// The arguments passed in from the console. If null, attempts to read the /// value from the command line. ///</param> ///<param name="collector"> /// A delegate called on each error. ///</param> ///<returns> /// Returns a value indicating if the parsing was successful. ///</returns> public static bool Parse( object target, string[] arguments, ErrorCollector collector ) { if( target == null ) return false; _errors.Clear(); if( collector == null ) collector = DefaultErrorCollector; if( arguments == null ) { var tmp = Environment.GetCommandLineArgs(); arguments = new string[tmp.Length - 1]; Array.Copy( tmp, 1, arguments, 0, arguments.Length ); } ArrayList records; Hashtable nameIndex, shortNameIndex; ArgumentRecord defaultArg; char lastchar, peek; string result; var errors = false; var helpRequested = false; foreach( string arg in arguments ) { var searcharg = arg.ToLower( CultureInfo.InvariantCulture ); if( searcharg == "/help" || searcharg == "/help+" || searcharg == "-help" || searcharg == "-help+" || searcharg == "/?" || searcharg == "/?+" || searcharg == "-?" || searcharg == "-?+" ) { helpRequested = true; break; } } ParseKnownArguments( target, out records, out nameIndex, out shortNameIndex, out defaultArg ); for( var index = 0; index < arguments.Length; index++ ) { var useDefault = false; var arg = arguments[ index ]; if( helpRequested && arg != "/help" && arg != "/help+" && arg != "-help" && arg != "-help+" && arg != "/?" && arg != "/?+" && arg != "-?" && arg != "-?+" ) continue; if( defaultArg == null && arg.Length < 2 ) goto unknown; if( arg[ 0 ] != '-' && arg[ 0 ] != '/' && defaultArg == null ) goto unknown; var searcharg = arg; ArgumentRecord record = null; if( arg[ 0 ] == '-' || arg[ 0 ] == '/' ) { record = FindRecord( arg, records, nameIndex, shortNameIndex ); if( record == null ) goto unknown; } else { record = defaultArg; useDefault = true; } #region Boolean if( record.PropertyType == typeof( bool ) || record.PropertyType.Name == "TriBool" ) { lastchar = arg[ arg.Length - 1 ]; if( lastchar != '-' && lastchar != '+' ) { lastchar = '+'; if( index < arguments.Length - 1 ) { peek = arguments[ index + 1 ][ 0 ]; if( peek == '-' || peek == '+' ) { index++; lastchar = peek; } } } record.SetValue( target, lastchar == '+' ); if( helpRequested ) return false; } #endregion else { if( useDefault ) result = arg; else { result = GetArgumentValue( arguments, record, collector, ref index ); if( result == null && record.ArgumentAttribute.RequiredParameters > 0 ) { record.ValueSet = true; errors = true; continue; } } TypeConverter converter = null; if( record.PropertyType.IsArray ) converter = TypeDescriptor.GetConverter( record.PropertyType.GetElementType() ); else converter = TypeDescriptor.GetConverter( record.PropertyType ); Debug.Assert( converter != null, "Cannot get a valid converter." ); string[] validParameters = null; if( record.ArgumentAttribute.ValidValues != null ) { validParameters = record.ArgumentAttribute.ValidValues.Split( ';' ); if( !HasValidValue( result, validParameters[ 0 ] ) ) { errors = true; collector( String.Format( "'{0}' is not a valid value for the {1} argument.", result, arg ), arg ); continue; } } try { if( result != null ) errors |= !AssignValue( target, record, converter.ConvertFromString( result ), arg, collector ); else errors |= !AssignValue( target, record, null, arg, collector ); } catch( Exception ex ) { collector( ex.Message, arg ); errors = true; } if( record.ArgumentAttribute.Parameters > 1 ) { var parameter = result == null ? 0 : 1; while( parameter < record.ArgumentAttribute.Parameters && index < arguments.Length ) { if( index >= arguments.Length - 1 ) break; if( arguments[ index + 1 ][ 0 ] == '/' || arguments[ index + 1 ][ 1 ] == '-' && FindRecord( arguments[ index + 1 ], records, nameIndex, shortNameIndex ) != null ) break; result = arguments[ index + 1 ]; if( validParameters != null && validParameters.Length > parameter ) { if( !HasValidValue( result, validParameters[ parameter ] ) ) { errors = true; var paramNames = record.ArgumentAttribute.ValueName.Split( ',' ); var paramName = paramNames.Length > parameter ? paramNames[ parameter ] : ( "parameter " + parameter ); collector( String.Format( "'{0}' is not a valid value for the {1} parameter of the {2} argument.", result, paramName, arg ), arg ); parameter++; index++; continue; } } index++; parameter++; errors |= !AssignValue( target, record, converter.ConvertFromString( result ), arg, collector ); } if( parameter < record.ArgumentAttribute.RequiredParameters || ( parameter < record.ArgumentAttribute.Parameters && record.ArgumentAttribute.RequiredParameters == -1 ) ) { collector( String.Format( CultureInfo.InvariantCulture, "Missing <{0}> parameter for {1} argument", record.ValueNames[ parameter ], arg ), arg ); } while( parameter < record.ArgumentAttribute.Parameters ) { AssignValue( target, record, null, arg, collector ); parameter++; } } continue; } continue; unknown: collector( String.Format( CultureInfo.InvariantCulture, "{0} is not a known command line argument.", arg ), arg ); errors = true; } foreach( ArgumentRecord record in records ) { if( record.PropertyType.IsArray ) { if( record.ArrayValues.Count > 0 ) record.SetValue( target, record.ArrayValues.ToArray( record.PropertyType.GetElementType() ) ); } if( ( record.ArgumentAttribute.ArgumentOptions & ArgumentOptions.Required ) != 0 && !record.ValueSet && record.GetValue( target ) == null ) { if( record.ArgumentAttribute.Default ) { collector( String.Format( CultureInfo.InvariantCulture, "The '{0}' argument is required and has not been specified", record.ValueNames[ 0 ] ), record.Name ); } else { collector( String.Format( CultureInfo.InvariantCulture, "The '/{0}' argument is required and has not been specified", record.Name ), record.Name ); } errors = true; } } return ! errors && ! helpRequested; }
internal abstract void MakeTypeDemands(ErrorCollector collector, ref bool _success);
private static string GetArgumentValue( string[] arguments, ArgumentRecord record, ErrorCollector collector, ref int index) { var arg = arguments[ index ]; var required = record.ArgumentAttribute.RequiredParameters > 0; string result; if( arg.IndexOf( ':' ) > -1 && arg[ arg.Length - 1 ] != ':' ) result = arg.Substring( arg.IndexOf( ':' ) + 1 ); else if( index < arguments.Length - 1 ) { result = arguments[ index + 1 ]; if( result.Length > 0 && ( result[ 0 ] == '/' || result[ 0 ] == '-' ) && ! required ) result = null; else index++; } else { if( required ) { collector( String.Format( CultureInfo.InvariantCulture, "Missing <{0}> parameter for {1} argument", record.ValueNames[ 0 ], arg ), arg ); } return null; } return result; }
public abstract Type EnsureType(ErrorCollector collector, Type type, ref bool success, bool must_unbox);
private async Task <TechnicalOutcome> Do(Point point, bool suppressExceptionsIntoResult, TestState testState, int testCaseId, CancellationToken cancelToken) { foreach (var step in point.TestSteps) { if (cancelToken.IsCancellationRequested) { break; } point.RunOk = true; if (!suppressExceptionsIntoResult) { testState = await ExecuteTestStep(point, step, testState, cancelToken); } else { try { testState = await ExecuteTestStep(point, step, testState, cancelToken); } catch (WebDriverException we) when(we.Message.Contains("Variable Resource Not Found")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (WebDriverException we) when(we.Message.Contains("Only one usage of each socket address")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (WebDriverException we) when( we.Message.Contains("The HTTP request to the remote WebDriver server for URL") && we.Message.Contains("timed out")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (NoSuchWindowException we) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (FailureToStartTestException we) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (InvalidOperationException we) when(we.Message.Contains("unable to send message to renderer")) { LogRunAgainException(we, testCaseId); return(TechnicalOutcome.RunAgain); } catch (Exception e) { step.Result = e is TestCaseException?TestStepResult.Failed(e.Message) : TestStepResult.ImplementationError(e); step.Result.RefToScreenshot = ErrorCollector.GetReferenceToAttachmentIfApplicable(testState); Console.WriteLine("For point in testcase " + point.Id + "; screenshot uploaded to " + step.Result.RefToScreenshot); step.Result.SetException(e); point.RunOk = false; _logger.Error(e); break; } } if (!step.Result.Success) { step.Result.RefToScreenshot = ErrorCollector.GetReferenceToAttachmentIfApplicable(testState); Console.WriteLine("For point in testcase " + point.Id + "; screenshot uploaded to " + step.Result.RefToScreenshot); point.RunOk = false; break; } } for (var i = point.TestSteps.Count - 1; i >= 0; i--) { var step = point.TestSteps[i]; try { CleanupTestStep(point, step, testState); } catch (Exception e) { _logger.Error($"Cleanup Failed for Point {point.Id} in Step {step.StepIndex} of TC {testCaseId}: {e.Message}"); } } return(TechnicalOutcome.Ok); }
internal abstract void MakeTypeDemands(ErrorCollector collector);
/** * Run a test case * * @param testCase the test case element in the catalog * @param xpc the XPath compiler to be used for compiling XPath expressions against the catalog * @throws SaxonApiException */ private void runTestCase(XdmNode testCase, XPathCompiler xpc) { string testCaseName = testCase.GetAttributeValue(new QName("name")); feedback.Message("Test case " + testCaseName + Environment.NewLine, false); XdmNode exceptionElement = null; try { exceptionElement = exceptionsMap[testCaseName]; } catch (Exception) { } XdmNode alternativeResult = null; XdmNode optimization = null; if (exceptionElement != null) { string runAtt = exceptionElement.GetAttributeValue(new QName("run")); if ("no".Equals(runAtt)) { WriteTestCaseElement(testCaseName, "notRun", "see exceptions file"); return; } if (unfolded && "not-unfolded".Equals(runAtt)) { WriteTestCaseElement(testCaseName, "notRun", "see exceptions file"); return; } alternativeResult = (XdmNode)xpc.EvaluateSingle("result", exceptionElement); optimization = (XdmNode)xpc.EvaluateSingle("optimization", exceptionElement); } XdmNode environmentNode = (XdmNode)xpc.EvaluateSingle("environment", testCase); TestEnvironment env = null; if (environmentNode == null) { env = localEnvironments["default"]; } else { string envName = environmentNode.GetAttributeValue(new QName("ref")); if (envName == null) { env = processEnvironment(xpc, environmentNode, null); } else { try { env = localEnvironments[envName]; } catch (Exception) { } if (env == null) { try { env = globalEnvironments[envName]; } catch (Exception) { } } if (env == null) { Console.WriteLine("*** Unknown environment " + envName); WriteTestCaseElement(testCaseName, "fail", "Environment " + envName + " not found"); failures++; return; } } } env.xpathCompiler.BackwardsCompatible = false; env.processor.XmlVersion = (decimal)1.0; bool run = true; bool xpDependency = false; string hostLang; string langVersion; if (preferQuery) { hostLang = "XQ"; langVersion = "1.0"; } else { hostLang = "XP"; langVersion = "2.0"; } XdmValue dependencies = xpc.Evaluate("/*/dependency, ./dependency", testCase); foreach (XdmItem dependency in dependencies) { string type = ((XdmNode)dependency).GetAttributeValue(new QName("type")); if (type == null) { throw new Exception("dependency/@type is missing"); } string value = ((XdmNode)dependency).GetAttributeValue(new QName("value")); if (value == null) { throw new Exception("dependency/@value is missing"); } if (type.Equals("spec")) { if (value.Contains("XP") && !value.Contains("XQ")) { hostLang = "XP"; langVersion = (value.Equals("XP20") ? "2.0" : "3.0"); xpDependency = true; } else if (value.Contains("XP") && value.Contains("XQ") && preferQuery) { hostLang = "XQ"; langVersion = (value.Contains("XQ10+") || value.Contains("XQ30") ? "3.0" : "1.0"); } else if (value.Contains("XT")) { hostLang = "XT"; langVersion = (value.Contains("XT30+") || value.Contains("XT30") ? "3.0" : "1.0"); } else { hostLang = "XQ"; langVersion = (value.Contains("XQ10+") || value.Contains("XQ30") ? "3.0" : "1.0"); } } if (type.Equals("feature") && value.Equals("xpath-1.0-compatibility")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; } if (type.Equals("feature") && value.Equals("namespace-axis")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; } if (!DependencyIsSatisfied((XdmNode)dependency, env)) { Console.WriteLine("*** Dependency not satisfied: " + ((XdmNode)dependency).GetAttributeValue(new QName("type"))); WriteTestCaseElement(testCaseName, "notRun", "Dependency not satisfied"); run = false; } } if ((unfolded && !xpDependency) || optimization != null) { hostLang = "XQ"; if (langVersion.Equals("2.0")) { langVersion = "1.0"; } } if (run) { Outcome outcome = null; string exp = null; try { exp = xpc.Evaluate("if (test/@file) then unparsed-text(resolve-uri(test/@file, base-uri(.))) else string(test)", testCase).ToString(); } catch (DynamicError err) { Console.WriteLine("*** Failed to read query: " + err.Message); outcome = new Outcome(err); } if (outcome == null) { if (hostLang.Equals(("XP"))) { XPathCompiler testXpc = env.xpathCompiler; testXpc.XPathLanguageVersion = langVersion; testXpc.DeclareNamespace("fn", JNamespaceConstant.FN); testXpc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); testXpc.DeclareNamespace("math", JNamespaceConstant.MATH); testXpc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); try { XPathSelector selector = testXpc.Compile(exp).Load(); foreach (QName varName in env.params1.Keys) { selector.SetVariable(varName, env.params1[varName]); } if (env.contextNode != null) { selector.ContextItem = env.contextNode; } selector.InputXmlResolver = new TestUriResolver(env); XdmValue result = selector.Evaluate(); outcome = new Outcome(result); } catch (DynamicError err) { Console.WriteLine(err.Message); outcome = new Outcome(err); } catch (StaticError err) { Console.WriteLine(err.Message); outcome = new Outcome(err); } catch (Exception err) { Console.WriteLine("*** Failed to read query: " + err.Message); outcome = new Outcome(new DynamicError("*** Failed to read query: " + err.Message)); } } else { XQueryCompiler testXqc = env.xqueryCompiler; testXqc.XQueryLanguageVersion = langVersion; testXqc.DeclareNamespace("fn", JNamespaceConstant.FN); testXqc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); testXqc.DeclareNamespace("math", JNamespaceConstant.MATH); testXqc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); ErrorCollector errorCollector = new ErrorCollector(); //testXqc.setErrorListener(errorCollector); string decVars = env.paramDecimalDeclarations.ToString(); if (decVars.Length != 0) { int x = (exp.IndexOf("(:%DECL%:)")); if (x < 0) { exp = decVars + exp; } else { exp = exp.Substring(0, x) + decVars + exp.Substring(x + 13); } } string vars = env.paramDeclarations.ToString(); if (vars.Length != 0) { int x = (exp.IndexOf("(:%VARDECL%:)")); if (x < 0) { exp = vars + exp; } else { exp = exp.Substring(0, x) + vars + exp.Substring(x + 13); } } ModuleResolver mr = new ModuleResolver(xpc); mr.setTestCase(testCase); testXqc.QueryResolver = (IQueryResolver)mr; try { XQueryExecutable q = testXqc.Compile(exp); if (optimization != null) { /* XdmDestination expDest = new XdmDestination(); net.sf.saxon.Configuration config = driverProc.Implementation; net.sf.saxon.trace.ExpressionPresenter presenter = new net.sf.saxon.trace.ExpressionPresenter(driverProc.Implementation, expDest.getReceiver(config)); //q.getUnderlyingCompiledQuery().explain(presenter); presenter.close(); XdmNode explanation = expDest.XdmNode; XdmItem optResult = xpc.EvaluateSingle(optimization.GetAttributeValue(new QName("assert")), explanation); if ((bool)((XdmAtomicValue)optResult).Value) { Console.WriteLine("Optimization result OK"); } else { Console.WriteLine("Failed optimization test"); Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Error); driverProc.WriteXdmValue(explanation, serializer); WriteTestCaseElement(testCaseName, "fail", "Failed optimization assertions"); failures++; return; }*/ } XQueryEvaluator selector = q.Load(); foreach (QName varName in env.params1.Keys) { selector.SetExternalVariable(varName, env.params1[varName]); } if (env.contextNode != null) { selector.ContextItem = env.contextNode; } selector.InputXmlResolver= new TestUriResolver(env); XdmValue result = selector.Evaluate(); outcome = new Outcome(result); } catch (DynamicError err) { Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(err); outcome.setErrorsReported(errorCollector.getErrorCodes()); } catch(StaticError err){ Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(err); outcome.setErrorsReported(errorCollector.getErrorCodes()); } catch(Exception err){ Console.WriteLine("TestSet" + testFuncSet); Console.WriteLine(err.Message); outcome = new Outcome(new DynamicError(err.Message)); outcome.setErrorsReported(errorCollector.getErrorCodes()); } } } XdmNode assertion; if (alternativeResult != null) { assertion = (XdmNode)xpc.EvaluateSingle("*[1]", alternativeResult); } else { assertion = (XdmNode)xpc.EvaluateSingle("result/*[1]", testCase); } if (assertion == null) { Console.WriteLine("*** No assertions found for test case " + testCaseName); WriteTestCaseElement(testCaseName, "fail", "No assertions in test case"); failures++; return; } XPathCompiler assertXpc = env.processor.NewXPathCompiler(); assertXpc.XPathLanguageVersion = "3.0"; assertXpc.DeclareNamespace("fn", JNamespaceConstant.FN); assertXpc.DeclareNamespace("xs", JNamespaceConstant.SCHEMA); assertXpc.DeclareNamespace("math", JNamespaceConstant.MATH); assertXpc.DeclareNamespace("map", JNamespaceConstant.MAP_FUNCTIONS); assertXpc.DeclareVariable(new QName("result")); bool b = testAssertion(assertion, outcome, assertXpc, xpc, debug); if (b) { Console.WriteLine("OK"); successes++; feedback.Message("OK" + Environment.NewLine, false); WriteTestCaseElement(testCaseName, "full", null); } else { if (outcome.isException()) { XdmItem expectedError = xpc.EvaluateSingle("result//error/@code", testCase); if (expectedError == null) { // if (debug) { // outcome.getException().printStackTrace(System.out); // } if (outcome.getException() is StaticError) { WriteTestCaseElement(testCaseName, "fail", "Expected success, got " + ((StaticError)outcome.getException()).ErrorCode); feedback.Message("*** fail, result " + ((StaticError)outcome.getException()).ErrorCode.LocalName + " Expected success." + Environment.NewLine, false); } else { WriteTestCaseElement(testCaseName, "fail", "Expected success, got " + ((DynamicError)outcome.getException()).ErrorCode); feedback.Message("*** fail, result " + ((DynamicError)outcome.getException()).ErrorCode.LocalName + " Expected success." + Environment.NewLine, false); } failures++; } else { if (outcome.getException() is StaticError) { WriteTestCaseElement(testCaseName, "different-error", "Expected error:" + expectedError.ToString() /*.GetstringValue()*/ + ", got " + ((StaticError)outcome.getException()).ErrorCode.ToString()); feedback.Message("*** fail, result " + ((StaticError)outcome.getException()).ErrorCode.LocalName + " Expected error:" + expectedError.ToString() + Environment.NewLine, false); } else { WriteTestCaseElement(testCaseName, "different-error", "Expected error:" + expectedError.ToString() /*.GetstringValue()*/ + ", got " + ((DynamicError)outcome.getException()).ErrorCode.ToString()); feedback.Message("*** fail, result " + ((DynamicError)outcome.getException()).ErrorCode.LocalName + " Expected error:" + expectedError.ToString() + Environment.NewLine, false); } wrongErrorResults++; } } else { try { WriteTestCaseElement(testCaseName, "fail", "Wrong results, got " + truncate(outcome.serialize(assertXpc.Processor))); }catch (Exception) { WriteTestCaseElement(testCaseName, "fail", "Wrong results, got "); } failures++; if (debug) { try { feedback.Message("Result:" + Environment.NewLine, false); // driverProc.WriteXdmValue(outcome.getResult(), driverSerializer); feedback.Message("=======" + Environment.NewLine, false); } catch (Exception) { } feedback.Message(outcome.getResult() + Environment.NewLine, false); } else { feedback.Message("*** fail (use -debug to show actual result)" + Environment.NewLine, false); } } } feedback.Feedback(successes, failures, 25693); } }
/// <summary> /// External Validations /// Register Code Validation /// </summary> /// <param name="model"></param> public static async Task <bool> ExternalUserValidation(RegisterViewModel model, ApplicationDbContext db, ErrorCollector errors = null) { var validOtherConditions = true; if (errors == null) { errors = new ErrorCollector(); } if (!AppVar.Setting.IsRegisterCodeRequiredToRegister) { model.RegistraterCode = Guid.NewGuid(); model.Role = -1; } else { var regCode = db.RegisterCodes.FirstOrDefault( n => n.IsUsed == false && n.RoleID == model.Role && n.RegisterCodeID == model.RegistraterCode && !n.IsExpired); if (regCode != null) { if (regCode.ValidityTill <= DateTime.Now) { // not valid regCode.IsExpired = true; errors.AddMedium(MessageConstants.RegistercCodeExpired, MessageConstants.SolutionContactAdmin); await db.SaveChangesAsync(); validOtherConditions = false; } } else { errors.AddMedium(MessageConstants.RegistercCodeNotValid, MessageConstants.SolutionContactAdmin); validOtherConditions = false; } } //validation for country language var languages = CachedQueriedData.GetLanguages(model.CountryID, 0); if (languages == null) { //select english as default. model.CountryLanguageID = CachedQueriedData.GetDefaultLanguage().CountryLanguageID; } else if (languages.Count > 1) { //it should be selected inside the register panel. validOtherConditions = !(model.CountryLanguageID == 0); //if zero then false. errors.AddMedium("You forgot you set your language."); } else if (languages.Count == 1) { model.CountryLanguageID = languages[0].CountryLanguageID; } //validation for country timzone var timezones = CachedQueriedData.GetTimezones(model.CountryID, 0); if (timezones != null && timezones.Count > 1) { //it should be selected inside the register panel. validOtherConditions = !(model.UserTimeZoneID == 0); //if zero then false. errors.AddMedium("You forgot you set your time zone."); } else if (timezones.Count == 1) { model.UserTimeZoneID = timezones[0].UserTimeZoneID; } else { validOtherConditions = false; errors.AddMedium( "You time zone not found. Please contact with admin and notify him/her about the issue to notify developer."); } if (!validOtherConditions) { AppConfig.SetGlobalError(errors); } return(validOtherConditions); }