public SequenceMultiBacktrackRuleGenerator(SequenceMultiBacktrack seqMulti, SequenceRuleCall seqRule, SequenceExpressionGenerator seqExprGen, SequenceGeneratorHelper seqHelper) { this.seqMulti = seqMulti; this.seqRule = seqRule; this.seqExprGen = seqExprGen; this.seqHelper = seqHelper; ArgumentExpressions = seqRule.ArgumentExpressions; ReturnVars = seqRule.ReturnVars; specialStr = seqRule.Special ? "true" : "false"; matchingPatternClassName = "GRGEN_ACTIONS." + TypesHelper.GetPackagePrefixDot(seqRule.Package) + "Rule_" + seqRule.Name; patternName = seqRule.Name; plainRuleName = TypesHelper.PackagePrefixedNameDoubleColon(seqRule.Package, seqRule.Name); ruleName = "rule_" + TypesHelper.PackagePrefixedNameUnderscore(seqRule.Package, seqRule.Name); matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); matchName = "match_" + seqRule.Id; matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; matchesName = "matches_" + seqRule.Id; }
private static void GenerateInternalObjectTypeAttributeInitializer(SequenceCheckingEnvironment env, IGraphModel model, SequenceExpressionNew attributeInitializer, SourceBuilder source) { if (attributeInitializer.AttributeInitializationList == null) { return; // plain constructor without attribute initialization list } string internalObjectType = "GRGEN_MODEL." + attributeInitializer.ConstructedType; source.Append("\n"); source.AppendFront("public static "); source.Append(internalObjectType); source.Append(" fillFromSequence_" + attributeInitializer.Id + "("); BaseObjectType objectType = env.Model.ObjectModel.GetType(attributeInitializer.ConstructedType); if (objectType != null) { source.Append("long uniqueId"); } for (int i = 0; i < attributeInitializer.AttributeInitializationList.Count; ++i) { KeyValuePair <string, SequenceExpression> attributeInitialization = attributeInitializer.AttributeInitializationList[i]; if (i > 0 || objectType != null) { source.Append(", "); } string valueType = TypesHelper.XgrsTypeToCSharpType(env.TypeOfMemberOrAttribute(attributeInitializer.ConstructedType, attributeInitialization.Key), model); source.AppendFormat("{0} {1}", valueType, "param" + i); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} obj = new {0}({1});\n", internalObjectType, objectType != null ? "uniqueId" : ""); for (int i = 0; i < attributeInitializer.AttributeInitializationList.Count; ++i) { KeyValuePair <string, SequenceExpression> attributeInitialization = attributeInitializer.AttributeInitializationList[i]; source.AppendFrontFormat("obj.{0} = {1};\n", attributeInitialization.Key, "param" + i); } source.AppendFront("return obj;\n"); source.Unindent(); source.AppendFront("}\n"); }
//Appends data line to the CSV file (if there's one) internal void AppendToCSVFile() { bool csvEnabled = TypesHelper.DoConvert <bool>(GetParamValue("CSV.enabled", "false")); string csvPath = GetParamValue("CSV.path", ""); if (!csvEnabled || string.IsNullOrEmpty(csvPath)) { return; } csvPath = GetAbsolutePath(csvPath); using (StreamWriter swCSV = new StreamWriter(csvPath, true)) //Open file to append data { using (CsvFileWriter csvFW = new CsvFileWriter(swCSV)) { csvFW.WriteRow(GetDataAsList(_data)); } } }
public String BuildParameters(Invocation invocation, SequenceExpression[] ArgumentExpressions, IFunctionDefinition functionMethod, SourceBuilder source) { String parameters = ""; for (int i = 0; i < ArgumentExpressions.Length; i++) { if (ArgumentExpressions[i] != null) { String typeName = TypesHelper.DotNetTypeToXgrsType(functionMethod.Inputs[i]); String cast = "(" + TypesHelper.XgrsTypeToCSharpType(typeName, model) + ")"; parameters += ", " + cast + exprGen.GetSequenceExpression(ArgumentExpressions[i], source); } else { // the sequence parser always emits all argument expressions, for interpreted and compiled throw new Exception("Internal error: missing argument expressions"); } } return(parameters); }
public static void GenerateContainerConstructor(IGraphModel model, SequenceExpressionContainerConstructor containerConstructor, SourceBuilder source) { string containerType = TypesHelper.XgrsTypeToCSharpType(GetContainerType(containerConstructor), model); string valueType = TypesHelper.XgrsTypeToCSharpType(containerConstructor.ValueType, model); string keyType = null; if (containerConstructor is SequenceExpressionMapConstructor) { keyType = TypesHelper.XgrsTypeToCSharpType(((SequenceExpressionMapConstructor)containerConstructor).KeyType, model); } source.Append("\n"); source.AppendFront("public static "); source.Append(containerType); source.Append(" fillFromSequence_" + containerConstructor.Id); source.Append("("); for (int i = 0; i < containerConstructor.ContainerItems.Length; ++i) { if (i > 0) { source.Append(", "); } if (keyType != null) { source.AppendFormat("{0} paramkey{1}, ", keyType, i); } source.AppendFormat("{0} param{1}", valueType, i); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFrontFormat("{0} container = new {0}();\n", containerType); for (int i = 0; i < containerConstructor.ContainerItems.Length; ++i) { source.AppendFrontFormat(GetAddToContainer(containerConstructor, "param" + i, keyType != null ? "paramkey" + i : null)); } source.AppendFront("return container;\n"); source.Unindent(); source.AppendFront("}\n"); }
public bool RunScriptWorkItemUpdated(WorkItemEvent.WorkItemEventUpdated pInputWorkItem, TFSServicesDBLib.Rules pRule) { bool _result = false; try { if (Debug) { DBConnection.AddRunHistory(pRule, "Start run: " + pRule.Title, TypesHelper.Serialize(pInputWorkItem)); } var _scrOpt = GetOptions(); string _srcHeader = @"string ProcessEvent(WorkItemEvent.WorkItemEventUpdated InputWorkItem){"; string _srcEnd = @" } ProcessEvent(InputWorkItem)"; string _src = _srcHeader + pRule.ProcessScript + _srcEnd; _result = CSharpScript.RunAsync <bool>(_src, _scrOpt, new ScriptWiUpdatedHost { InputWorkItem = pInputWorkItem }).Result.ReturnValue; if (Debug) { DBConnection.AddRunHistory(pRule, "End run: " + pRule.Title, TypesHelper.Serialize(pInputWorkItem)); } } catch (Exception ex) { if (Debug) { DBConnection.AddRunHistory(pRule, "Validation exception for : " + pRule.Title, ex.Message + "\n\n" + ex.StackTrace); } _result = false; } return(_result); }
public Link GetLink(string inLink, Node inNode) { string linkType = ""; string linkPattern = "Link Type=\""; int linkTypeIndex = inLink.IndexOf(linkPattern); if (linkTypeIndex > -1) { int linkEndIndex = inLink.IndexOf("\"", linkTypeIndex + linkPattern.Length); int length = linkEndIndex - (linkTypeIndex + linkPattern.Length); linkType = inLink.Substring(linkTypeIndex + linkPattern.Length, length); } else { return(null); } Link link = (Link)Serializer.LinkSerializers[linkType].Deserialize(TypesHelper.StringToStream(inLink)); return(link); }
public NodeConnexions(Node inNode, bool inputs, bool outputs, string excludeType) { _nodeName = inNode.Name; _nodeFullName = inNode.FullName; _nodeNativeName = inNode.NativeName; if (inputs) { foreach (Link inputLink in inNode.InDependencies) { if (linkMatches(inputLink, excludeType) && (!(inNode is Compound) || !inputLink.Source.Owner.IsIn(inNode as Compound))) { MemoryStream stream = new MemoryStream(); Serializer.LinkSerializers[inputLink.NodeElementType].Serialize(stream, inputLink); string linkSerialization = TypesHelper.StringFromStream(stream); stream.Close(); _inputs.PushItemInList(inputLink.Target.Owner.FullName + ":" + inputLink.Target.Name, linkSerialization); } } } if (outputs) { foreach (Link outputLink in inNode.OutDependencies) { if (linkMatches(outputLink, excludeType) && (!(inNode is Compound) || !outputLink.Target.Owner.IsIn(inNode as Compound))) { MemoryStream stream = new MemoryStream(); Serializer.LinkSerializers[outputLink.NodeElementType].Serialize(stream, outputLink); string linkSerialization = TypesHelper.StringFromStream(stream); stream.Close(); _outputs.PushItemInList(outputLink.Target.Owner.FullName + ":" + outputLink.Target.Name, linkSerialization); } } } }
public SequenceMultiRuleAllCallGenerator(SequenceMultiRuleAllCall seqMulti, SequenceRuleCall seqRule, SequenceExpressionGenerator seqExprGen, SequenceGeneratorHelper seqHelper) { this.seqMulti = seqMulti; // parent this.seqRule = seqRule; this.seqExprGen = seqExprGen; this.seqHelper = seqHelper; ArgumentExpressions = seqRule.ArgumentExpressions; specialStr = seqRule.Special ? "true" : "false"; matchingPatternClassName = "GRGEN_ACTIONS." + TypesHelper.GetPackagePrefixDot(seqRule.Package) + "Rule_" + seqRule.Name; patternName = seqRule.Name; plainRuleName = TypesHelper.PackagePrefixedNameDoubleColon(seqRule.Package, seqRule.Name); ruleName = "rule_" + TypesHelper.PackagePrefixedNameUnderscore(seqRule.Package, seqRule.Name); matchType = matchingPatternClassName + "." + NamesOfEntities.MatchInterfaceName(patternName); matchName = "match_" + seqRule.Id; matchesType = "GRGEN_LIBGR.IMatchesExact<" + matchType + ">"; matchesName = "matches_" + seqRule.Id; seqHelper.BuildReturnParameters(seqRule, seqRule.ReturnVars, out returnParameterDeclarations, out returnArguments, out returnAssignments, out returnParameterDeclarationsAllCall, out intermediateReturnAssignmentsAllCall, out returnAssignmentsAllCall); }
/// <summary> /// Locate all value matcher classes and add them to the value matchers list using reflection (or just manually as below) /// </summary> private static Dictionary <string, TAGValueMatcher> InitialiseValueMatchers() { // Get all the value matcher classes that exist in the assembly. These are all classes that // descend from TAGValueMatcher var matchers = TypesHelper.FindAllDerivedTypes <TAGValueMatcher>(); var valueMatchers = new Dictionary <string, TAGValueMatcher>(); // Iterate through those types and create each on in turn, query the TAG types from it that the matcher supports and // then register the value matcher instance against those TAGs to allow the TAG file processor to locate matcher for TAGS foreach (var t in matchers) { var matcher = (TAGValueMatcher)Activator.CreateInstance(t); foreach (string tag in matcher.MatchedValueTypes()) { valueMatchers.Add(tag, matcher); } } return(valueMatchers); }
public void LoadData(int method = 0) { NameValueCollection nvc = null; switch (method) { case 0: nvc = HttpContext.Current.Request.Params; break; case 1: nvc = HttpContext.Current.Request.Form; break; case 2: nvc = HttpContext.Current.Request.QueryString; break; } if (nvc.Count != 0) { var ti = TypesHelper.GetTypeInfo(this.GetType()); //缓存中获取 var li = ti.IgnoreCaseLiteracy; foreach (var key in nvc.AllKeys) { var item = key.ToLower(); if (li.Property.Names.Contains(item)) { string value = nvc[item]; if (!string.IsNullOrEmpty(value)) { li.Property[item].SetValue(this, value); } else { if (li.Property[item].GetType() == typeof(string)) { li.Property[item].SetValue(this, ""); } } } } } }
/// /// <summary>Main for TypesClient</summary> /// <param name="args"></param> /// public static void Main(String[] args) { string uri = "tcp://localhost:4001"; MainTypesListener.Main1(null); MainTypesClient implFactory = new MainTypesClient(); RemoteTypesServer server = TypesHelper.NewServer(uri, null, implFactory); server._TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); Hashtable table = new Hashtable(); table.Add("1", "Entry1"); table.Add("2", "Entry2"); IDictionary map1 = server.test1(table); ArrayList list = new ArrayList(); list.Add("List1"); IList list1 = server.test3(list); DateTime?date = server.test4(DateTime.Now); Hashtable set = new Hashtable(); set.Add("1", null); set.Add("2", null); Hashtable retset = server.test2(set); server._TransportControl(TransportConsts.STOP_AND_WAIT_DOWN, 4000); }
public String BuildParametersInDeclarations(Invocation invocation, SequenceExpression[] ArgumentExpressions, SourceBuilder source, out String declarations) { String parameters = ""; declarations = ""; for (int i = 0; i < ArgumentExpressions.Length; i++) { String typeName; if (actionsTypeInformation.rulesToInputTypes.ContainsKey(invocation.PackagePrefixedName)) { typeName = actionsTypeInformation.rulesToInputTypes[invocation.PackagePrefixedName][i]; } else { typeName = actionsTypeInformation.sequencesToInputTypes[invocation.PackagePrefixedName][i]; } String type = TypesHelper.XgrsTypeToCSharpType(typeName, model); String name = "tmpvar_" + GetUniqueId(); declarations += type + " " + name + " = " + "(" + type + ")" + exprGen.GetSequenceExpression(ArgumentExpressions[i], source) + ";"; parameters += ", " + name; } return(parameters); }
public static IEnumerable <EVEMaterial> GetInventionRequirements(string t2ItemName) { List <EVEMaterial> result = new List <EVEMaterial>(); invType t1type = TypesHelper.GetMeta0Type(t2ItemName); invBlueprintType bpType = TypesHelper.GetBlueprintType(t1type); IEnumerable <ramTypeRequirement> ramReqs = TypesHelper.GetRamTypeRequirements(bpType).Where(x => x.activityID == 8); foreach (ramTypeRequirement r in ramReqs) { invType reqType = TypesHelper.GetType(r.requiredTypeID); EVEMaterial newMat = new EVEMaterial(EVECache.GetItem(reqType), r.quantity.Value, r.damagePerJob.Value, true); if (reqType.groupID == 716) { newMat.damage = 0; } result.Add(newMat); } return(result); }
public static EVEBlueprint GetBlueprint(string productTypeName) { EVEBlueprint blueprint = new EVEBlueprint(); if (productTypeName != null) { blueprint.Product = EVECache.GetItem(productTypeName); } var x = TypesHelper.GetBlueprintType(blueprint.Product.TypeID); blueprint.Blueprint = EVECache.GetItem(x.blueprintTypeID); blueprint.MaxRuns = x.maxProductionLimit.Value; blueprint.BaseInventionTime = x.researchTechTime.Value; blueprint.BaseProductionTime = x.productionTime.Value; blueprint.MaterialEfficiency = -4; blueprint.ProductionEfficiency = -4; blueprint.NumRuns = blueprint.MaxRuns / 10; return(blueprint); }
/// <summary> /// Returns the types to which the operands must be casted to, /// assuming an external type equality or ordering operator. /// Returns "" if the type can only be determined at runtime. /// Returns "-" in case of a type error and/or if no operator working on external types can be applied. /// </summary> private static string BalanceExternalType(string left, string right, IGraphModel model) { if (left == right) { return(left); } if (left == "" || right == "") { return(""); } if (TypesHelper.IsSameOrSubtype(left, right, model) && TypesHelper.IsExternalTypeIncludingObjectType(right, model)) { return(right); } if (TypesHelper.IsSameOrSubtype(right, left, model) && TypesHelper.IsExternalTypeIncludingObjectType(left, model)) { return(left); } return("-"); }
/// <summary> /// Method that sets a property value into model object /// </summary> /// <param name="propertyName">Property name</param> /// <param name="propertyValue">Property value</param> internal void SetPropertyValue( string propertyName, object propertyValue ) { var property = Model.GetType().GetProperties().SingleOrDefault(p => p.Name.ToLower().Equals(propertyName.ToLower())); if (property != null) { Type propertyType = property.PropertyType; if (Nullable.GetUnderlyingType(propertyType) != null) { propertyType = Nullable.GetUnderlyingType(propertyType); } SetConfigProperty(Constants.CONST_SUPPLIED, property.Name); if (propertyValue is JToken) { var newPropertyValue = JsonConvert.DeserializeObject(propertyValue.ToString(), property.PropertyType); property.SetValue(this.Model, newPropertyValue); } else if (propertyValue != null) { bool changed = false; var newPropertyValue = TypesHelper.TryChangeType(propertyValue.ToString(), property.PropertyType, out changed); if (changed) { property.SetValue(this.Model, newPropertyValue); } } else { property.SetValue(this.Model, propertyValue); } } }
/// <summary> /// Method that extends IWrapRequest<T> allowing to get filter properties from request /// </summary> /// <typeparam name="TModel">Generic type of the entity</typeparam> /// <param name="source">Self IWrapRequest<T> instance</param> /// <returns>Returns a dictionary with properties and values found</returns> internal static List <FilterProperty> FilterProperties <TModel>( this IWrapRequest <TModel> source ) where TModel : class { var filterProperties = new List <FilterProperty>(); foreach (var property in typeof(TModel).GetProperties().Where(x => !source.IsPropertySuppressed(x.Name) ).ToList()) { foreach (var criteria in CriteriasHelper.GetPropertyTypeCriteria(property.PropertyType)) { var criteriaName = $"{property.Name.ToCamelCase()}{criteria}"; var listObjects = new List <object>(); foreach (var value in source.AllProperties.Where(x => x.Name.ToLower().Equals(criteriaName.ToLower()) ).Select(x => x.Value).ToList()) { bool changed = false; object typedValue = TypesHelper.TryChangeType(value.ToString(), property.PropertyType, out changed); if (changed) { listObjects.Add(typedValue); } } if (listObjects.Count > 0) { filterProperties.Add(new FilterProperty { Name = criteriaName, Value = listObjects.Count > 1 ? listObjects : listObjects.FirstOrDefault() }); } } } return(filterProperties); }
public ContainerContext(IContainerConfiguration configuration, IClassWrapperCreator classWrapperCreator) { this.Configuration = configuration; ClassWrapperCreator = classWrapperCreator; typesHelper = new TypesHelper(); var funcHelper = new FuncHelper(); FuncBuilder = new FuncBuilder(); var classCreator = new ClassCreator(funcHelper); var constructorSelector = new ConstructorSelector(); CreationContext = new CreationContext(classCreator, constructorSelector, classWrapperCreator); var implementationTypesCollection = new ImplementationTypesCollection(configuration, typesHelper); ImplementationCache = new ImplementationCache(); abstractionsCollection = new AbstractionsCollection(implementationTypesCollection, ImplementationCache); //g ImplementationConfigurationCache = new ImplementationConfigurationCache(); //l var factory = new AutoAbstractionConfigurationFactory(typesHelper, abstractionsCollection, ImplementationConfigurationCache); AbstractionConfigurationCollection = new AbstractionConfigurationCollection(factory); AbstractionConfigurationCollection.Add(typeof(IContainer), new StupidAbstractionConfiguration(new ContainerImplementationConfiguration())); }
private void LblFiltrar_Click(object sender, EventArgs e) { try { #region Validaciones var filtersSetted = false; var exceptionMessage = string.Empty; if (!TypesHelper.IsEmpty(CboAño.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(CboTrimestre.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(CboListado.Text)) { filtersSetted = true; } if ((int)CboListado.SelectedValue == 1 && !TypesHelper.IsEmpty(CboVisibilidad.Text)) { filtersSetted = true; } if (!filtersSetted) { exceptionMessage = "No se puede obtener el listado estadístico. Verifique que haya ingresado los filtros correctamente."; } if (!TypesHelper.IsEmpty(exceptionMessage)) { throw new Exception(exceptionMessage); } #endregion var monthDesde = ""; var dayHasta = ""; var monthHasta = ""; //Si es la primera estadística, puede que esté filtrada por mes, si está en 00, filtro por trimestre if ((string)cboMes.SelectedValue == "00" || (int)CboListado.SelectedValue != 1) { switch ((int)CboTrimestre.SelectedValue) { case 1: monthDesde = "01"; monthHasta = "03"; break; case 2: monthDesde = "04"; monthHasta = "06"; break; case 3: monthDesde = "07"; monthHasta = "09"; break; case 4: monthDesde = "10"; monthHasta = "12"; break; } } else { monthDesde = monthHasta = (string)cboMes.SelectedValue; } switch (monthHasta) { case "01": case "03": case "05": case "07": case "08": case "10": case "12": dayHasta = "31"; break; case "04": case "06": case "09": case "11": dayHasta = "30"; break; case "02": dayHasta = "28"; break; } var fechaDesde = DateTime.Parse("01/" + monthDesde + "/" + CboAño.SelectedValue.ToString()); var fechaHasta = DateTime.Parse(dayHasta + "/" + monthHasta + "/" + CboAño.SelectedValue.ToString()); //Creo los filtros con los que se ejecuta la consulta. var filters = new EstadisticaFilters { FechaDesde = fechaDesde, FechaHasta = fechaHasta, Visibilidad = (!TypesHelper.IsEmpty(CboVisibilidad.Text) && (int)CboVisibilidad.SelectedValue != 0) ? (int)CboVisibilidad.SelectedValue : (int?)null }; var listado = new List <Estadistica>(); switch ((int)CboListado.SelectedValue) { case 1: listado = EstadisticaPersistance.GetSellersWithMoreProductsNotSold(filters); break; case 2: listado = EstadisticaPersistance.GetSellersWithMoreBilling(filters); break; case 3: listado = EstadisticaPersistance.GetSellersWithBetterQualifications(filters); break; case 4: listado = EstadisticaPersistance.GetClientsWithMoreNotQualifiedPublications(filters); break; } if (listado == null || listado.Count == 0) { throw new Exception("No se encontraron estadísticas según los filtros informados."); } LoadGrid(listado); } catch (Exception ex) { MessageBox.Show(ex.Message, "Atención"); ClearDataGridView(); } }
private void CreateControls() { #region Fields Creation foreach (var item in _editableItem.GetType().GetProperties()) { bool standard = false; bool generic = false; bool array = false; //--Standard type if (TypesHelper.IsStandardType(item.PropertyType)) { if (item.PropertyType != typeof(bool)) { Label lb = new Label(); lb.Text = item.Name + ":"; lb.Top = (this.Controls.Count * lb.Height); lb.Left = 2; lb.AutoSize = true; lb.SendToBack(); this.Controls.Add(lb); TextBox tb = new TextBox(); tb.Top = (this.Controls.Count * tb.Height); tb.Left = 2; tb.Name = string.Format("{0}_{1}", item.Name, "TextBox"); this.Controls.Add(tb); _controlsBindings.Add(tb.Name, item.Name); } standard = true; } #region Generic type if (item.PropertyType.IsGenericType) { generic = true; } #endregion #region Array Type if (item.PropertyType.IsArray) { Type eltype = item.PropertyType.GetElementType(); if (TypesHelper.IsStandardType(eltype)) { } if (eltype.IsGenericType) { } array = true; } #endregion #region Class type if (!standard && !generic && !array) { } #endregion } #endregion #region Ok & Cancel Buttons Creation Button but = new Button(); but.Text = "ОК"; but.Top = (this.Controls.Count * but.Height); but.Left = 2; this.Controls.Add(but); but = new Button(); but.Text = "Отмена"; but.Top = this.Controls[this.Controls.Count - 1].Top; but.Left = this.Controls[this.Controls.Count - 1].Width + 6; this.Controls.Add(but); #endregion }
public override void SetUp() { base.SetUp(); helpers = new TypesHelper(); }
public void Run(Options options) { GlobalScope globalScope = new GlobalScope(); Loader ld = new Loader(globalScope, options); ld.Load(options.References); Types.RegisterType("Boolean", (IType)globalScope.GetSymbol("System.Boolean")); Types.RegisterType("Char", (IType)globalScope.GetSymbol("System.Char")); Types.RegisterType("SByte", (IType)globalScope.GetSymbol("System.SByte")); Types.RegisterType("Byte", (IType)globalScope.GetSymbol("System.Byte")); Types.RegisterType("Int16", (IType)globalScope.GetSymbol("System.Int16")); Types.RegisterType("UInt16", (IType)globalScope.GetSymbol("System.UInt16")); Types.RegisterType("Int32", (IType)globalScope.GetSymbol("System.Int32")); Types.RegisterType("UInt32", (IType)globalScope.GetSymbol("System.UInt32")); Types.RegisterType("Int64", (IType)globalScope.GetSymbol("System.Int64")); Types.RegisterType("UInt64", (IType)globalScope.GetSymbol("System.UInt64")); Types.RegisterType("IntPtr", (IType)globalScope.GetSymbol("System.IntPtr")); Types.RegisterType("UIntPtr", (IType)globalScope.GetSymbol("System.UIntPtr")); Types.RegisterType("Single", (IType)globalScope.GetSymbol("System.Single")); Types.RegisterType("Double", (IType)globalScope.GetSymbol("System.Double")); Types.RegisterType("String", (IType)globalScope.GetSymbol("System.String")); Types.RegisterType("Object", (IType)globalScope.GetSymbol("System.Object")); Types.RegisterType("ValueType", (IType)globalScope.GetSymbol("System.ValueType")); Types.RegisterType("Enum", (IType)globalScope.GetSymbol("System.Enum")); Types.RegisterType("Void", (IType)globalScope.GetSymbol("System.Void")); Types.RegisterType("Array", (IType)globalScope.GetSymbol("System.Array")); Types.RegisterType("Exception", (IType)globalScope.GetSymbol("System.Exception")); Types.RegisterType("Type", (IType)globalScope.GetSymbol("System.Type")); Types.RegisterType("MulticastDelegate", (IType)globalScope.GetSymbol("System.MulticastDelegate")); Types.RegisterType("IAsyncResult", (IType)globalScope.GetSymbol("System.IAsyncResult")); Types.RegisterType("AsyncCallback", (IType)globalScope.GetSymbol("System.AsyncCallback")); TypesHelper th = new TypesHelper(); th.Prepare(); Types.ResultTable = th.ResultTable; Types.PromotionTable = th.PromotionTable; int files_number = options.FilesNumber; if (files_number == 0) { Report.Error.NoFilesToCompile(); } List <FileNamespace> file_namespace = new List <FileNamespace>(); List <CompilationUnit> compilation_units = new List <CompilationUnit>(); foreach (string source in options.Files) { try { FileStream file = new FileStream(source, FileMode.Open, FileAccess.Read); ANTLRInputStream input = new ANTLRInputStream(file); GrammarLexer lexer = new GrammarLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); GrammarParser parser = new GrammarParser(tokens); compilation_units.Add(parser.program()); file_namespace.Add(new FileNamespace(globalScope)); } catch (FileNotFoundException) { Report.Error.SourceFileNotFound(source); } catch (DirectoryNotFoundException) { Report.Error.SourceFileNotFound(source); } catch (IOException) { Report.Error.IOError(source); } } CodeGen codegen = new CodeGen(options); for (int i = 0; i < files_number; ++i) { compilation_units[i].DefineSymbols(new Context(file_namespace[i])); } for (int i = 0; i < files_number; ++i) { compilation_units[i].ResolveSymbols(new Context(file_namespace[i])); } codegen.BuildAssembly(compilation_units); }
private static List <SelectedProperty> GetValidProperties <TModel>( IWrapRequest <TModel> source, Type type, List <string> requestProperties, string rootName = null, bool isFromCollection = false) where TModel : class { var properties = new List <SelectedProperty>(); type.GetProperties() .Where(property => !source.IsPropertySuppressedResponse(string.Join(".", TermsHelper.GetTerms(rootName, ".").Union(new List <string> { property.Name }).Where(term => !string.IsNullOrWhiteSpace(term)))) && ( (requestProperties.Count == 0 && IsToLoadComplexPropertyWhenNotRequested(TypesHelper.TypeIsComplex(property.PropertyType), ConfigurationService.GetConfiguration().ByDefaultLoadComplexProperties, string.IsNullOrWhiteSpace(rootName))) || (requestProperties.Any(requested => TermsHelper.GetTerms(requested, ".").FirstOrDefault().ToLower().Equals(property.Name.ToLower()))) ) ) .ToList() .ForEach(property => { if (!TypesHelper.TypeIsComplex(property.PropertyType)) { properties.Add(new SelectedProperty { RequestedPropertyName = string.Join(".", TermsHelper.GetTerms(rootName, ".").Union(new List <string> { property.Name }).Where(term => !string.IsNullOrWhiteSpace(term))), PropertyName = property.Name, RootPropertyName = rootName, PropertyType = property.PropertyType, PropertyInfo = property }); } else if (ConfigurationService.GetConfiguration().ByDefaultLoadComplexProperties) { properties.AddRange( GetValidProperties( source, TypesHelper.TypeIsCollection(property.PropertyType) ? property.PropertyType.GetGenericArguments()[0] : property.PropertyType, requestProperties .Where(requested => TermsHelper.GetTerms(requested, ".").FirstOrDefault().ToLower().Equals(property.Name.ToLower())) .Select(requested => string.Join(".", TermsHelper.GetTerms(requested, ".").Skip(1))) .Where(requested => !string.IsNullOrWhiteSpace(requested)) .ToList(), string.Join(".", TermsHelper.GetTerms(rootName, ".").Union(new List <string> { property.Name }).Where(term => !string.IsNullOrWhiteSpace(term))), TypesHelper.TypeIsCollection(property.PropertyType) ) ); } }); return(properties); }
public string GetEndpointKey(Type type) { string mask = EndpointMask ?? MaskVariable; return(mask.Replace(MaskVariable, TypesHelper.GetFlatClassName(type))); }
private void GenerateInternalDefinedSequenceApplicationMethod(SourceBuilder source, DefinedSequenceInfo sequence, Sequence seq) { source.AppendFront("public static bool ApplyXGRS_" + sequence.Name + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for (int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i]), model) + " var_"); source.Append(sequence.Parameters[i]); } for (int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i]), model) + " var_"); source.Append(sequence.OutParameters[i]); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = procEnv.graph;\n"); source.AppendFront("GRGEN_LGSP.LGSPActions actions = procEnv.curActions;\n"); neededEntitiesEmitter.Reset(); if (fireDebugEvents) { source.AppendFrontFormat("procEnv.DebugEntering(\"{0}\"", sequence.Name); for (int i = 0; i < sequence.Parameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.Parameters[i]); } source.Append(");\n"); } neededEntitiesEmitter.EmitNeededVarAndRuleEntities(seq, source); seqGen.EmitSequence(seq, source); if (fireDebugEvents) { source.AppendFrontFormat("procEnv.DebugExiting(\"{0}\"", sequence.Name); for (int i = 0; i < sequence.OutParameters.Length; ++i) { source.Append(", var_"); source.Append(sequence.OutParameters[i]); } source.Append(");\n"); } source.AppendFront("return " + seqGen.GetSequenceResult(seq) + ";\n"); source.Unindent(); source.AppendFront("}\n"); List <SequenceExpressionContainerConstructor> containerConstructors = new List <SequenceExpressionContainerConstructor>(); Dictionary <SequenceVariable, SetValueType> variables = new Dictionary <SequenceVariable, SetValueType>(); seq.GetLocalVariables(variables, containerConstructors, null); foreach (SequenceExpressionContainerConstructor cc in containerConstructors) { SequenceContainerConstructorEmitter.GenerateContainerConstructor(model, cc, source); } }
public bool GenerateXGRSCode(string xgrsName, String package, String xgrsStr, String[] paramNames, GrGenType[] paramTypes, String[] defToBeYieldedToNames, GrGenType[] defToBeYieldedToTypes, SourceBuilder source, int lineNr) { Dictionary <String, String> varDecls = new Dictionary <String, String>(); for (int i = 0; i < paramNames.Length; ++i) { varDecls.Add(paramNames[i], TypesHelper.DotNetTypeToXgrsType(paramTypes[i])); } for (int i = 0; i < defToBeYieldedToNames.Length; ++i) { varDecls.Add(defToBeYieldedToNames[i], TypesHelper.DotNetTypeToXgrsType(defToBeYieldedToTypes[i])); } Sequence seq; try { SequenceParserEnvironmentCompiled parserEnv = new SequenceParserEnvironmentCompiled(package, actionNames, model); List <string> warnings = new List <string>(); seq = SequenceParser.ParseSequence(xgrsStr, parserEnv, varDecls, warnings); foreach (string warning in warnings) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " reported back:\n" + warning); } seq.Check(env); seq.SetNeedForProfilingRecursive(emitProfiling); } catch (ParseException ex) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " caused the following error:\n" + ex.Message); return(false); } catch (SequenceParserException ex) { Console.Error.WriteLine("The exec statement \"" + xgrsStr + "\" given on line " + lineNr + " caused the following error:\n"); HandleSequenceParserException(ex); return(false); } source.Append("\n"); source.AppendFront("public static bool ApplyXGRS_" + xgrsName + "(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv"); for (int i = 0; i < paramNames.Length; ++i) { source.Append(", " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(paramTypes[i]), model) + " var_"); source.Append(paramNames[i]); } for (int i = 0; i < defToBeYieldedToTypes.Length; ++i) { source.Append(", ref " + TypesHelper.XgrsTypeToCSharpType(TypesHelper.DotNetTypeToXgrsType(defToBeYieldedToTypes[i]), model) + " var_"); source.Append(defToBeYieldedToNames[i]); } source.Append(")\n"); source.AppendFront("{\n"); source.Indent(); source.AppendFront("GRGEN_LGSP.LGSPGraph graph = procEnv.graph;\n"); source.AppendFront("GRGEN_LGSP.LGSPActions actions = procEnv.curActions;\n"); neededEntitiesEmitter.Reset(); if (fireDebugEvents) { source.AppendFrontFormat("procEnv.DebugEntering(\"{0}\", \"{1}\");\n", InjectExec(xgrsName), xgrsStr.Replace("\\", "\\\\").Replace("\"", "\\\"")); } neededEntitiesEmitter.EmitNeededVarAndRuleEntities(seq, source); seqGen.EmitSequence(seq, source); if (fireDebugEvents) { source.AppendFrontFormat("procEnv.DebugExiting(\"{0}\");\n", InjectExec(xgrsName)); } source.AppendFront("return " + seqGen.GetSequenceResult(seq) + ";\n"); source.Unindent(); source.AppendFront("}\n"); List <SequenceExpressionContainerConstructor> containerConstructors = new List <SequenceExpressionContainerConstructor>(); Dictionary <SequenceVariable, SetValueType> variables = new Dictionary <SequenceVariable, SetValueType>(); seq.GetLocalVariables(variables, containerConstructors, null); foreach (SequenceExpressionContainerConstructor cc in containerConstructors) { SequenceContainerConstructorEmitter.GenerateContainerConstructor(model, cc, source); } return(true); }
private void LblBuscar_Click(object sender, EventArgs e) { try { #region Validations var filtersSetted = false; var exceptionMessage = string.Empty; if (!TypesHelper.IsEmpty(txtCodigo.Text)) { filtersSetted = true; if (!TypesHelper.IsNumeric(txtCodigo.Text)) { exceptionMessage += Environment.NewLine + "El código debe ser numérico."; } } if (!TypesHelper.IsEmpty(txtDesc.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(txtPrecio.Text)) { filtersSetted = true; if (!TypesHelper.IsDecimal(txtPrecio.Text)) { exceptionMessage += Environment.NewLine + "El precio de la publicacion ser decimal (o numérico)."; } } if (!TypesHelper.IsEmpty(txtFecha.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(txtCantidad.Text)) { filtersSetted = true; if (!TypesHelper.IsNumeric(txtCantidad.Text)) { exceptionMessage += Environment.NewLine + "La cantidad debe ser numérica."; } } if (!filtersSetted) { exceptionMessage = "No se puede realizar la busqueda ya que no se informó ningún filtro"; } if (!TypesHelper.IsEmpty(exceptionMessage)) { throw new Exception(exceptionMessage); } #endregion var filters = new HistoryCompraFilters { Codigo = (!TypesHelper.IsEmpty(txtCodigo.Text)) ? Convert.ToInt32(txtCodigo.Text) : (int?)null, Descripcion = (!TypesHelper.IsEmpty(txtDesc.Text)) ? txtDesc.Text : null, Precio = (!TypesHelper.IsEmpty(txtPrecio.Text)) ? Convert.ToDouble(txtPrecio.Text) : (double?)null, Fecha = (!TypesHelper.IsEmpty(txtFecha.Text)) ? txtFecha.Text : null, Cantidad = (!TypesHelper.IsEmpty(txtCantidad.Text)) ? Convert.ToInt32(txtCantidad.Text) : (int?)null }; var historyCompras = (cBExact.Checked) ? CompraPersistance.GetAllComprasByParameters(SessionManager.CurrentUser, filters) : CompraPersistance.GetAllComprasByParametersLike(SessionManager.CurrentUser, filters); if (historyCompras == null || historyCompras.Count == 0) { throw new Exception("No se encontraron compras según los filtros informados."); } RefreshSources(historyCompras); } catch (Exception ex) { MessageBox.Show(ex.Message, "Atención"); ClearFiltersAndTable(); } }
private void LblBuscar_Click(object sender, EventArgs e) { try { #region Validations var filtersSetted = false; var exceptionMessage = string.Empty; if (!TypesHelper.IsEmpty(TxtDescripcion.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(TxtStock.Text)) { filtersSetted = true; if (!TypesHelper.IsNumeric(TxtStock.Text)) { exceptionMessage += Environment.NewLine + "El stock de la publicacion debe ser numérico."; } } if (!TypesHelper.IsEmpty(TxtPrecio.Text)) { filtersSetted = true; if (!TypesHelper.IsDecimal(TxtPrecio.Text)) { exceptionMessage += Environment.NewLine + "El precio de la publicacion debe ser decimal (o numérico)."; } } if (!TypesHelper.IsEmpty(CboEstadoPublicacion.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(CboVisibilidad.Text)) { filtersSetted = true; } if (!TypesHelper.IsEmpty(CboTipoPublicacion.Text)) { filtersSetted = true; } if (!filtersSetted) { exceptionMessage = "No se puede realizar la busqueda ya que no se informó ningún filtro"; } if (!TypesHelper.IsEmpty(exceptionMessage)) { throw new Exception(exceptionMessage); } #endregion //Armo el objeto que representa a los filtros var filters = new PublicacionFilters { IdUsuario = SessionManager.CurrentUser.ID, Descripcion = (!TypesHelper.IsEmpty(TxtDescripcion.Text)) ? TxtDescripcion.Text : null, Stock = (!TypesHelper.IsEmpty(TxtStock.Text) && ChkBusquedaExacta.Checked) ? Convert.ToInt32(TxtStock.Text) : (int?)null, Precio = (!TypesHelper.IsEmpty(TxtPrecio.Text) && ChkBusquedaExacta.Checked) ? Convert.ToDouble(TxtPrecio.Text) : (double?)null, IdEstadoPublicacion = (ChkBusquedaExacta.Checked) ? ((EstadoPublicacion)CboEstadoPublicacion.SelectedItem).ID : (int?)null, IdVisibilidad = (ChkBusquedaExacta.Checked) ? ((Visibilidad)CboVisibilidad.SelectedItem).ID : (int?)null, IdTipoPublicacion = (ChkBusquedaExacta.Checked) ? ((TipoPublicacion)CboTipoPublicacion.SelectedItem).ID : (int?)null }; //Obtengo las publicaciones que cumplen con la busqueda var publications = (ChkBusquedaExacta.Checked) ? PublicacionPersistance.GetAllByParameters(filters) : PublicacionPersistance.GetAllByParametersLike(filters); if (publications == null || publications.Count == 0) { throw new Exception("No se encontraron publicaciones según los filtros informados."); } //Cargo el resultado en la grilla RefreshSources(publications); } catch (Exception ex) { MessageBox.Show(ex.Message, "Atención"); } }
public bool GenerateDefinedSequence(SourceBuilder source, DefinedSequenceInfo sequence) { Dictionary <String, String> varDecls = new Dictionary <String, String>(); for (int i = 0; i < sequence.Parameters.Length; i++) { varDecls.Add(sequence.Parameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.ParameterTypes[i])); } for (int i = 0; i < sequence.OutParameters.Length; i++) { varDecls.Add(sequence.OutParameters[i], TypesHelper.DotNetTypeToXgrsType(sequence.OutParameterTypes[i])); } Sequence seq; try { SequenceParserEnvironmentCompiled parserEnv = new SequenceParserEnvironmentCompiled(sequence.Package, actionNames, model); List <string> warnings = new List <string>(); seq = SequenceParser.ParseSequence(sequence.XGRS, parserEnv, varDecls, warnings); foreach (string warning in warnings) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" reported back:\n" + warning); } seq.Check(env); seq.SetNeedForProfilingRecursive(emitProfiling); } catch (ParseException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n" + ex.Message); return(false); } catch (SequenceParserException ex) { Console.Error.WriteLine("In the defined sequence " + sequence.Name + " the exec part \"" + sequence.XGRS + "\" caused the following error:\n"); HandleSequenceParserException(ex); return(false); } // exact sequence definition compiled class source.Append("\n"); if (sequence.Package != null) { source.AppendFrontFormat("namespace {0}\n", sequence.Package); source.AppendFront("{\n"); source.Indent(); } source.AppendFront("public class Sequence_" + sequence.Name + " : GRGEN_LIBGR.SequenceDefinitionCompiled\n"); source.AppendFront("{\n"); source.Indent(); GenerateSequenceDefinedSingleton(source, sequence); source.Append("\n"); GenerateGenericMethodReturnValues(source, sequence); source.Append("\n"); GenerateInternalDefinedSequenceApplicationMethod(source, sequence, seq); source.Append("\n"); GenerateExactExternalDefinedSequenceApplicationMethod(source, sequence); source.Append("\n"); GenerateGenericExternalDefinedSequenceApplicationMethod(source, sequence); // end of exact sequence definition compiled class source.Unindent(); source.AppendFront("}\n"); if (sequence.Package != null) { source.Unindent(); source.AppendFront("}\n"); } return(true); }