static private bool WriteFile(string completeJavascriptFilename, EFunctionFile eFile) { try { StringBuilder newFileContent = new StringBuilder(); newFileContent.Append("//author Bruno Tezine\n"); newFileContent.Append("//.pragma library nao suporta variavel de contexto\n"); newFileContent.Append(".import com.tezine.basesingletons 1.0 as BaseSingletons\n"); newFileContent.Append(".import com.tezine.base 1.0 as Base\n"); newFileContent.Append(".import 'qrc:/Scripts/JFunctions.js' as JFunctions\n"); newFileContent.Append("\n"); foreach (EFunction eFunction in eFile.functionList) { newFileContent.Append(eFunction.qmlFunctionContent); newFileContent.Append("\n\n"); } string oldContent = ""; if (File.Exists(completeJavascriptFilename)) { oldContent = File.ReadAllText(completeJavascriptFilename); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(completeJavascriptFilename, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
//Ex from Typescript: [RestInPeacePost("ECaminhao GetByID(segment number id, mandatory number age, optional string bla, body string oi)")] static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfo("\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\tasync "); result.Append(functionName); result.Append("("); result.Append(argsStringBuilder.ToString()); result.Append("):Promise<"); result.Append(AngularWatcher.ConvertToAngularTypeName(eFunction.returnTypeName)); result.Append(">{\n"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { List <EArg> parametersList = mandatoryList; parametersList.AddRange(optionalList); StringBuilder bodyTxt = new StringBuilder(); bodyTxt.Append("\t\tif(progressBar)progressBar.visible=true;\n"); bodyTxt.Append("\t\tlet rest=base.createRestObj();\n"); bodyTxt.Append("\t\trest.clear();\n"); bodyTxt.Append("\t\trest.setBaseUrl(base.baseURL);\n"); var cSharpClassName = "S" + eFile.frontendClassName.Remove(0, 1); bodyTxt.Append("\t\trest.setRoute('/v" + eFunction.version.ToString() + "/" + cSharpClassName + "/" + eFunction.functionName + "');\n"); bodyTxt.Append("\t\trest.setToken(base.token);\n"); foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("\t\trest.appendUrlSegment(" + eArgSegment.name + ");\n"); } foreach (EArg eArgParameter in parametersList) { bodyTxt.Append("\t\trest.appendParameter('" + eArgParameter.name + "'," + eArgParameter.name + ");\n"); } if (bodyArg != null) { bodyTxt.Append("\t\trest.setBody(JSON.stringify(" + bodyArg.name + "));\n"); } bodyTxt.Append("\t\treturn rest." + Helper.GetRESTOperationForQML(eFile, eFunction, true) + "(progressBar);\n"); bodyTxt.Append("\t}"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfoIfDebugLevel(DebugLevels.Functions | DebugLevels.All, "\tFunction " + eFunction.functionName); eFunction.frontendReturnTypeName = eFunction.returnTypeName; string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\t\tpublic async Task<" + eFunction.frontendReturnTypeName + "> " + eFunction.functionName + "(" + argsStringBuilder.ToString() + ") {"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static public string GetRESTOperation(EFunctionFile eFile, EFunction eFunction) { try { string operation = ""; if (eFunction.functionType == FunctionType.GET) { operation = "get"; } else if (eFunction.functionType == FunctionType.POST) { operation = "post"; } else if (eFunction.functionType == FunctionType.PUT) { operation = "put"; } else if (eFunction.functionType == FunctionType.DELETE) { operation = "delete"; } else { Logger.LogError("unable to identify function operation to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(""); } return(operation); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfoIfDebugLevel(DebugLevels.Functions | DebugLevels.All, "\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); eFunction.frontendReturnTypeName = FlutterWatcher.GetFlutterType(eFunction.returnTypeName, out bool isAnotherEntityImport); //antes era GetFlutterFuctionReturnType string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("\tstatic Future<" + eFunction.frontendReturnTypeName + "> " + functionName + "(" + argsStringBuilder.ToString() + ") async {"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.frontendFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
//Ex from Typescript: [RestInPeacePost("ECaminhao GetByID(segment number id, mandatory number age, optional string bla, body string oi)")] static private bool WriteFunction(EFunctionFile eFile, EFunction eFunction) { try { StringBuilder result = new StringBuilder(); StringBuilder argsStringBuilder = new StringBuilder(); List <EArg> segmentsList, mandatoryList, optionalList, formArgList, allArgsList; EArg bodyArg; Logger.LogInfo("\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); string operation = Helper.GetRESTOperation(eFile, eFunction); if (string.IsNullOrEmpty(operation)) { return(false); } if (!GetFunctionArgs(eFunction, ref argsStringBuilder, out allArgsList, out segmentsList, out mandatoryList, out optionalList, out formArgList, out bodyArg)) { Logger.LogError("unable to get funcion parameters to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(false); } result.Append("function "); result.Append(functionName); string args = argsStringBuilder.ToString(); if (!isForTypescriptApp) { if (args.Length > 0) { result.Append("(progressBar, callback, "); } else { result.Append("(progressBar, callback"); //nao tem argumento } } else { if (args.Length > 0) { result.Append("(progressBar, "); } else { result.Append("(progressBar"); //nao tem argumento } } result.Append(args); result.Append(") {\n"); string functionBody = GetFunctionBody(eFile, eFunction, operation, segmentsList, mandatoryList, optionalList, formArgList, bodyArg); result.Append(functionBody); eFunction.qmlFunctionContent = result.ToString(); return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private bool WriteBlazorFile(EFunctionFile eFile) { try { StringBuilder newFileContent = new StringBuilder(); newFileContent.Append("#region Imports\n"); //newFileContent.Append("//author Bruno Tezine\n"); newFileContent.Append("using Newtonsoft.Json;\n"); newFileContent.Append("using SharedLib.Entities;\n"); newFileContent.Append("using " + Globals.blazorNamespaceName + ".Codes;\n"); newFileContent.Append("using " + Globals.blazorNamespaceName + ".Entities.RestInPeace;\n"); newFileContent.Append("using System;\n"); newFileContent.Append("using System.Text;\n"); newFileContent.Append("using System.Collections.Generic;\n"); newFileContent.Append("using System.Linq;\n"); newFileContent.Append("using System.Net.Http;\n"); newFileContent.Append("using System.Threading.Tasks;\n"); newFileContent.Append("#endregion\n"); //imports above newFileContent.Append("\nnamespace Frontend.Services {\n"); newFileContent.Append("\tpublic class " + eFile.frontendClassName + " {\n"); newFileContent.Append("\t\tHttpClient httpClient;\n\n"); newFileContent.Append("\t\tpublic " + eFile.frontendClassName + "(HttpClient client) {\n"); newFileContent.Append("\t\t\thttpClient = client;\n"); newFileContent.Append("\t\t}\n\n"); foreach (EFunction eFunction in eFile.functionList) { if (!WriteFunction(eFile, eFunction)) { Logger.LogError("unable get function " + eFunction.functionName + " from file " + eFile.csharpFileName); return(false); } newFileContent.Append(eFunction.frontendFunctionContent); newFileContent.Append("\n\n"); } newFileContent.Append("\t}\n"); newFileContent.Append("}\n"); string oldContent = ""; if (File.Exists(eFile.frontendFileName)) { oldContent = File.ReadAllText(eFile.frontendFileName); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(eFile.frontendFileName, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private bool AnalyseFile(string path) { try { if (!File.Exists(path)) { return(true); } FileInfo fileInfo = new FileInfo(path); if (fileInfo.Name.StartsWith("E")) { return(true); //entity } string fullContent = File.ReadAllText(path); if (fullContent.Contains("public enum")) { return(true); //enum } IEnumerable <string> linesList = fullContent.Split('\n'); EFunctionFile eFile = new EFunctionFile(); eFile.csharpFileName = fileInfo.Name.Replace(".cs", String.Empty); eFile.functionList = new List <EFunction>(); if (fullContent.Contains("[RestInPeace")) { Logger.LogInfoIfDebugLevel(DebugLevels.Files | DebugLevels.All, "\t" + eFile.csharpFileName); } for (int l = 0; l < linesList.Count(); l++) { string lineContent = linesList.ElementAt(l); if (!lineContent.Contains("[RestInPeace")) { continue; } EFunction eFunction = AnalyseTypeSyncFunction(fileInfo.Name, lineContent, l + 1); if (eFunction == null) { return(false); } eFile.functionList.Add(eFunction); } if (eFile.functionList.Count > 0) { Globals.backendControllerFiles.Add(eFile); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetImports(List <string> entitiesList, EFunctionFile eFile) { try { StringBuilder imports = new StringBuilder(); imports.Append("//#region Imports\n"); imports.Append("import { Injectable } from '@angular/core'\n"); imports.Append("import {Http, Response, URLSearchParams} from '@angular/http'\n"); if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { imports.Append("import {AuthHttp} from 'angular2-jwt'\n"); imports.Append("import {Observable} from 'rxjs/Rx';\n"); } else { imports.Append("import {HttpClient, HttpParams} from '@angular/common/http';\n"); } imports.Append("import {Defines} from '../../codes/defines';\n"); imports.Append("import {Helper} from '../../codes/helper';\n"); //Logger.LogInfo("entidade usadas:"+entitiesList.Count.ToString()); List <EEnumFile> restInPeaceEnums = CSharpEnumReader.fileList; foreach (string entityName in entitiesList) { if (restInPeaceEnums.Any(x => String.Equals(x.enumName, entityName, StringComparison.CurrentCultureIgnoreCase))) { imports.Append("import { " + entityName + " } from '../../enums/restinpeace/" + entityName.ToLower() + "';\n"); } else { imports.Append("import { " + entityName + " } from '../../entities/restinpeace/" + entityName.ToLower() + "';\n"); //import { ECaminhao } from "../entities/ecaminhao"; } } //let's find external(not entities) imports used in file foreach (EFunction eFunction in eFile.functionList) { GetImportFromType(ref imports, eFunction.returnTypeName); foreach (EArg eArg in eFunction.argsList) { GetImportFromType(ref imports, eArg.typeName); } } imports.Append("//#endregion\n\n"); return(imports.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static public string GetRESTOperationForQML(EFunctionFile eFile, EFunction eFunction, bool isForTypescriptApp = false) { try { if (!isForTypescriptApp) { if (eFunction.functionType == FunctionType.GET) { return("get"); } if (eFunction.functionType == FunctionType.POST) { return("post"); } if (eFunction.functionType == FunctionType.PUT) { return("put"); } if (eFunction.functionType == FunctionType.DELETE) { return("del"); } } else //for typescript app { if (eFunction.functionType == FunctionType.GET) { return("getForTypescript"); } if (eFunction.functionType == FunctionType.POST) { return("postForTypescript"); } if (eFunction.functionType == FunctionType.PUT) { return("putForTypescript"); } if (eFunction.functionType == FunctionType.DELETE) { return("delForTypescript"); } } Logger.LogError("unable to identify function operation to write file " + eFile.frontendFileName + ": " + eFunction.functionName); return(""); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteFunctionsFromFile(EFunctionFile eFile) { try { foreach (EFunction eFunction in eFile.functionList) { if (!WriteFunction(eFile, eFunction)) { Logger.LogError("unable write function " + eFunction.functionName + " from file " + eFile.csharpFileName); return(false); } } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private bool GetTypescriptFunctions(EFunctionFile eFile) { try { //Logger.LogInfo("Writing functions of file " + eFile.fileName); foreach (EFunction eFunction in eFile.functionList) { if (!WriteFunction(eFile, eFunction)) { Logger.LogError("unable get typescript function " + eFunction.functionName + " from file " + eFile.csharpFileName); return(false); } } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { List <EArg> parametersList = mandatoryList; parametersList.AddRange(optionalList); StringBuilder bodyTxt = new StringBuilder(); bodyTxt.Append("\tif(progressBar)progressBar.visible=true;\n"); bodyTxt.Append("\tvar rest=base.createRestObj();\n"); bodyTxt.Append("\trest.clear();\n"); bodyTxt.Append("\trest.setBaseUrl(dstore.baseURL);\n"); bodyTxt.Append("\trest.setRoute('/v" + eFunction.version.ToString() + "/" + eFile.csharpFileName + "/" + eFunction.functionName + "');\n"); bodyTxt.Append("\trest.setToken(dstore.token);\n"); foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("\trest.appendUrlSegment(" + eArgSegment.name + ");\n"); } foreach (EArg eArgParameter in parametersList) { bodyTxt.Append("\trest.appendParameter('" + eArgParameter.name + "'," + eArgParameter.name + ");\n"); } if (bodyArg != null) { bodyTxt.Append("\trest.setBody(JSON.stringify(" + bodyArg.name + "));\n"); } if (!isForTypescriptApp) { bodyTxt.Append("\trest." + Helper.GetRESTOperationForQML(eFile, eFunction, isForTypescriptApp) + "(function(response){\n"); bodyTxt.Append("\t\tif(progressBar)progressBar.visible=false;\n"); bodyTxt.Append("\t\tvar result=JSON.parse(response);\n"); bodyTxt.Append("\t\tcallback(result);\n"); bodyTxt.Append("\t});\n"); } else //for typescript app { bodyTxt.Append("\treturn rest." + Helper.GetRESTOperationForQML(eFile, eFunction, isForTypescriptApp) + "(progressBar);\n"); } bodyTxt.Append("}"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private List <string> GetProjectEntitiesUsedInFile(List <EEntityFile> entityFilesList, EFunctionFile eFunctionFile) { try { List <string> entitiesUsedList = new List <string>(); foreach (EFunction eFunction in eFunctionFile.functionList) { string name = StringHelper.RemoveString(eFunction.returnTypeName, "List<").Trim(); name = StringHelper.RemoveString(name, ">"); if (IsEntity(entityFilesList, name)) { entitiesUsedList.Add(name); } foreach (EArg eArg in eFunction.argsList) { string name1 = StringHelper.RemoveString(eArg.typeName, "List<").Trim(); name1 = StringHelper.RemoveString(name1, ">"); if (IsEntity(entityFilesList, name1)) { entitiesUsedList.Add(name1); } } } return(entitiesUsedList); } catch (Exception e) { Logger.LogError(e); } return(null); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { StringBuilder bodyTxt = new StringBuilder(); string operationName = ""; switch (eFunction.functionType) { case FunctionType.GET: operationName = "HttpMethod.Get"; break; case FunctionType.PUT: operationName = "HttpMethod.Put"; break; case FunctionType.POST: operationName = "HttpMethod.Post"; break; case FunctionType.DELETE: operationName = "HttpMethod.Delete"; break; } bodyTxt.Append("\n\t\t\tGlobals.loading = true;"); bodyTxt.Append("\n\t\t\tHttpRequestMessage req = new HttpRequestMessage(" + operationName + ", $\"api/v" + eFunction.version + "/S" + eFile.frontendClassName + "/" + eFunction.functionName); if (segmentsList.Count == 0 && optionalList.Count == 0) { bodyTxt.Append("\");"); } foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("/{" + eArgSegment.name + "}"); } if (optionalList.Any()) { bodyTxt.Append("?"); } for (int i = 0; i < optionalList.Count; i++) { var eArgOptional = optionalList.ElementAt(i); bodyTxt.Append(eArgOptional.name + "={" + eArgOptional.name + "}"); if (i < (optionalList.Count - 1)) { bodyTxt.Append("&"); } } if (segmentsList.Any() || optionalList.Any()) { bodyTxt.Append("\");"); } bodyTxt.Append("\n"); bodyTxt.Append("\t\t\treq.Headers.Add(\"Authorization\", $\"bearer {Globals.jwtToken}\");\n"); if (bodyArg != null) { bodyTxt.Append("\t\t\treq.Content = new StringContent(JsonConvert.SerializeObject(" + bodyArg.name + "), Encoding.UTF8, \"application/json\");\n"); } bodyTxt.Append("\t\t\tvar response = await httpClient.SendAsync(req);\n"); bodyTxt.Append("\t\t\tGlobals.loading = false;\n"); bodyTxt.Append("\t\t\tif (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)throw new UnauthorizedAccessException();\n"); bodyTxt.Append("\t\t\tresponse.EnsureSuccessStatusCode();\n"); if (eFunction.frontendReturnTypeName != "void") { bodyTxt.Append("\t\t\tstring responseBody = await response.Content.ReadAsStringAsync();\n"); switch (eFunction.frontendReturnTypeName) { case "string": bodyTxt.Append("\t\t\treturn responseBody;\n"); break; case "Int64": bodyTxt.Append("\t\t\treturn Int64.Parse(responseBody);\n"); break; case "bool": bodyTxt.Append("\t\t\treturn bool.Parse(responseBody);\n"); break; case "Decimal": case "decimal": bodyTxt.Append("\t\t\treturn decimal.Parse(responseBody);\n"); break; default: bodyTxt.Append("\t\t\t" + eFunction.frontendReturnTypeName + " result = JsonConvert.DeserializeObject<" + eFunction.frontendReturnTypeName + ">(responseBody);\n"); bodyTxt.Append("\t\t\treturn result;\n"); break; } } bodyTxt.Append("\t\t}"); // // // // // // // bodyTxt.Append("\n\t\tfinal response = await http." + operation + "(Defines.RestBaseURL + '/v" + eFunction.version.ToString() + "/" + eFile.csharpFileName + "/" + eFunction.functionName); // if (segmentsList.Count == 0) bodyTxt.Append("'"); // foreach (EArg eArgSegment in segmentsList) { // bodyTxt.Append("/${" + eArgSegment.name + "}"); // } // if (segmentsList.Count > 0) bodyTxt.Append("'"); // bodyTxt.Append(",\n\t\t\t\theaders: {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+Defines.JwtToken},"); // if (bodyArg != null) { // switch (bodyArg.typeName) { // //cshartptype // case "string": // bodyTxt.Append("\n\t\t\t\tbody: json.encode(" + bodyArg.name + "));\n\n"); // break; // default: // bodyTxt.Append("\n\t\t\t\tbody: json.encode(" + bodyArg.name + ".toJson()));\n\n"); // break; // } // } else bodyTxt.Append(");\n\n"); // // bodyTxt.Append("\t\tif (response.statusCode != 200) print('(" + eFile.frontendClassName + ")" + eFunction.functionName + " error. Status code: ${response.statusCode}');\n"); // if (eFunction.frontendReturnTypeName != "void") { // bodyTxt.Append("\t\treturn "); // if (eFunction.frontendReturnTypeName == "int") bodyTxt.Append(eFunction.frontendReturnTypeName + ".parse(response.body);\n"); // else if (eFunction.frontendReturnTypeName == "bool") bodyTxt.Append("BoolHelper.convertStringToBool(response.body);\n"); // else if (eFunction.frontendReturnTypeName.Contains("List<")) { // string nameWithoutList = StringHelper.RemoveString(eFunction.returnTypeName, "List<"); // nameWithoutList = StringHelper.RemoveString(nameWithoutList, ">"); // bodyTxt.Append("(json.decode(response.body) as List).map((e) => new " + nameWithoutList + ".fromJson(e)).toList();\n"); // } else if (eFunction.frontendReturnTypeName == "String") bodyTxt.Append("json.decode(response.body);\n"); // else bodyTxt.Append(eFunction.frontendReturnTypeName + ".fromJson(json.decode(response.body));\n"); // } return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteFlutterFile(EFunctionFile eFile) { try { StringBuilder newFileContent = new StringBuilder(); newFileContent.Append("//region imports\n"); newFileContent.Append("//author Bruno Tezine\n"); newFileContent.Append("import \'dart:convert\';\n"); newFileContent.Append("import \'package:http/http.dart\' as http;\n"); newFileContent.Append("import \'package:flutter_base/codes/bool_helper.dart\';\n"); newFileContent.Append($"import \'package:{Globals.flutterPackageName}/codes/defines.dart\';\n"); //let's insert all entity imports List <string> importList = new List <string>(); List <string> allFunctionArgTypes = GetFunctionArgumentTypeNames(eFile.functionList); List <string> allReturnTypes = GetAllReturnTypeNames(eFile.functionList); foreach (string argType in allFunctionArgTypes) { string completeImportLine = ""; if (CSharpEntityReader.IsEntity(argType)) { completeImportLine = "import 'package:" + Globals.flutterPackageName + "/entities/restinpeace/" + argType.ToLower() + ".dart';\n"; } else if (CSharpEnumReader.IsEnum(argType)) { completeImportLine = "import 'package:" + Globals.flutterPackageName + "/enums/" + argType.ToLower() + ".dart';\n"; } else if (!Helper.isBasicDotnetType(argType)) { Logger.LogError($"Unknown arg type {argType} used in file {eFile.csharpFileName}!!!"); continue; } if (importList.Contains(completeImportLine)) { continue; } importList.Add(completeImportLine); } foreach (string returnType in allReturnTypes) { string completeImportLine = ""; if (CSharpEntityReader.IsEntity(returnType)) { completeImportLine = "import 'package:" + Globals.flutterPackageName + "/entities/restinpeace/" + returnType.ToLower() + ".dart';\n"; } else if (CSharpEnumReader.IsEnum(returnType)) { completeImportLine = "import 'package:" + Globals.flutterPackageName + "/enums/" + returnType.ToLower() + ".dart';\n"; } else if (!Helper.isBasicDotnetType(returnType)) { Logger.LogError($"Unknown return type {returnType} used in file {eFile.csharpFileName}!!!"); continue; } if (importList.Contains(completeImportLine)) { continue; } importList.Add(completeImportLine); } foreach (string importLine in importList) { newFileContent.Append(importLine); } newFileContent.Append("//endregion\n\n"); //imports above newFileContent.Append($"class {eFile.frontendClassName}" + "{\n"); // foreach (EFunction eFunction in eFile.functionList) { // string flutterTypeName=FlutterWatcher.GetFlutterType(eFunction.returnTypeName, out bool isAnotherEntityImport);//antes era GetFlutterFuctionReturnType // if (string.IsNullOrEmpty(flutterTypeName)) continue; // } newFileContent.Append("\n"); foreach (EFunction eFunction in eFile.functionList) { if (!WriteFunction(eFile, eFunction)) { Logger.LogError("unable get function " + eFunction.functionName + " from file " + eFile.csharpFileName); return(false); } newFileContent.Append(eFunction.frontendFunctionContent); newFileContent.Append("\n\n"); } newFileContent.Append("}\n"); string oldContent = ""; if (File.Exists(eFile.frontendFileName)) { oldContent = File.ReadAllText(eFile.frontendFileName); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(eFile.frontendFileName, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private bool WriteFile(string mJSClassName, string completeJavascriptFilename, EFunctionFile eFile) { try { StringBuilder newFileContent = new StringBuilder(); newFileContent.Append("//author Bruno Tezine\n\n"); newFileContent.Append("export class " + mJSClassName + " {\n"); newFileContent.Append("\n"); foreach (EFunction eFunction in eFile.functionList) { newFileContent.Append(eFunction.qmlFunctionContent); newFileContent.Append("\n\n"); } newFileContent.Append("}\n"); string oldContent = ""; if (File.Exists(completeJavascriptFilename)) { oldContent = File.ReadAllText(completeJavascriptFilename); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(completeJavascriptFilename, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private bool WriteFile(List <string> entitiesList, string serviceFileName, EFunctionFile eFile) { try { string newFileContent = @"#region Imports using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Flurl; using Flurl.Http; using Newtonsoft.Json; using SharedLib.Entities; using Mobile.Codes; using Mobile.Entities.RestInPeace; #endregion namespace Mobile.Services{ class " + eFile.frontendClassName + @"{ #region Singleton private static " + eFile.frontendClassName + @" instance; private " + eFile.frontendClassName + @"() { } public static " + eFile.frontendClassName + @" Obj { get { if (instance == null) instance = new " + eFile.frontendClassName + @"(); return instance; } } #endregion "; foreach (EFunction eFunction in eFile.functionList) { newFileContent += eFunction.frontendFunctionContent; newFileContent += "\n"; } newFileContent += "\t}\n"; newFileContent += "}\n"; newFileContent += System.Environment.NewLine; string oldContent = ""; if (File.Exists(serviceFileName)) { oldContent = File.ReadAllText(serviceFileName); } if (newFileContent != oldContent) { File.WriteAllText(serviceFileName, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { StringBuilder bodyTxt = new StringBuilder(); bodyTxt.Append("\t\t\ttry{\n"); if (eFunction.returnTypeName != "void") { bodyTxt.Append("\t\t\t\t" + eFunction.returnTypeName + " result = await (Defines.RestBaseURL+\"/v" + eFunction.version.ToString() + "/S" + eFile.frontendClassName + "/" + eFunction.functionName + "\")\n"); } else { bodyTxt.Append("\t\t\t\t await (Defines.RestBaseURL+\"/v" + eFunction.version.ToString() + "/" + eFile.csharpFileName + "/" + eFunction.functionName + "\")\n"); } foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("\t\t\t\t\t.AppendPathSegment(" + eArgSegment.name + ")\n"); } foreach (EArg mandatoryArg in mandatoryList) { bodyTxt.Append("\t\t\t\t\t.SetQueryParam(\"" + mandatoryArg.name + "\", " + mandatoryArg.name + ")\n"); } foreach (EArg optionalArg in optionalList) { bodyTxt.Append("\t\t\t\t\t.SetQueryParam(\"" + optionalArg.name + "\", " + optionalArg.name + ")\n"); } bodyTxt.Append("\t\t\t\t\t.WithHeader(\"Authorization\",\"Bearer \"+Defines.Token)\n"); if (eFunction.functionType == FunctionType.GET || eFunction.functionType == FunctionType.DELETE) { if (eFunction.returnTypeName != "void") { bodyTxt.Append("\t\t\t\t\t.GetJsonAsync<" + eFunction.returnTypeName + ">();\n"); } else { bodyTxt.Append("\t\t\t\t\t.GetAsync();\n"); } } else if (eFunction.functionType == FunctionType.POST) { if (bodyArg != null) { bodyTxt.Append("\t\t\t\t\t.PostJsonAsync(JsonConvert.SerializeObject(" + bodyArg.name + "))\n"); } else { bodyTxt.Append("\t\t\t\t\t.PostAsync(null)\n"); } if (eFunction.returnTypeName != "void") { bodyTxt.Append("\t\t\t\t\t.ReceiveJson<" + eFunction.returnTypeName + ">();\n"); } } else if (eFunction.functionType == FunctionType.PUT) { if (bodyArg != null) { bodyTxt.Append("\t\t\t\t\t.PutJsonAsync(JsonConvert.SerializeObject(" + bodyArg.name + "))\n"); } else { bodyTxt.Append("\t\t\t\t\t.PutAsync(null)\n"); } if (eFunction.returnTypeName != "void") { bodyTxt.Append("\t\t\t\t\t.ReceiveJson<" + eFunction.returnTypeName + ">();\n"); } } if (eFunction.returnTypeName != "void") { bodyTxt.Append("\t\t\t\treturn result;\n"); } bodyTxt.Append("\t\t\t}catch(Exception ex){\n"); bodyTxt.Append("\t\t\t\tLogger.LogError(ex);\n"); bodyTxt.Append("\t\t\t}\n"); if (eFunction.returnTypeName != "void") { if (eFunction.returnTypeName == "bool") { bodyTxt.Append("\t\t\treturn false;\n"); } else if (eFunction.returnTypeName == "int" || eFunction.returnTypeName == "Int64" || eFunction.returnTypeName == "Int32" || eFunction.returnTypeName == "double" || eFunction.returnTypeName == "float") { bodyTxt.Append("\t\t\treturn -1;\n"); } else if (eFunction.returnTypeName == "TimeSpan") { bodyTxt.Append("\t\t\treturn new TimeSpan();\n"); } else { bodyTxt.Append("\t\t\treturn null;\n"); } } bodyTxt.Append("\t\t}\n"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteTypescriptFile(string completeTypescriptFilename, EFunctionFile eFile) { try { //string typescriptClassName = ""; //if (eFile.csharpFileName.StartsWith("S")) typescriptClassName = eFile.csharpFileName.Remove(0, 1); StringBuilder newFileContent = new StringBuilder(); newFileContent.Append("//author Bruno Tezine\n"); //let's insert all entity imports List <string> importList = new List <string>(); List <string> allFunctionArgTypes = GetFunctionArgumentTypeNames(eFile.functionList); List <string> allReturnTypes = GetAllReturnTypeNames(eFile.functionList); newFileContent.Append("//region imports\n"); foreach (string argType in allFunctionArgTypes) { string completeImportLine = ""; if (CSharpEntityReader.IsEntity(argType)) { completeImportLine = "import {" + argType + "} from \"./" + argType + "\";\n"; } else if (CSharpEnumReader.IsEnum(argType)) { completeImportLine = "import {" + argType + "} from \"./" + argType + "\";\n"; } else if (!Helper.isBasicDotnetType(argType)) { Logger.LogError($"Unknown arg type {argType} used in file {eFile.csharpFileName}!!!"); continue; } if (importList.Contains(completeImportLine)) { continue; } importList.Add(completeImportLine); } foreach (string returnType in allReturnTypes) { string completeImportLine = ""; if (CSharpEntityReader.IsEntity(returnType)) { completeImportLine = "import {" + returnType + "} from \"./" + returnType + "\";\n"; } else if (CSharpEnumReader.IsEnum(returnType)) { completeImportLine = "import {" + returnType + "} from \"./" + returnType + "\";\n"; } else if (!Helper.isBasicDotnetType(returnType)) { Logger.LogError($"Unknown return type {returnType} used in file {eFile.csharpFileName}!!!"); continue; } if (importList.Contains(completeImportLine)) { continue; } importList.Add(completeImportLine); } foreach (string importLine in importList) { newFileContent.Append(importLine); } // newFileContent.Append("import {MySimpleEvent} from \"@QtTyped/Codes/MySimpleEvent\";\n"); newFileContent.Append("import {MySimpleEvent} from \"./MySimpleEvent\";\n"); newFileContent.Append("//endregion\n\n"); //imports above foreach (EFunction eFunction in eFile.functionList) { GetTypeScriptFuctionReturnType(eFunction, out string userTypeName); if (string.IsNullOrEmpty(userTypeName)) { continue; } } newFileContent.Append("export declare class " + eFile.frontendClassName + " {\n"); newFileContent.Append("\n"); foreach (EFunction eFunction in eFile.functionList) { Logger.LogInfoIfDebugLevel(DebugLevels.Functions | DebugLevels.All, "\tFunction " + eFunction.functionName); string functionName = Char.ToLowerInvariant(eFunction.functionName[0]) + eFunction.functionName.Substring(1); newFileContent.Append("\tstatic " + functionName + "(" + GetTypeScriptFuctionArguments(eFunction) + ")" + GetTypeScriptFuctionReturnType(eFunction, out string userTypeName)); newFileContent.Append("\n"); } newFileContent.Append("}\n"); string oldContent = ""; if (File.Exists(completeTypescriptFilename)) { oldContent = File.ReadAllText(completeTypescriptFilename); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(completeTypescriptFilename, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { StringBuilder bodyTxt = new StringBuilder(); // if (formArgList.Any()) { // bodyTxt.Append("\t\tlet formData = new FormData();\n"); // foreach (EArg formArg in formArgList) { // if (formArg.typeName == "any") bodyTxt.Append("\t\tformData.append('" + formArg.name + "', " + formArg.name + ");\n"); // else bodyTxt.Append("\t\tformData.append('" + formArg.name + "', " + formArg.name + ".toString());\n"); // } // bodyTxt.Append("\t\tconst response = await this.authHttp." + operation + "(Defines.RestBaseURL + '/v" + eFunction.version.ToString() + "/" + eFile.csharpFileName + "/" + eFunction.functionName + "'"); // if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) bodyTxt.Append(", formData).timeout(timeoutSeconds*1000).toPromise().catch(Helper.handleError);\n"); // else bodyTxt.Append(", formData).toPromise().catch(Helper.handleError);\n"); // bodyTxt.Append("\t\treturn response.json();\n"); // bodyTxt.Append("\t}"); // return bodyTxt.ToString(); // } // if (mandatoryList.Count > 0 || optionalList.Count > 0) { // bodyTxt.Append("\t\tlet params: HttpParams = new HttpParams();\n"); // foreach (EArg mandatoryArg in mandatoryList) { // bodyTxt.Append("\t\tparams= params.set('" + mandatoryArg.name + "', " + mandatoryArg.name + ".toString());\n"); // } // foreach (EArg optionalArg in optionalList) { // bodyTxt.Append("\t\tif(" + optionalArg.name + "!=null) params= params.set('" + optionalArg.name + "', " + optionalArg.name + ".toString());\n"); // } // } bodyTxt.Append("\n\t\tfinal response = await http." + operation + "(Defines.RestBaseURL + '/v" + eFunction.version.ToString() + "/" + eFile.csharpFileName + "/" + eFunction.functionName); if (segmentsList.Count == 0) { bodyTxt.Append("'"); } foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("/${" + eArgSegment.name + "}"); } if (segmentsList.Count > 0) { bodyTxt.Append("'"); } bodyTxt.Append(",\n\t\t\t\theaders: {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+Defines.JwtToken},"); if (bodyArg != null) { switch (bodyArg.typeName) //cshartptype { case "string": bodyTxt.Append("\n\t\t\t\tbody: json.encode(" + bodyArg.name + "));\n\n"); break; default: bodyTxt.Append("\n\t\t\t\tbody: json.encode(" + bodyArg.name + ".toJson()));\n\n"); break; } } else { bodyTxt.Append(");\n\n"); } // if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { // if (eFunction.functionType == FunctionType.PUT || eFunction.functionType == FunctionType.POST) { // bodyTxt.Append(", { headers: Defines.Headers }"); // } // } // if (mandatoryList.Count > 0 || optionalList.Count > 0) { // bodyTxt.Append(", {params: params}"); // } bodyTxt.Append("\t\tif (response.statusCode != 200) print('(" + eFile.frontendClassName + ")" + eFunction.functionName + " error. Status code: ${response.statusCode}');\n"); if (eFunction.frontendReturnTypeName != "void") { bodyTxt.Append("\t\treturn "); if (eFunction.frontendReturnTypeName == "int") { bodyTxt.Append(eFunction.frontendReturnTypeName + ".parse(response.body);\n"); } else if (eFunction.frontendReturnTypeName == "bool") { bodyTxt.Append("BoolHelper.convertStringToBool(response.body);\n"); } else if (eFunction.frontendReturnTypeName.Contains("List<")) { string nameWithoutList = StringHelper.RemoveString(eFunction.returnTypeName, "List<"); nameWithoutList = StringHelper.RemoveString(nameWithoutList, ">"); bodyTxt.Append("(json.decode(response.body) as List).map((e) => new " + nameWithoutList + ".fromJson(e)).toList();\n"); } else if (eFunction.frontendReturnTypeName == "String") { bodyTxt.Append("json.decode(response.body);\n"); } else { bodyTxt.Append(eFunction.frontendReturnTypeName + ".fromJson(json.decode(response.body));\n"); } } bodyTxt.Append("\t}"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }
static private bool WriteTypescriptFile(List <string> entitiesList, string serviceFileName, EFunctionFile eFile) { try { StringBuilder newFileContent = new StringBuilder(); string imports = GetImports(entitiesList, eFile); if (string.IsNullOrEmpty(imports)) { return(false); } newFileContent.Append("//author Bruno Vacare Tezine\n"); newFileContent.Append(imports); newFileContent.Append("@Injectable()\n"); newFileContent.Append("export class " + eFile.frontendClassName + " {\n\n"); if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { newFileContent.Append("\tconstructor(private authHttp: AuthHttp) {}\n\n"); } else { newFileContent.Append("\tconstructor(private authHttp: HttpClient) {}\n\n"); } foreach (EFunction eFunction in eFile.functionList) { newFileContent.Append(eFunction.frontendFunctionContent); newFileContent.Append("\n\n"); } newFileContent.Append("\n}"); string oldContent = ""; if (File.Exists(serviceFileName)) { oldContent = File.ReadAllText(serviceFileName); } if (newFileContent.ToString() != oldContent) { File.WriteAllText(serviceFileName, newFileContent.ToString()); } return(true); } catch (Exception e) { Logger.LogError(e); } return(false); }
static private string GetFunctionBody(EFunctionFile eFile, EFunction eFunction, string operation, List <EArg> segmentsList, List <EArg> mandatoryList, List <EArg> optionalList, List <EArg> formArgList, EArg bodyArg) { try { StringBuilder bodyTxt = new StringBuilder(); if (formArgList.Any()) { bodyTxt.Append("\t\tlet formData = new FormData();\n"); foreach (EArg formArg in formArgList) { if (formArg.typeName == "any") { bodyTxt.Append("\t\tformData.append('" + formArg.name + "', " + formArg.name + ");\n"); } else { bodyTxt.Append("\t\tformData.append('" + formArg.name + "', " + formArg.name + ".toString());\n"); } } bodyTxt.Append("\t\tconst response = await this.authHttp." + operation + "(Defines.RestBaseURL + '/v" + eFunction.version.ToString() + "/S" + eFile.frontendClassName + "/" + eFunction.functionName + "'"); if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { bodyTxt.Append(", formData).timeout(timeoutSeconds*1000).toPromise().catch(Helper.handleError);\n"); } else { bodyTxt.Append(", formData).toPromise().catch(Helper.handleError);\n"); } bodyTxt.Append("\t\treturn response;\n"); bodyTxt.Append("\t}"); return(bodyTxt.ToString()); } if (mandatoryList.Count > 0 || optionalList.Count > 0) { bodyTxt.Append("\t\tlet params: HttpParams = new HttpParams();\n"); foreach (EArg mandatoryArg in mandatoryList) { bodyTxt.Append("\t\tparams= params.set('" + mandatoryArg.name + "', " + mandatoryArg.name + ".toString());\n"); } foreach (EArg optionalArg in optionalList) { bodyTxt.Append("\t\tif(" + optionalArg.name + "!=null) params= params.set('" + optionalArg.name + "', " + optionalArg.name + ".toString());\n"); } } bodyTxt.Append("\t\tconst response = await this.authHttp." + operation + "(Defines.RestBaseURL + '/v" + eFunction.version.ToString() + "/S" + eFile.frontendClassName + "/" + eFunction.functionName + "'"); foreach (EArg eArgSegment in segmentsList) { bodyTxt.Append("+'/'+" + eArgSegment.name); } if (bodyArg != null) { if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { bodyTxt.Append(", JSON.stringify(" + bodyArg.name + ")"); } else { bodyTxt.Append(", JSON.stringify(" + bodyArg.name + "), Defines.httpOptions"); } } else { if ((!string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) && (eFunction.functionType == FunctionType.POST || eFunction.functionType == FunctionType.PUT)) { bodyTxt.Append(", Defines.httpOptions"); } } if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { if (eFunction.functionType == FunctionType.PUT || eFunction.functionType == FunctionType.POST) { bodyTxt.Append(", { headers: Defines.Headers }"); } } if (mandatoryList.Count > 0 || optionalList.Count > 0) { bodyTxt.Append(", {params: params}"); } if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { bodyTxt.Append(").timeout(timeoutSeconds*1000).toPromise().catch(Helper.handleError);\n"); } else { bodyTxt.Append(").toPromise().catch(Helper.handleError);\n"); } if (string.IsNullOrEmpty(AngularFunctionWriter.restInPeaceVersion)) { bodyTxt.Append("\t\treturn response.json();\n"); } else { bodyTxt.Append("\t\treturn response;\n"); } bodyTxt.Append("\t}"); return(bodyTxt.ToString()); } catch (Exception e) { Logger.LogError(e); } return(""); }