private static void HideEmptySuper(ClassWrapper wrapper) { foreach (MethodWrapper method in wrapper.GetMethods()) { if (ICodeConstants.Init_Name.Equals(method.methodStruct.GetName()) && method.root != null) { Statement firstData = Statements.FindFirstData(method.root); if (firstData == null || (firstData.GetExprents().Count == 0)) { return; } Exprent exprent = firstData.GetExprents()[0]; if (exprent.type == Exprent.Exprent_Invocation) { InvocationExprent invExpr = (InvocationExprent)exprent; if (Statements.IsInvocationInitConstructor(invExpr, method, wrapper, false) && (invExpr .GetLstParameters().Count == 0)) { firstData.GetExprents().RemoveAtReturningValue(0); } } } } }
public static string UseClassWrapper(this string code, ISwaggerInterfaceBuilderContext context) { var wrapper = new ClassWrapper(code, context.Settings.CSharpGeneratorSettings.Namespace, context.Root.GetUsingDirectives()); return(wrapper.Get()); }
public static List <VarVersionPair> GetSyntheticParametersMask(ClassesProcessor.ClassNode node, string descriptor, int parameters) { List <VarVersionPair> mask = null; ClassWrapper wrapper = node.GetWrapper(); if (wrapper != null) { // own class MethodWrapper methodWrapper = wrapper.GetMethodWrapper(ICodeConstants.Init_Name, descriptor); if (methodWrapper == null) { if (DecompilerContext.GetOption(IFernflowerPreferences.Ignore_Invalid_Bytecode)) { return(null); } throw new Exception("Constructor " + node.classStruct.qualifiedName + "." + ICodeConstants .Init_Name + descriptor + " not found"); } mask = methodWrapper.synthParameters; } else if (parameters > 0 && node.type == ClassesProcessor.ClassNode.Class_Member && (node.access & ICodeConstants.Acc_Static) == 0) { // non-static member class mask = new List <VarVersionPair>(Enumerable.Repeat <VarVersionPair>(null, parameters)); mask[0] = new VarVersionPair(-1, 0); } return(mask); }
public override string CreateUpdate(ChangedObject obj) { ClassWrapper currentClassWrapper = wrappingHandler.GetClassWrapper(obj.RuntimeObject.GetType()); string result = "UPDATE "; result += currentClassWrapper.Name; result += " SET "; string delimiter = ""; foreach (var elm in obj.GetChangedFields()) { PropertyWrapper currentFieldWrapper = currentClassWrapper.GetFieldWrapper(elm.Key); result += delimiter + currentFieldWrapper.Name; result += " = "; // result += normalizeValueForInsertStatement(currentFieldWrapper.getOriginalField().getType(), elm.getValue()); result += fieldTypeParser.NormalizeValueForInsertStatement(elm.Value); if (delimiter == "") { delimiter = " , "; } } result += " WHERE "; result += currentClassWrapper.GetPrimaryKeyMember().Name + " = "; result += "'" + obj.RuntimeObject.ID + "'"; return(result); }
private static bool CollapseInlinedClass14(Statement stat) { bool ret = class14Builder.Match(stat); if (ret) { string class_name = (string)class14Builder.GetVariableValue("$classname$"); AssignmentExprent assignment = (AssignmentExprent)class14Builder.GetVariableValue ("$assignfield$"); FieldExprent fieldExpr = (FieldExprent)class14Builder.GetVariableValue("$field$"); assignment.ReplaceExprent(assignment.GetRight(), new ConstExprent(VarType.Vartype_Class , class_name, null)); List <Exprent> data = new List <Exprent>(stat.GetFirst().GetExprents()); stat.SetExprents(data); SequenceHelper.DestroyAndFlattenStatement(stat); ClassWrapper wrapper = (ClassWrapper)DecompilerContext.GetProperty(DecompilerContext .Current_Class_Wrapper); if (wrapper != null) { wrapper.GetHiddenMembers().Add(InterpreterUtil.MakeUniqueKey(fieldExpr.GetName(), fieldExpr.GetDescriptor().descriptorString)); } } return(ret); }
public override DataRow GetObject(ClassWrapper type, Guid id) { string statement = statementBuilder.CreateSelect(type, new WhereClause(type.GetPrimaryKeyMember().Name, id, ComparisonOperator.Equal)); DataTable table = new DataTable(); try { var command = _connection.CreateCommand(); command.CommandText = statement; table.Load(command.ExecuteReader()); } catch { throw; } if (table.Rows.Count > 0) { return(table.Rows[0]); } else { return(null); } }
/// <summary> /// Fills the references of a <see cref="PersistentObject"/> /// </summary> /// <param name="pObject"><see cref="PersistentObject"/> to fill references</param> private void FillReferences(ClassWrapper classWrapper, DataRow row, PersistentObject pObject) { foreach (PropertyWrapper fw in classWrapper.GetRelationWrapper()) { if (fw.IsList) { continue; } string oid = row[fw.Name] as string; if (oid != null && !oid.Equals("")) { Guid uuidToCompare = new Guid(oid); AssociationWrapper asW = fw.GetForeignKey(); ClassWrapper cw = asW.AssociationPartnerClass; Type cl = cw.ClassToWrap; // check if refObj is already loaded PersistentObject refObj = ObjectCache.GetTemp(cl).FirstOrDefault(x => x.ID.Equals(uuidToCompare)); if (refObj == null) { refObj = GetObject(cl, uuidToCompare, true); } pObject.SetRelation(fw.OriginalField.Name, refObj); } } }
public static void BuildAssertions(ClassesProcessor.ClassNode node) { ClassWrapper wrapper = node.GetWrapper(); StructField field = FindAssertionField(node); if (field != null) { string key = InterpreterUtil.MakeUniqueKey(field.GetName(), field.GetDescriptor() ); bool res = false; foreach (MethodWrapper meth in wrapper.GetMethods()) { RootStatement root = meth.root; if (root != null) { res |= ReplaceAssertions(root, wrapper.GetClassStruct().qualifiedName, key); } } if (res) { // hide the helper field wrapper.GetHiddenMembers().Add(key); } } }
private static bool ReplaceInvocations(Exprent exprent, ClassWrapper wrapper, MethodWrapper meth) { bool res = false; while (true) { bool found = false; foreach (Exprent expr in exprent.GetAllExprents()) { string cl = IsClass14Invocation(expr, wrapper, meth); if (cl != null) { exprent.ReplaceExprent(expr, new ConstExprent(VarType.Vartype_Class, cl.Replace('.' , '/'), expr.bytecode)); found = true; res = true; break; } res |= ReplaceInvocations(expr, wrapper, meth); } if (!found) { break; } } return(res); }
private static string IsClass14Invocation(Exprent exprent, ClassWrapper wrapper, MethodWrapper meth) { if (exprent.type == Exprent.Exprent_Function) { FunctionExprent fexpr = (FunctionExprent)exprent; if (fexpr.GetFuncType() == FunctionExprent.Function_Iif) { if (fexpr.GetLstOperands()[0].type == Exprent.Exprent_Function) { FunctionExprent headexpr = (FunctionExprent)fexpr.GetLstOperands()[0]; if (headexpr.GetFuncType() == FunctionExprent.Function_Eq) { if (headexpr.GetLstOperands()[0].type == Exprent.Exprent_Field && headexpr.GetLstOperands ()[1].type == Exprent.Exprent_Const && ((ConstExprent)headexpr.GetLstOperands()[ 1]).GetConstType().Equals(VarType.Vartype_Null)) { FieldExprent field = (FieldExprent)headexpr.GetLstOperands()[0]; ClassesProcessor.ClassNode fieldnode = DecompilerContext.GetClassProcessor().GetMapRootClasses ().GetOrNull(field.GetClassname()); if (fieldnode != null && fieldnode.classStruct.qualifiedName.Equals(wrapper.GetClassStruct ().qualifiedName)) { // source class StructField fd = wrapper.GetClassStruct().GetField(field.GetName(), field.GetDescriptor ().descriptorString); // FIXME: can be null! why?? if (fd != null && fd.HasModifier(ICodeConstants.Acc_Static) && (fd.IsSynthetic() || DecompilerContext.GetOption(IFernflowerPreferences.Synthetic_Not_Set))) { if (fexpr.GetLstOperands()[1].type == Exprent.Exprent_Assignment && fexpr.GetLstOperands ()[2].Equals(field)) { AssignmentExprent asexpr = (AssignmentExprent)fexpr.GetLstOperands()[1]; if (asexpr.GetLeft().Equals(field) && asexpr.GetRight().type == Exprent.Exprent_Invocation) { InvocationExprent invexpr = (InvocationExprent)asexpr.GetRight(); if (invexpr.GetClassname().Equals(wrapper.GetClassStruct().qualifiedName) && invexpr .GetName().Equals(meth.methodStruct.GetName()) && invexpr.GetStringDescriptor(). Equals(meth.methodStruct.GetDescriptor())) { if (invexpr.GetLstParameters()[0].type == Exprent.Exprent_Const) { wrapper.GetHiddenMembers().Add(InterpreterUtil.MakeUniqueKey(fd.GetName(), fd.GetDescriptor ())); // hide synthetic field return(((ConstExprent)invexpr.GetLstParameters()[0]).GetValue().ToString()); } } } } } } } } } } } return(null); }
private static StructField FindAssertionField(ClassesProcessor.ClassNode node) { ClassWrapper wrapper = node.GetWrapper(); bool noSynthFlag = DecompilerContext.GetOption(IFernflowerPreferences.Synthetic_Not_Set ); foreach (StructField fd in wrapper.GetClassStruct().GetFields()) { string keyField = InterpreterUtil.MakeUniqueKey(fd.GetName(), fd.GetDescriptor()); // initializer exists if (wrapper.GetStaticFieldInitializers().ContainsKey(keyField)) { // access flags set if (fd.HasModifier(ICodeConstants.Acc_Static) && fd.HasModifier(ICodeConstants.Acc_Final ) && (noSynthFlag || fd.IsSynthetic())) { // field type boolean FieldDescriptor fdescr = FieldDescriptor.ParseDescriptor(fd.GetDescriptor()); if (VarType.Vartype_Boolean.Equals(fdescr.type)) { Exprent initializer = wrapper.GetStaticFieldInitializers().GetWithKey(keyField); if (initializer.type == Exprent.Exprent_Function) { FunctionExprent fexpr = (FunctionExprent)initializer; if (fexpr.GetFuncType() == FunctionExprent.Function_Bool_Not && fexpr.GetLstOperands ()[0].type == Exprent.Exprent_Invocation) { InvocationExprent invexpr = (InvocationExprent)fexpr.GetLstOperands()[0]; if (invexpr.GetInstance() != null && invexpr.GetInstance().type == Exprent.Exprent_Const && "desiredAssertionStatus".Equals(invexpr.GetName()) && "java/lang/Class".Equals (invexpr.GetClassname()) && (invexpr.GetLstParameters().Count == 0)) { ConstExprent cexpr = (ConstExprent)invexpr.GetInstance(); if (VarType.Vartype_Class.Equals(cexpr.GetConstType())) { ClassesProcessor.ClassNode nd = node; while (nd != null) { if (nd.GetWrapper().GetClassStruct().qualifiedName.Equals(cexpr.GetValue())) { break; } nd = nd.parent; } if (nd != null) { // found enclosing class with the same name return(fd); } } } } } } } } } return(null); }
public override async Task FinalizeGeneration(ProtocolGeneration proto) { await base.FinalizeGeneration(proto); if (proto.Protocol.Namespace != "Bethesda") { return; } FileGeneration fg = new FileGeneration(); fg.AppendLine("using System;"); fg.AppendLine(); using (new NamespaceWrapper(fg, "Mutagen.Bethesda")) { using (var cl = new ClassWrapper(fg, "GameCategoryHelper")) { cl.Partial = true; cl.Static = true; } using (new BraceWrapper(fg)) { using (var args = new FunctionWrapper(fg, $"public static {nameof(GameCategory)} FromModType<TMod>")) { args.Wheres.Add($"where TMod : {nameof(IModGetter)}"); } using (new BraceWrapper(fg)) { fg.AppendLine("switch (typeof(TMod).Name)"); using (new BraceWrapper(fg)) { foreach (var cat in EnumExt.GetValues <GameCategory>()) { fg.AppendLine($"case \"I{cat}Mod\":"); fg.AppendLine($"case \"I{cat}ModGetter\":"); using (new DepthWrapper(fg)) { fg.AppendLine($"return {nameof(GameCategory)}.{cat};"); } } fg.AppendLine("default:"); using (new BraceWrapper(fg)) { fg.AppendLine("throw new ArgumentException($\"Unknown game type for: {typeof(TMod).Name}\");"); } } } } } var path = Path.Combine(proto.DefFileLocation.FullName, "../Extensions", $"GameCategoryHelper{Loqui.Generation.Constants.AutogeneratedMarkerString}.cs"); fg.Generate(path); proto.GeneratedFiles.Add(path, ProjItemType.Compile); }
public void StringTest() { const string name = "Cody"; ClassWrapper <string> wrapper = new ClassWrapper <string>(name); Assert.AreEqual(wrapper.Instance, name); Assert.IsTrue(wrapper.isEqualUsingMethod(name)); Assert.IsTrue(wrapper.isEqualUsingOperator(name)); }
private static void ProcessClassRec(ClassesProcessor.ClassNode node, IDictionary <ClassWrapper, MethodWrapper> mapClassMeths, HashSet <ClassWrapper> setFound) { ClassWrapper wrapper = node.GetWrapper(); // search code foreach (MethodWrapper meth in wrapper.GetMethods()) { RootStatement root = meth.root; if (root != null) { DirectGraph graph = meth.GetOrBuildGraph(); graph.IterateExprents((Exprent exprent) => { foreach (KeyValuePair <ClassWrapper, MethodWrapper> ent in mapClassMeths) { if (ReplaceInvocations(exprent, ent.Key, ent.Value)) { setFound.Add(ent.Key); } } return(0); } ); } } // search initializers for (int j = 0; j < 2; j++) { VBStyleCollection <Exprent, string> initializers = j == 0 ? wrapper.GetStaticFieldInitializers () : wrapper.GetDynamicFieldInitializers(); for (int i = 0; i < initializers.Count; i++) { foreach (KeyValuePair <ClassWrapper, MethodWrapper> ent in mapClassMeths) { Exprent exprent = initializers[i]; if (ReplaceInvocations(exprent, ent.Key, ent.Value)) { setFound.Add(ent.Key); } string cl = IsClass14Invocation(exprent, ent.Key, ent.Value); if (cl != null) { initializers[i] = new ConstExprent(VarType.Vartype_Class, cl.Replace('.', '/'), exprent .bytecode); setFound.Add(ent.Key); } } } } // iterate nested classes foreach (ClassesProcessor.ClassNode nd in node.nested) { ProcessClassRec(nd, mapClassMeths, setFound); } }
public static void ClearEnum(ClassWrapper wrapper) { StructClass cl = wrapper.GetClassStruct(); // hide values/valueOf methods and super() invocations foreach (MethodWrapper method in wrapper.GetMethods()) { StructMethod mt = method.methodStruct; string name = mt.GetName(); string descriptor = mt.GetDescriptor(); if ("values".Equals(name)) { if (descriptor.Equals("()[L" + cl.qualifiedName + ";")) { wrapper.GetHiddenMembers().Add(InterpreterUtil.MakeUniqueKey(name, descriptor)); } } else if ("valueOf".Equals(name)) { if (descriptor.Equals("(Ljava/lang/String;)L" + cl.qualifiedName + ";")) { wrapper.GetHiddenMembers().Add(InterpreterUtil.MakeUniqueKey(name, descriptor)); } } else if (ICodeConstants.Init_Name.Equals(name)) { Statement firstData = Statements.FindFirstData(method.root); if (firstData != null && !(firstData.GetExprents().Count == 0)) { Exprent exprent = firstData.GetExprents()[0]; if (exprent.type == Exprent.Exprent_Invocation) { InvocationExprent invExpr = (InvocationExprent)exprent; if (Statements.IsInvocationInitConstructor(invExpr, method, wrapper, false)) { firstData.GetExprents().RemoveAtReturningValue(0); } } } } } // hide synthetic fields of enum and it's constants foreach (StructField fd in cl.GetFields()) { string descriptor = fd.GetDescriptor(); if (fd.IsSynthetic() && descriptor.Equals("[L" + cl.qualifiedName + ";")) { wrapper.GetHiddenMembers().Add(InterpreterUtil.MakeUniqueKey(fd.GetName(), descriptor )); } } }
private static void LiftConstructor(ClassWrapper wrapper) { foreach (MethodWrapper method in wrapper.GetMethods()) { if (ICodeConstants.Init_Name.Equals(method.methodStruct.GetName()) && method.root != null) { Statement firstData = Statements.FindFirstData(method.root); if (firstData == null) { return; } int index = 0; List <Exprent> lstExprents = firstData.GetExprents(); foreach (Exprent exprent in lstExprents) { int action = 0; if (exprent.type == Exprent.Exprent_Assignment) { AssignmentExprent assignExpr = (AssignmentExprent)exprent; if (assignExpr.GetLeft().type == Exprent.Exprent_Field && assignExpr.GetRight().type == Exprent.Exprent_Var) { FieldExprent fExpr = (FieldExprent)assignExpr.GetLeft(); if (fExpr.GetClassname().Equals(wrapper.GetClassStruct().qualifiedName)) { StructField structField = wrapper.GetClassStruct().GetField(fExpr.GetName(), fExpr .GetDescriptor().descriptorString); if (structField != null && structField.HasModifier(ICodeConstants.Acc_Final)) { action = 1; } } } } else if (index > 0 && exprent.type == Exprent.Exprent_Invocation && Statements.IsInvocationInitConstructor ((InvocationExprent)exprent, method, wrapper, true)) { // this() or super() lstExprents.Add(0, lstExprents.RemoveAtReturningValue(index)); action = 2; } if (action != 1) { break; } index++; } } } }
public virtual Response PostRequiredClassProperty(ClassWrapper bodyParameter, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExplicitClient.PostRequiredClassProperty"); scope.Start(); try { return(RestClient.PostRequiredClassProperty(bodyParameter, cancellationToken)); } catch (Exception e) { scope.Failed(e); throw; } }
public virtual async Task <Response> PostRequiredClassPropertyAsync(ClassWrapper bodyParameter, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("ExplicitClient.PostRequiredClassProperty"); scope.Start(); try { return(await RestClient.PostRequiredClassPropertyAsync(bodyParameter, cancellationToken).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
private void RefreshType(ClassWrapper classWrapper) { DataTable table = connection.GetTable(classWrapper); foreach (DataRow row in table.Rows) { Guid elementUUID = new Guid((string)row[PersistentObject.KeyPropertyName]); // only load if not already loaded //if (objectCache.getTemp(classWrapper.getClassToWrap()).stream().noneMatch(x->x.getID().equals(elementUUID))) if (!ObjectCache.GetTemp(classWrapper.ClassToWrap).Any(x => x.ID.Equals(elementUUID))) { LoadObject(classWrapper, row); } } }
private static void InitWrappers(ClassesProcessor.ClassNode node) { if (node.type == ClassesProcessor.ClassNode.Class_Lambda) { return; } ClassWrapper wrapper = new ClassWrapper(node.classStruct); wrapper.Init(); node.wrapper = wrapper; foreach (ClassesProcessor.ClassNode nd in node.nested) { InitWrappers(nd); } }
private PersistentObject CreateValueObject(ClassWrapper classWrapper, DataRow row) { PersistentObject pObject; pObject = (PersistentObject)Activator.CreateInstance(classWrapper.ClassToWrap, this); // set Object fields foreach (PropertyWrapper fw in classWrapper.GetWrappedValueMemberWrapper()) { object value = row[fw.Name]; pObject.SetMemberValue(fw.OriginalField.Name, FieldTypeParser.CastValue(fw.OriginalField.PropertyType, value)); } return(pObject); }
public void BookTest() { Book book = new Book { Title = "Walden Two" }; ClassWrapper <Book> wrapper = new ClassWrapper <Book>(book); Assert.AreEqual(wrapper.Instance, book); Book anotherBook = new Book { Title = "Walden Two" }; Assert.AreNotEqual(wrapper.Instance, anotherBook); }
private PersistentObject LoadObject(ClassWrapper classWrapper, DataRow row) { IsLoadingObjects = true; PersistentObject pObject; pObject = CreateValueObject(classWrapper, row); ObjectCache.AddTemp(pObject); FillReferences(classWrapper, row, pObject); IsLoadingObjects = false; return(pObject); }
/// <summary> /// Loads all objects of a type (always loads from DB) /// </summary> /// <typeparam name="T">Type to load</typeparam> /// <param name="clause">the clause to apply while loading from DB</param> /// <returns>a list of <see cref="PersistentObject"/>s</returns> public List <T> GetObjects <T>(WhereClause clause) where T : PersistentObject { ClassWrapper classWrapper = WrappingHandler.GetClassWrapper(typeof(T)); List <T> objectsToReturn = new List <T>(); DataTable table = connection.GetTable(classWrapper, clause); foreach (DataRow row in table.Rows) { objectsToReturn.Add((T)LoadObject(classWrapper, row)); } ObjectCache.ApplyLoadedObjectsToCache(); return(objectsToReturn); }
public void GenerateModGameCategoryRegistration(ObjectGeneration obj, FileGeneration fg) { using (var ns = new NamespaceWrapper(fg, $"Mutagen.Bethesda.{obj.GetObjectData().GameCategory}.Internals", fileScoped: false)) { using (var c = new ClassWrapper(fg, $"{obj.Name}_Registration")) { c.Partial = true; c.Interfaces.Add(nameof(IModRegistration)); } using (new BraceWrapper(fg)) { fg.AppendLine($"public {nameof(GameCategory)} GameCategory => {nameof(GameCategory)}.{obj.GetObjectData().GameCategory};"); } fg.AppendLine(); } }
private static void ExtractStaticInitializers(ClassWrapper wrapper, MethodWrapper method) { RootStatement root = method.root; StructClass cl = wrapper.GetClassStruct(); Statement firstData = Statements.FindFirstData(root); if (firstData != null) { bool inlineInitializers = cl.HasModifier(ICodeConstants.Acc_Interface) || cl.HasModifier (ICodeConstants.Acc_Enum); while (!(firstData.GetExprents().Count == 0)) { Exprent exprent = firstData.GetExprents()[0]; bool found = false; if (exprent.type == Exprent.Exprent_Assignment) { AssignmentExprent assignExpr = (AssignmentExprent)exprent; if (assignExpr.GetLeft().type == Exprent.Exprent_Field) { FieldExprent fExpr = (FieldExprent)assignExpr.GetLeft(); if (fExpr.IsStatic() && fExpr.GetClassname().Equals(cl.qualifiedName) && cl.HasField (fExpr.GetName(), fExpr.GetDescriptor().descriptorString)) { // interfaces fields should always be initialized inline if (inlineInitializers || IsExprentIndependent(assignExpr.GetRight(), method)) { string keyField = InterpreterUtil.MakeUniqueKey(fExpr.GetName(), fExpr.GetDescriptor ().descriptorString); if (!wrapper.GetStaticFieldInitializers().ContainsKey(keyField)) { wrapper.GetStaticFieldInitializers().AddWithKey(assignExpr.GetRight(), keyField); firstData.GetExprents().RemoveAtReturningValue(0); found = true; } } } } } if (!found) { break; } } } }
public override async Task FinalizeGeneration(ProtocolGeneration proto) { await base.FinalizeGeneration(proto); if (proto.Protocol.Namespace != "All") { return; } await Task.WhenAll(proto.Gen.Protocols.Values.SelectMany(p => p.ObjectGenerationsByID.Values.Select(o => o.LoadingCompleteTask.Task))); FileGeneration fg = new FileGeneration(); foreach (var modObj in mods) { fg.AppendLine($"using Mutagen.Bethesda.{modObj.ProtoGen.Protocol.Namespace};"); } fg.AppendLine($"using Mutagen.Bethesda.Environments;"); fg.AppendLine($"using Mutagen.Bethesda.Plugins.Cache;"); fg.AppendLine(); using (new NamespaceWrapper(fg, "Mutagen.Bethesda", fileScoped: false)) { using (var c = new ClassWrapper(fg, "GameEnvironmentMixIn")) { c.Static = true; } using (new BraceWrapper(fg)) { foreach (var modObj in mods) { var relStr = modObj.GetObjectData().HasMultipleReleases ? $"{modObj.GetObjectData().GameCategory}Release gameRelease" : string.Empty; var retType = $"IGameEnvironmentState<I{modObj.Name}, I{modObj.Name}Getter>"; using (var args = new FunctionWrapper(fg, $"public static {retType} {modObj.ProtoGen.Protocol.Namespace}")) { args.Add($"this {nameof(GameEnvironment)} env"); if (modObj.GetObjectData().HasMultipleReleases) { args.Add(modObj.GetObjectData().HasMultipleReleases ? $"{modObj.GetObjectData().GameCategory}Release gameRelease" : string.Empty); } args.Add($"{nameof(LinkCachePreferences)}? linkCachePrefs = null"); } using (new BraceWrapper(fg)) { fg.AppendLine($"return env.Construct<I{modObj.Name}, I{modObj.Name}Getter>({(modObj.GetObjectData().HasMultipleReleases ? "gameRelease.ToGameRelease()" : $"GameRelease.{modObj.ProtoGen.Protocol.Namespace}")}, linkCachePrefs);");
public static bool IsInvocationInitConstructor(InvocationExprent inv, MethodWrapper method, ClassWrapper wrapper, bool withThis) { if (inv.GetFunctype() == InvocationExprent.Typ_Init && inv.GetInstance().type == Exprent.Exprent_Var) { VarExprent instVar = (VarExprent)inv.GetInstance(); VarVersionPair varPair = new VarVersionPair(instVar); string className = method.varproc.GetThisVars().GetOrNull(varPair); if (className != null) { // any this instance. TODO: Restrict to current class? return(withThis || !wrapper.GetClassStruct().qualifiedName.Equals(inv.GetClassname ())); } } return(false); }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No arguments were passed."); Console.WriteLine("Please pass the path to the file or a directory"); return; } String path = args[0]; String htmlCode = "<!DOCTYPE html>\r\n<html>\r\n\r\n<head>\r\n\r\n <!-- BOOTSTRAP 3 -->\r\n <link rel=\"stylesheet\" media=\"screen\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css\">\r\n\r\n <!-- OUR CSS -->\r\n <link rel=\"stylesheet\" href=\"css/styles.css\">\r\n <link rel=\"stylesheet\" href=\"css/responsive.css\">\r\n <link rel=\"stylesheet\" href=\"css/custom.css\">\r\n\r\n <title>Class Details</title>\r\n</head>\r\n\r\n<body>\r\n\r\n <!--**************************************************************************************************\r\n HEADER\r\n **************************************************************************************************-->\r\n <nav class=\"navbar navbar-default\" role=\"navigation\">\r\n <div class=\"navbar-header\">\r\n <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-ex1-collapse\">\r\n\t\t\t<span class=\"sr-only\">Toggle navigation</span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t\t<span class=\"icon-bar\"></span>\r\n\t\t</button>\r\n </div>\r\n\r\n <div class=\"collapse navbar-collapse navbar-ex1-collapse\">\r\n <ul class=\"nav navbar-nav\">\r\n <li><a href=\"#\">Overview</a></li>\r\n <li><a href=\"#\">Structures</a></li>\r\n <li><a href=\"#\">Classes</a></li>\r\n <li><a href=\"#\">Files</a></li>\r\n <li><a href=\"#\">Tree</a></li>\r\n </ul>\r\n </div>\r\n <!-- /.navbar-collapse -->\r\n </nav>\r\n \r\n <!-- MAIN CONTAINER -->\r\n <div class=\"container main-container\">"; htmlCode += ClassWebPage.generateClassName("LinkedList"); ClassWrapper[] classWrappers = new ClassWrapper[5]; for (var i = 0; i < 5; i++) { classWrappers[i] = new ClassWrapper("LinkedList", "", null, null); } htmlCode += ClassWebPage.generateImplementedClasses(classWrappers); ParameterWrapper[] parameters = new ParameterWrapper[2]; for (var i = 0; i < parameters.Length; i++) { parameters[i] = new ParameterWrapper("start", "struct Node*"); } htmlCode += ClassWebPage.generateFields(parameters); ConstructorWrapper[] constructors = new ConstructorWrapper[2]; constructors[0] = new ConstructorWrapper("LinkedList", "", "", new ParameterWrapper[0]); constructors[1] = new ConstructorWrapper("LinkedList", "", "", parameters); htmlCode += ClassWebPage.generateConstructors(constructors); MethodWrapper[] methods = new MethodWrapper[10]; for (var i = 0; i < methods.Length; i++) { methods[i] = new MethodWrapper("traverse", "Traverses the given LinkedList", "", parameters, "void"); } htmlCode += ClassWebPage.generateMethods(methods); htmlCode += "</div><!--.main-container-->\r\n\r\n\r\n\r\n <!-- JQUERY SCRIPT -->\r\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\r\n <!-- BOOTSTRAP SCRIPT -->\r\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js\"></script>\r\n <!-- OUR SCRIPT -->\r\n <script src=\"js/script.js\"></script>\r\n</body>\r\n\r\n</html>\r\n"; File.WriteAllText("/Users/gauravpunjabi/Desktop/index.html", htmlCode); }
public override DataTable GetTable(ClassWrapper type, WhereClause clause = null) { string result = statementBuilder.CreateSelect(type, clause); DataTable table = new DataTable(); try { var command = _connection.CreateCommand(); command.CommandText = result; table.Load(command.ExecuteReader()); } catch { throw; } return(table); }
/// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredClassProperty(this IExplicitModel operations, ClassWrapper bodyParameter) { return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassPropertyAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); }
/// <summary> /// Main executor function. /// </summary> /// <returns>A CodeCompileUnit.</returns> public CodeCompileUnit Execute() { var codeCompileUnit = new CodeCompileUnit(); // Set namespace var nsWrap = new NamespaceWrapper(new CodeNamespace(_codeNamespace)); // Set class var codeClass = new CodeTypeDeclaration(_schemaDocument.Title) {Attributes = MemberAttributes.Public}; var clWrap = new ClassWrapper(codeClass); // Add imports for interfaces and dependencies nsWrap.AddImportsFromWrapper(_schemaWrapper); // Add comments and attributes for class if (!String.IsNullOrEmpty(_schemaDocument.Description)) { clWrap.AddComment(_schemaDocument.Description); } // Add extended class if (_schemaDocument.Extends != null && _schemaDocument.Extends.Count > 0) { clWrap.AddInterface(JsonSchemaUtils.GetType(_schemaDocument.Extends[0], _codeNamespace).Name); } // Add interfaces foreach (Type t in _schemaWrapper.Interfaces) { clWrap.AddInterface(t.Name); } // Add properties with getters/setters if (_schemaDocument.Properties != null) { foreach (var i in _schemaDocument.Properties) { JsonSchema schema = i.Value; // Sanitize inputs if (!String.IsNullOrEmpty(schema.Description)) { schema.Description = Regex.Unescape(schema.Description); } // If it is an enum var propertyName = i.Key.Capitalize(); if (schema.Enum != null) { var enumField = new CodeTypeDeclaration(propertyName); var enumWrap = new EnumWrapper(enumField); // Add comment if not null if (!String.IsNullOrEmpty(schema.Description)) { enumField.Comments.Add(new CodeCommentStatement(schema.Description)); } foreach (JToken j in schema.Enum) { enumWrap.AddMember(j.ToString().SanitizeIdentifier()); } // Add to namespace nsWrap.AddClass(enumWrap.Property); } else { // WARNING: This assumes the namespace of the property is the same as the parent. // This should not be a problem since imports are handled for all dependencies at the beginning. Type type = JsonSchemaUtils.GetType(schema, _codeNamespace); bool isCustomType = type.Namespace != null && type.Namespace.Equals(_codeNamespace); string strType = String.Empty; // Add imports nsWrap.AddImport(type.Namespace); nsWrap.AddImportsFromSchema(schema); // Get the property type if (isCustomType) { strType = JsonSchemaUtils.IsArray(schema) ? string.Format("{0}<{1}>", JsonSchemaUtils.GetArrayType(schema), type.Name) : type.Name; } else if (JsonSchemaUtils.IsArray(schema)) { strType = string.Format("{0}<{1}>", JsonSchemaUtils.GetArrayType(schema), new CSharpCodeProvider().GetTypeOutput(new CodeTypeReference(type))); } //var field = new CodeMemberField //{ // Attributes = MemberAttributes.Private, // Name = "_" + i.Key, // Type = // TypeUtils.IsPrimitive(type) && !JsonSchemaUtils.IsArray(schema) // ? new CodeTypeReference(type) // : new CodeTypeReference(strType) //}; //clWrap.Property.Members.Add(field); var property = CreateProperty(propertyName, TypeUtils.IsPrimitive(type) && !JsonSchemaUtils.IsArray(schema) ? new CodeTypeReference(type) : new CodeTypeReference(strType)); var prWrap = new PropertyWrapper(property); // Add comments and attributes prWrap.Populate(schema, _attributeType); // Add default, if any if (schema.Default != null) { clWrap.AddDefault(propertyName, property.Type, schema.Default.ToString()); } clWrap.Property.Members.Add(property); } } } // Add class to namespace nsWrap.AddClass(clWrap.Property); codeCompileUnit.Namespaces.Add(nsWrap.Namespace); return codeCompileUnit; }
static bool Filter(string value, ClassWrapper item) { return item.Name.IndexOf(value, StringComparison.OrdinalIgnoreCase) > -1; }
/// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> PostRequiredClassPropertyAsync( this IExplicitModel operations, ClassWrapper bodyParameter, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Error> result = await operations.PostRequiredClassPropertyWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); return result.Body; }
private bool TryInvoke(MethodWrapperDescriptor method, Dictionary<string, object> allParams, ClassWrapper.ClassWrapper controllerWrapper, bool hasConverter, IHttpContext context, bool isChildRequest, out object methResult) { try { var request = context.Request; var parsValues = new List<object>(); methResult = null; var methPars = method.Parameters.ToList(); for (int index = 0; index < methPars.Count; index++) { bool parValueSet = false; var par = methPars[index]; object valueToAdd = null; if (allParams.ContainsKey(par.Name)) { var parValue = allParams[par.Name]; if (parValue.GetType() != par.ParameterType) { object convertedValue; if (UniversalTypeConverter.TryConvert(parValue, par.ParameterType, out convertedValue)) { valueToAdd = convertedValue; parValueSet = true; } else if (!par.HasDefault) { if (par.ParameterType.IsValueType) { return false; } parValueSet = true; } } else { valueToAdd = parValue; parValueSet = true; } } if (par.ParameterType == typeof(FormCollection)) { parValueSet = true; valueToAdd = new FormCollection(context.Request.Form); } if (parValueSet == false && request.ContentType != null) { var parType = par.ParameterType; if (!parType.IsValueType && !parType.IsArray && !(parType == typeof(string)) && !parType.IsEnum && !(parType == typeof(object))) { try { valueToAdd = _conversionService.Convert(parType, request.ContentType, request); parValueSet = true; } catch (Exception) { } } } if (par.HasDefault && !parValueSet) { parValueSet = true; valueToAdd = par.Default; } if (!parValueSet && string.Compare(par.Name, "returnUrl", StringComparison.OrdinalIgnoreCase) == 0) { if (request.UrlReferrer != null) { parValueSet = true; valueToAdd = request.UrlReferrer.ToString(); } } if (!par.GetType().IsValueType && !parValueSet) { parValueSet = true; valueToAdd = null; } if (!parValueSet) return false; parsValues.Add(valueToAdd); } var attributes = new List<Attribute>(method.Attributes); foreach (var attribute in attributes) { var filter = attribute as IFilter; if (filter != null) { if (!filter.OnPreExecute(context)) { methResult = NullResponse.Instance; return true; } } else if (attribute is ChildActionOnly && !isChildRequest) { throw new HttpException(404, string.Format("Url '{0}' not found.", _context.Request.Url)); } } var msd = new ModelStateDictionary(); foreach (var par in parsValues) { if (ValidationService.CanValidate(par)) { var validationResult = ValidationService.ValidateModel(par); foreach (var singleResult in validationResult) { msd.AddModelError(singleResult.Property, singleResult.Message); } } } controllerWrapper.Set("ModelState", msd); var result = controllerWrapper.TryInvoke(method, out methResult, parsValues.ToArray()); if (result) { foreach (var attribute in attributes) { var filter = attribute as IFilter; if (filter != null) { filter.OnPostExecute(context); } } } return result; } catch (Exception) { Log.Info("Not found suitable action for method '{0}'.", method.Name); methResult = null; return false; } }
public ControllerWrapperInstance(ControllerWrapperDescriptor cd, ClassWrapper.ClassWrapper instance) { WrapperDescriptor = cd.WrapperDescriptor; _cd = cd; Instance = instance; }