private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e) { try { var path = e.FullPath.RemoveStart(nodeModulesPath + @"\"); if (NO_CACHING) { return; } if (path != ".staging") { using (lockObject.Lock()) { if (cacheStatusType < CacheStatusType.AddingPathsToList) { cacheStatusType = CacheStatusType.AddingPathsToList; } if (!pathsToProcess.Contains(path) && !pathsToNotProcess.Contains(path)) { this.WriteLineNoLock("Adding '{0}' to paths to process", path); pathsToProcess.Add(path); this.AddPathStatusNoLock(path, CacheStatusType.PathAddedToList); } } } } catch (Exception ex) { DebugUtils.Break(); } }
public override void VisitViewData(ViewDataNode viewDataNode) { var key = viewDataNode.Key; var right = viewDataNode.Right; object value = null; if (right is LiteralExpressionSyntax) { var literalExpression = (LiteralExpressionSyntax)right; value = literalExpression.GetValue(); } else { DebugUtils.Break(); } if (this.ViewData.ContainsKey(key)) { this.ViewData[key] = value; } else { this.ViewData.Add(key, value); } base.VisitViewData(viewDataNode); }
private bool InstallFromCache(PackageWorkingInstallFromCache installFromCache) { var mode = installFromCache.Mode; var install = installFromCache.Install; var packageDirectory = new DirectoryInfo(installFromCache.PackagePath); var path = packageDirectory.FullName.RemoveStart(nodeModulesPath + @"\"); try { var elapsed = TimeSpan.MinValue; SkipPath(packageDirectory.Name); AddInstallStatus(installFromCache, StatusMode.Normal, $"Installing '{ install }' from cache"); using (this.StartStopwatch((s) => elapsed = s)) { installFromCache.InstallPackage(); AddPathStatus(path, CacheStatusType.PathProcessed); } AddInstallStatus(installFromCache, StatusMode.Success, "Install of '{0}' from cache took {1} seconds", path, elapsed.ToDecimalSeconds()); AddPackageCacheStatus(path, install, CacheStatusType.PathCopiedFromCache); } catch (Exception ex) { AddInstallStatus(installFromCache, StatusMode.Error, "Error installing '{0}', ", ex.Message); AddPackageCacheStatus(path, install, ex); DebugUtils.Break(); return(false); } return(true); }
protected override Expression VisitBinary(BinaryExpression binaryExpression) { var binaryOperatorExpression = new BinaryOperatorExpressionNode(); switch (binaryExpression.NodeType) { case ExpressionType.And: DebugUtils.Break(); break; case ExpressionType.Equal: binaryOperatorExpression.Operator = Operator.Equality; break; default: throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported", binaryExpression.NodeType)); } AddChild(binaryOperatorExpression); binaryOperatorExpression.Left = (ExpressionNode)this.VisitNode(binaryExpression.Left); binaryOperatorExpression.Right = (ExpressionNode)this.VisitNode(binaryExpression.Right); return(binaryExpression); }
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { if (methodCallExpression.Method.DeclaringType == typeof(Queryable)) { var methodDeclaration = new InvocationExpressionNode(methodCallExpression.Method.Name); LambdaExpression lambda; AddChild(methodDeclaration); methodDeclaration.Target = (ExpressionNode)this.VisitNode(methodCallExpression.Arguments[0]); if (methodCallExpression.Arguments.Count > 1) { lambda = (LambdaExpression)StripQuotes(methodCallExpression.Arguments[1]); methodDeclaration.Arguments.Add((ExpressionNode)this.VisitNode(lambda.Body)); } return(methodCallExpression); } else { DebugUtils.Break(); } throw new NotSupportedException(string.Format("The method '{0}' is not supported", methodCallExpression.Method.Name)); }
public override bool Process(IBase baseObject, Facet facet, IGeneratorConfiguration generatorConfiguration) { var uiAttribute = (UIAttribute)facet.Attribute; var baseElement = (IElement)baseObject; var userFields = new List <IdentityField>(); var parentObject = (IElement)baseObject.Parent; var name = baseElement.GetNavigationName(UIKind.LoginPage); var subFolderName = name.ToLower(); var pagePath = FileSystemObject.PathCombine(generatorConfiguration.ApplicationFolderHierarchy[IonicFileSystemType.Pages], subFolderName); var resourcesHelper = generatorConfiguration.ResourcesHandler.CreateHelper(UIKind.LoginPage, baseObject); IDictionary <string, IEnumerable <ModuleImportDeclaration> > importGroups; IModuleAssembly module; Folder pageFolder = null; string loginTitleTranslationKey; string loginButtonTranslationKey; if (!generatorConfiguration.FileSystem.Exists(pagePath)) { var newPath = generatorConfiguration.FileSystem.CreatePath(pagePath); pageFolder = (Folder)generatorConfiguration.FileSystem[newPath]; } else { pageFolder = (Folder)generatorConfiguration.FileSystem[pagePath]; } if (uiAttribute.UILoadKind == UILoadKind.RootPage) { this.Raise <ApplicationFacetHandler>(); } importGroups = generatorConfiguration.CreateImportGroups(this, baseObject, pageFolder, true); importGroups.AddIndexImport("Page", "MainPage", 1); foreach (var childObject in baseElement.GetIdentityFields(IdentityFieldCategory.Login)) { if (childObject is IAttribute) { userFields.Add(new IdentityField((IAttribute)childObject, generatorConfiguration)); } else { DebugUtils.Break(); } } module = generatorConfiguration.PushModuleAssembly <AngularModule>("Login"); module.UILoadKind = uiAttribute.UILoadKind; loginTitleTranslationKey = resourcesHelper.Get(() => LOGIN_TITLE); loginButtonTranslationKey = resourcesHelper.Get(() => LOGIN_BUTTON); LoginPageGenerator.GeneratePage(baseObject, pagePath, name, generatorConfiguration, module, importGroups, userFields, loginTitleTranslationKey, loginButtonTranslationKey); return(true); }
private void InstallDependency(string name, NpmVersion installVersion, DirectoryInfo cachePackageNodeModulesDirectory, bool executeActions = true, bool executeDirectly = false) { var cachePath = Path.Combine(cachePathRoot, name.BackSlashes()); if (name.IsNullWhiteSpaceOrEmpty()) { DebugUtils.Break(); } InstallDependency(name, installVersion, cachePath, cachePackageNodeModulesDirectory, executeActions, executeDirectly); }
public void UpdateModuleAssembly(IModuleAssembly moduleAssembly) { var angularModule = (AngularModule)moduleAssembly; var count = 0; if (this.BaseObject == null) { DebugUtils.Break(); } angularModule.BaseObject = this.BaseObject; ObjectExtensions.MultiAct <IList>(l => { count += l.Count; }, this.Exports, this.Providers, this.Declarations); if (count == 0) { DebugUtils.Break(); } foreach (var export in this.Exports) { angularModule.AddBaseExport(this.BaseObject, export); } foreach (var provider in this.Providers) { List <Provider> providers = null; provider.BaseObject = this.BaseObject; if (this.Configuration.KeyValuePairs.ContainsKey("Providers")) { providers = (List <Provider>) this.Configuration.KeyValuePairs["Providers"]; } else { providers = new List <Provider>(); this.Configuration.KeyValuePairs.Add("Providers", providers); } if (!providers.Contains(provider)) { providers.Add(provider); } } angularModule.Declarations.AddRange(this.Declarations); angularModule.Exports.AddRange(this.Exports); }
public HelperExpressionNode(RazorParserVisitor visitor, SyntaxTreeNode syntaxTreeNode, string contentPart) : base(visitor, NodeKind.HelperExpression, syntaxTreeNode, contentPart) { SyntaxTree syntaxTree; CompilationUnitSyntax syntaxRoot; MethodDeclarationSyntax renderMethod; ExpressionStatementSyntax statement; ExpressionSyntax expression; var builder = new StringBuilder(); visitor.StartClass(builder); visitor.StartRender(builder); builder.AppendLineFormat("{0}{1};", " ".Repeat(8), contentPart); visitor.WrapRenderAndClass(builder); syntaxTree = CSharpSyntaxTree.ParseText(builder.ToString()); syntaxRoot = (CompilationUnitSyntax)syntaxTree.GetRoot(); renderMethod = syntaxRoot.GetRenderMethod(); statement = (ExpressionStatementSyntax)renderMethod.Body.Statements.Single(); expression = statement.Expression; if (expression is InvocationExpressionSyntax) { var invocationExpression = (InvocationExpressionSyntax)expression; if (invocationExpression.Expression is MemberAccessExpressionSyntax) { var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression; this.Method = memberAccessExpression.Name.Identifier.Text; if (this.Method == "Partial") { this.PartialView = visitor.CreatePartialView(this.Method, invocationExpression.ArgumentList.Arguments); } } else { DebugUtils.Break(); } this.Arguments = invocationExpression.ArgumentList.Arguments; } else { DebugUtils.Break(); } Parse(); }
public override bool Process(IBase baseObject, Facet facet, IGeneratorConfiguration generatorConfiguration) { var uiAttribute = (UIAttribute)facet.Attribute; var baseElement = (IElement)baseObject; var name = baseElement.GetNavigationName(); var formFields = new List <FormField>(); var parentObject = (IElement)baseObject.Parent; var subFolderName = name.ToLower(); var pagePath = FileSystemObject.PathCombine(generatorConfiguration.ApplicationFolderHierarchy[IonicFileSystemType.Pages], subFolderName); IDictionary <string, IEnumerable <ModuleImportDeclaration> > importGroups; IModuleAssembly module; Folder pageFolder = null; if (!generatorConfiguration.FileSystem.Exists(pagePath)) { var newPath = generatorConfiguration.FileSystem.CreatePath(pagePath); pageFolder = (Folder)generatorConfiguration.FileSystem[newPath]; } else { pageFolder = (Folder)generatorConfiguration.FileSystem[pagePath]; } if (uiAttribute.UILoadKind == UILoadKind.RootPage) { this.Raise <ApplicationFacetHandler>(); } importGroups = generatorConfiguration.CreateImportGroups(this, baseObject, pageFolder, true); foreach (var childObject in baseElement.GetFormFields(generatorConfiguration.PartsAliasResolver)) { if (childObject is IAttribute) { formFields.Add(new FormField((IAttribute)childObject, generatorConfiguration)); } else { DebugUtils.Break(); } } module = generatorConfiguration.PushModuleAssembly <AngularModule>("Edit" + name); module.UILoadKind = uiAttribute.UILoadKind; EditPopupPageGenerator.GeneratePage(baseObject, pagePath, name, generatorConfiguration, module, importGroups, formFields); return(true); }
public void AddAssembly(IModuleAssembly moduleAssembly) { if (!this.moduleAssemblies.Any(a => a.Name == moduleAssembly.Name)) { var folders = folderHierarchy.GetAllFolders().Where(f => f.ModuleAssemblies.Any(a => a == moduleAssembly)); if (folders.Count() > 0) { var folder = folders.First(); DebugUtils.Break(); } this.moduleAssemblies.Add(moduleAssembly); } }
public void BinaryOperatorExpression(BinaryOperatorExpressionNode binaryOperatorExpressionNode) { binaryOperatorExpressionNode.Left.AcceptVisitor(this); switch (binaryOperatorExpressionNode.Operator) { case Operator.Equality: textWriter.Write("="); break; default: DebugUtils.Break(); break; } binaryOperatorExpressionNode.Right.AcceptVisitor(this); }
public void VisitMemberExpression(MemberExpressionNode memberExpressionNode) { var expression = memberExpressionNode.Expression; string member; if (expression is ParameterExpressionNode) { switch (this.namingConvention) { case NamingConvention.CamelCase: member = memberExpressionNode.Name.ToCamelCase(); textWriter.Write(member); break; } } else if (expression is MemberExpressionNode) { expression.AcceptVisitor(this); } else if (expression is ConstantExpressionNode) { if (memberExpressionNode.ParentNode is MemberExpressionNode) { var propertyName = ((MemberExpressionNode)memberExpressionNode.ParentNode).Name; var constantValue = ((ConstantExpressionNode)expression).Value; // this doesn't feel right, but works member = constantValue.GetPropertyValue <string>(propertyName); textWriter.Write(member); } else { member = (string)((ConstantExpressionNode)expression).Value; textWriter.Write(member); } } else { DebugUtils.Break(); } }
public void AddModule(Module module) { // kn - may not need this if (!this.modules.Any(a => a.Name == module.Name)) { var folders = folderHierarchy.GetAllFolders().Where(f => f.ModuleAssemblies.Any(a => a == module)); if (folders.Count() > 0) { var folder = folders.First(); DebugUtils.Break(); } this.modules.Add(module); } }
public bool Process(Enum moduleKind, IModuleObject moduleObject, Folder folder, IGeneratorConfiguration generatorConfiguration) { var angularModule = (AngularModule)moduleObject; var baseObject = moduleObject.BaseObject; var imports = generatorConfiguration.CreateImports(this, angularModule, folder, true); var name = baseObject.GetNavigationName(); var parentObject = (IParentBase)baseObject; if (!moduleObject.ValidateModuleName(name, out string error)) { DebugUtils.Break(error); } angularModule.AddImportsAndRoutes(imports); NavigationGridModuleGenerator.GenerateModule(baseObject, angularModule, folder.fullPath, name, generatorConfiguration, imports); return(true); }
public override void VisitViewBag(ViewBagNode viewBagNode) { var name = viewBagNode.PropertyName; var right = viewBagNode.Right; object value = null; if (right is LiteralExpressionSyntax) { var literalExpression = (LiteralExpressionSyntax)right; value = literalExpression.GetValue(); } else { DebugUtils.Break(); } this.ViewBag.Add(name, value); base.VisitViewBag(viewBagNode); }
/// <summary> Constructor. </summary> /// /// <remarks> Ken, 10/3/2020. </remarks> /// /// <param name="name"> The name. </param> /// <param name="parentDataItemText"> The parent data item text. </param> public EntityObject(string name, string parentDataItemText) : base(name) { int parentDataItem; if (int.TryParse(parentDataItemText, out parentDataItem)) { this.ParentDataItem = parentDataItem; } else if (parentDataItemText == "*") { this.IsInherentDataItem = true; } else { DebugUtils.Break(); } this.ParentDataItem = parentDataItem; this.Attributes = new List <AttributeObject>(); }
/// <summary> Parse file. </summary> /// /// <remarks> Ken, 10/1/2020. </remarks> /// /// <param name="path"> Full pathname of the file. </param> /// <param name="textReplacements"> The text replacements. </param> /// /// <returns> A List<TRecord> </returns> public override List <EntityDomainRecord> ParseFile(string path, Dictionary <string, string> textReplacements) { var records = base.ParseFile(path, textReplacements); EntityObject lastEntity = null; this.Entities = new List <EntityObject>(); foreach (var record in records) { if (record.EntityName != null) { var entity = new EntityObject(record.EntityName, record.ParentDataItem); if (record.Properties != null) { entity.Properties.AddRange(record.Properties); } this.Entities.Add(entity); lastEntity = entity; } else if (record.AttributeName != null) { var attribute = new AttributeObject(record.AttributeName, record.AttributeType); if (record.Properties != null) { attribute.Properties.AddRange(record.Properties); } lastEntity.Attributes.Add(attribute); } else { DebugUtils.Break(); } } return(records); }
public override void VisitModel(ModelNode modelNode) { this.ModelType = modelNode.ModelType; if (this.BaseObject.Name != this.ModelType) { if (this.BaseObject is IParentBase) { var parentBase = (IParentBase)this.BaseObject; var child = parentBase.ChildElements.Single(e => e.Name == this.ModelType); this.IsChildSet = true; this.SetObject = child; } else { DebugUtils.Break(); } } base.VisitModel(modelNode); }
public override void Add(T item) { if (item is Folder) { var folder = (Folder)(FileSystemObject)item; folder.Parent = (Folder)fileSystemObject; } else if (item is File) { var file = (File)(FileSystemObject)item; file.Folder = (Folder)fileSystemObject; file.fullPath = Path.Combine(file.Folder.FullName, file.Name).ForwardSlashes(); } else { DebugUtils.Break(); } folderHierarchy.IndexAdd(item.RelativeFullName, item); base.Add(item); }
private void InstallScopedPackage(DirectoryInfo cacheDirectory, bool executeActions, bool executeDirectly) { this.CachePath = cacheDirectory.FullName; this.PackagePath = Path.Combine(this.nodeModulesPath, "@" + this.Install); this.IsScoped = true; foreach (var subDirectory in cacheDirectory.GetDirectories()) { NpmVersion cacheVersion; var fileInfoCacheJson = new FileInfo(Path.Combine(subDirectory.FullName, "package.json")); if (fileInfoCacheJson.Exists) { using (var readerCache = fileInfoCacheJson.OpenText()) { var cachePackageJson = JsonExtensions.ReadJson <PackageJson>(readerCache); var cachePackageName = cachePackageJson.Name; var nodeModulesDirectory = new DirectoryInfo(nodeModulesPath); if (cachePackageJson.PeerDependencies == null || cachePackageJson.PeerDependencies.PeerExists(this.PackageModules)) { cacheVersion = cachePackageJson.Version; InstallDependency(cacheDirectory.Name + "/" + subDirectory.Name, cacheVersion, subDirectory.FullName, null, executeActions, executeDirectly); } else { } } } else { DebugUtils.Break(); } } }
public NpmVersion(string versionString) { string major; string minor; string patch; string tagid; var regexVersion = new Regex(@"^(?<prefix>[\^~><*xX]|\>=|\<=)?" + @"(?<version>" + @"(?<major>\d+|[*xX])" + @"(\.(?<minor>\d+||[*xX]))?" + @"(\.(?<patch>\d+||[*xX]))?" + @"(\-(?<tag>\w+?)\.(?<tagid>\d+)" + ")?" + ")?$"); if (!versionString.IsNullWhiteSpaceOrEmpty()) { if (regexVersion.IsMatch(versionString)) { var match = regexVersion.Match(versionString); this.Prefix = match.GetGroupValue("prefix"); if (this.Prefix.IsOneOf("*", "x", "X")) { this.MatchesAll = true; } else { this.VersionTuple = match.GetGroupValue("version"); major = match.GetGroupValue("major"); minor = match.GetGroupValue("minor"); patch = match.GetGroupValue("patch"); tagid = match.GetGroupValue("tagid"); this.Tag = match.GetGroupValue("tag"); if (!major.IsNullWhiteSpaceOrEmpty()) { if (major.IsOneOf("*", "x", "X")) { this.MajorWildcard = true; } else { this.Major = int.Parse(major); } } if (!minor.IsNullWhiteSpaceOrEmpty()) { if (minor.IsOneOf("*", "x", "X")) { this.MinorWildcard = true; } else { this.Minor = int.Parse(minor); } } if (!patch.IsNullWhiteSpaceOrEmpty()) { if (patch.IsOneOf("*", "x", "X")) { this.PatchWildcard = true; } else { this.Patch = int.Parse(patch); } } if (!tagid.IsNullWhiteSpaceOrEmpty()) { this.TagId = int.Parse(tagid); } } } else { var regexHyphenRange = new Regex(@"(?<versionLower>" + @"(?<majorLower>\d+)" + @"(\.(?<minorLower>\d+))?" + @"(\.(?<patchLower>\d+))?" + ")" + @"\s*\-\s*" + @"(?<versionUpper>" + @"(?<majorUpper>\d+)" + @"(\.(?<minorUpper>\d+))?" + @"(\.(?<patchUpper>\d+))?" + ")$"); if (regexHyphenRange.IsMatch(versionString)) { var match = regexHyphenRange.Match(versionString); this.VersionRangeLower = match.GetGroupValue("versionLower"); this.VersionRangeHigher = match.GetGroupValue("versionUpper"); } else { DebugUtils.Break(); } } this.Version = versionString; } }
public static NpmVersionComparison GetComparison(NpmVersion version1, NpmVersion version2) { bool?majorMatch = null; bool?minorMatch = null; bool?patchMatch = null; bool?major1Greater = null; bool?minor1Greater = null; bool?patch1Greater = null; var comparison = NpmVersionComparison.NoComparison; var skipDeeperComparison = false; if (version1.MatchesAll || version2.MatchesAll) { comparison = NpmVersionComparison.Matches; skipDeeperComparison = true; } else if (version1.HasWildcard || version2.HasWildcard) { NpmVersion npmWildcard = null; NpmVersion npmMatch = null; Regex regex = null; if (version1.HasWildcard) { npmWildcard = version1; npmMatch = version2.ToPaddedVersion(); } else if (version2.HasWildcard) { npmWildcard = version2; npmMatch = version1.ToPaddedVersion(); } else { DebugUtils.Break(); } regex = npmWildcard.GetRegexFromWildchard(); if (regex.IsMatch(npmMatch.VersionTuple)) { comparison = NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.NotEquals; } skipDeeperComparison = true; } else if (version1.VersionRangeLower != null && version1.VersionRangeHigher != null) { if (version2 >= version1.VersionRangeLower && version2 <= version1.VersionRangeHigher) { comparison = NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.NotEquals; } skipDeeperComparison = true; } else if (version2.VersionRangeLower != null && version2.VersionRangeHigher != null) { if (version1 >= version2.VersionRangeLower && version1 <= version2.VersionRangeHigher) { comparison = NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.NotEquals; } skipDeeperComparison = true; } if (!skipDeeperComparison) { if (version1.Version == null) { if (version2.Version == null) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; skipDeeperComparison = true; } else { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; skipDeeperComparison = true; } } else if (version2.Version != null) { if (version1.Version == version2.Version) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; if (!version1.HasRangeComparison && !version2.HasRangeComparison) { skipDeeperComparison = true; } } } if (version1.Major == null) { if (version2.Major == null) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; skipDeeperComparison = true; } else { comparison = NpmVersionComparison.LessThan; skipDeeperComparison = true; } } } if (!skipDeeperComparison) { if (version1.Major == null && version2.Major != null) { major1Greater = false; } else if (version1.Major != null && version2.Major == null) { major1Greater = true; } else if (version1.Major == version2.Major) { majorMatch = true; if (version1.Minor != null) { if (version2.Minor != null) { if (version1.Minor == version2.Minor) { minorMatch = true; // majors and minors match if (version1.Patch != null) { if (version2.Patch != null) { if (version1.Patch == version2.Patch) { patchMatch = true; // majors, minors, and patches match } else { patch1Greater = version1.Patch > version2.Patch; } } else { patch1Greater = true; } } else if (version2.Patch != null) { patch1Greater = false; // v1 has no patch, v2 does } else { // both have no patch patch1Greater = false; } } else { minor1Greater = version1.Minor > version2.Minor; } } else { minor1Greater = true; } } else if (version2.Minor != null) { minor1Greater = false; // v1 has no minor, v2 does } else { // both have no minor minor1Greater = false; } } else { major1Greater = version1.Major > version2.Major; majorMatch = false; } if (version1.Prefix != string.Empty && version2.Prefix != string.Empty) { comparison = NpmVersionComparison.NotEquals; // versions did not equal above } else if (version1.Prefix == string.Empty && version2.Prefix == string.Empty) { if (patch1Greater.IsValueTrue()) { comparison = NpmVersionComparison.GreaterThan; } else if (minor1Greater.IsValueTrue()) { comparison = NpmVersionComparison.GreaterThan; } else if (major1Greater.IsValueTrue()) { comparison = NpmVersionComparison.GreaterThan; } else if (patch1Greater.IsValueFalse()) { comparison = NpmVersionComparison.LessThan; } else if (minor1Greater.IsValueFalse()) { comparison = NpmVersionComparison.LessThan; } else if (major1Greater.IsValueFalse()) { comparison = NpmVersionComparison.LessThan; } else { DebugUtils.Break(); comparison = NpmVersionComparison.LessThan; } } else { // left has the prefix, matching to right. Left in general must be less than or equal to right switch (version1.Prefix) { case "^": if (version2.VersionTuple == version1.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (major1Greater.IsValueTrue()) { comparison = NpmVersionComparison.GreaterThan; } else if (major1Greater.IsValueFalse()) { comparison = NpmVersionComparison.LessThan; } else if (majorMatch.IsValueTrue()) { if (BoolExtensions.AnyAreValueTrue(patch1Greater, minor1Greater)) { comparison = NpmVersionComparison.GreaterThan; } else if (BoolExtensions.AnyAreValueFalse(patch1Greater, minor1Greater)) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else if (minorMatch.IsValueTrue()) { comparison = NpmVersionComparison.Matches; } else { DebugUtils.Break(); } } break; case "~": if (version2.VersionTuple == version1.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater)) { comparison = NpmVersionComparison.GreaterThan; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater)) { comparison = NpmVersionComparison.LessThan; } else if (minorMatch.IsValueTrue()) { if (patch1Greater.IsValueTrue()) { comparison = NpmVersionComparison.GreaterThan; } else if (patch1Greater.IsValueFalse()) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else if (patchMatch.IsValueTrue()) { comparison = NpmVersionComparison.Matches; } else { DebugUtils.Break(); } } break; case ">": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.LessThan; } break; case "<": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.GreaterThan; } break; case ">=": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.LessThan; } break; case "<=": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.GreaterThan; } break; } // right has the prefix, matching to left. Right in general must be less than or equal to left switch (version2.Prefix) { case "^": if (version2.VersionTuple == version1.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (major1Greater.IsValueTrue()) { comparison = NpmVersionComparison.LessThan; } else if (majorMatch.IsValueTrue()) { if (BoolExtensions.AnyAreValueTrue(patch1Greater, minor1Greater)) { comparison = NpmVersionComparison.LessThan; } else if (BoolExtensions.AnyAreValueFalse(patch1Greater, minor1Greater)) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else if (minorMatch.IsValueTrue()) { comparison = NpmVersionComparison.Matches; } else { DebugUtils.Break(); } } break; case "~": if (version2.VersionTuple == version1.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater)) { comparison = NpmVersionComparison.LessThan; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater)) { comparison = NpmVersionComparison.GreaterThan; } else if (minorMatch.IsValueTrue()) { if (patch1Greater.IsValueTrue()) { comparison = NpmVersionComparison.LessThan; } else if (patch1Greater.IsValueFalse()) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else if (patchMatch.IsValueTrue()) { comparison = NpmVersionComparison.Matches; } else { DebugUtils.Break(); } } break; case ">": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.LessThan; } break; case "<": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.GreaterThan; } break; case ">=": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueTrue(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.GreaterThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.LessThan; } break; case "<=": if (version1.VersionTuple == version2.VersionTuple) { comparison = NpmVersionComparison.Equals | NpmVersionComparison.Matches; } else if (BoolExtensions.AnyAreValueFalse(major1Greater, minor1Greater, patch1Greater)) { comparison = NpmVersionComparison.LessThan | NpmVersionComparison.Matches; } else { comparison = NpmVersionComparison.GreaterThan; } break; } } } /* * public enum NpmVersionComparison * { * NoComparison = 0, * NotEquals = 1, * Equals = 1 << 2, * GreaterThan = 1 << 3, * LessThan = 1 << 4, * Matches = 1 << 5 * } */ Debug.Assert(comparison != NpmVersionComparison.NoComparison); Debug.Assert(!(comparison.HasFlag(NpmVersionComparison.GreaterThan) && comparison.HasFlag(NpmVersionComparison.LessThan))); Debug.Assert(!(comparison.HasFlag(NpmVersionComparison.Equals) && comparison.HasFlag(NpmVersionComparison.NotEquals))); Debug.Assert(!(comparison.HasFlag(NpmVersionComparison.Equals) && comparison.HasFlag(NpmVersionComparison.GreaterThan))); Debug.Assert(!(comparison.HasFlag(NpmVersionComparison.Equals) && comparison.HasFlag(NpmVersionComparison.LessThan))); return(comparison); }
private void VisitChildren(BaseNode node) { foreach (var child in node.ChildNodes) { VisitNode(child); SwitchExtensions.Switch(child, () => child.GetType().Name, SwitchExtensions.Case <DirectiveNode>("DirectiveNode", (directiveNode) => { VisitDirective(directiveNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <MarkupNode> ("MarkupNode", (markupNode) => { VisitMarkup(markupNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <ModelNode>("ModelNode", (modelNode) => { VisitModel(modelNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <RenderNode>("RenderNode", (renderNode) => { VisitRender(renderNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <CodeNode>("CodeNode", (codeNode) => { VisitCode(codeNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <ModelInvocationNode>("ModelInvocationNode", (modelInvocationNode) => { VisitModelInvocation(modelInvocationNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <ViewDataNode>("ViewDataNode", (viewDataNode) => { VisitViewData(viewDataNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <ViewBagNode>("ViewBagNode", (viewBagNode) => { VisitViewBag(viewBagNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <PropertyNode>("PropertyNode", (propertyNode) => { VisitProperty(propertyNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <VariableNode>("VariableNode", (variableNode) => { VisitVariable(variableNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <SectionNode>("SectionNode", (sectionNode) => { VisitSection(sectionNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <MarkupBlockNode>("MarkupBlockNode", (markupBlockNode) => { VisitMarkupBlock(markupBlockNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <CommentNode>("CommentNode", (commentNode) => { VisitComment(commentNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <CodeExpressionNode>("CodeExpressionNode", (codeExpressionNode) => { VisitCodeExpression(codeExpressionNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <HelperExpressionNode>("HelperExpressionNode", (helperExpressionNode) => { VisitHelperExpression(helperExpressionNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <CustomScriptsSectionNode>("CustomScriptsSectionNode", (customScriptsSectionNode) => { VisitCustomScriptsSection(customScriptsSectionNode); DebugUtils.NoOp(); }), SwitchExtensions.Case <ScriptExpressionNode>("ScriptExpressionNode", (scriptExpressionNode) => { VisitScriptExpression(scriptExpressionNode); DebugUtils.NoOp(); }), SwitchExtensions.CaseElse(() => { var a = child; var t = child.GetType().Name; // implementation here or throw error DebugUtils.Break(); }) ); } }
public static void GeneratePage(IBase baseObject, string pagesFolderPath, string pageName, IGeneratorConfiguration generatorConfiguration, IModuleAssembly module, IEnumerable <ModuleImportDeclaration> imports, IModuleAssembly angularModule, List <ManagedList> managedLists, List <GridColumn> gridColumns, bool isComponent) { var host = new TemplateEngineHost(); var pass = generatorConfiguration.CurrentPass; var moduleAssemblyProperties = new AngularModuleAssemblyProperties(baseObject, imports); var parentElement = (IParentBase)baseObject; var childElement = parentElement.ChildElements.Single(); Dictionary <string, object> sessionVariables; FileInfo fileInfo; string fileLocation; string filePath; string output; try { // grid page sessionVariables = new Dictionary <string, object>(); sessionVariables.Add("PageName", pageName); sessionVariables.Add("EntityName", childElement.Name); sessionVariables.Add("IsComponent", isComponent); fileLocation = PathCombine(pagesFolderPath, childElement.Name.ToLower()); filePath = PathCombine(fileLocation, pageName.ToLower() + ".html"); fileInfo = new FileInfo(filePath); output = host.Generate <NavigationGridPageTemplate>(sessionVariables, false); generatorConfiguration.CreateFile(fileInfo, output, FileKind.Project, () => generatorConfiguration.GenerateInfo(sessionVariables, "Navigation Grid Page")); // grid class sessionVariables = new Dictionary <string, object>(); sessionVariables.Add("PageName", pageName); sessionVariables.Add("Authorize", generatorConfiguration.AuthorizedRoles); sessionVariables.Add("EntityName", childElement.Name); sessionVariables.Add("ParentEntityName", parentElement.Name); sessionVariables.Add("IsComponent", isComponent); if (baseObject is IRelationProperty) { var navigationProperty = (IRelationProperty)baseObject; var thisPropertyRef = navigationProperty.ThisPropertyRef; var parentPropertyRef = navigationProperty.ParentPropertyRef; var thisPropertyType = thisPropertyRef.GetScriptTypeName(); var thisShortType = thisPropertyRef.GetShortType().ToLower(); switch (navigationProperty.ThisMultiplicity) { case "*": sessionVariables.Add("EntityParentRefName", baseObject.Parent.Name); sessionVariables.Add("EntityPropertyRefName", thisPropertyRef.Name); break; case "0..1": case "1": DebugUtils.Break(); break; default: DebugUtils.Break(); break; } } sessionVariables.Add("ManagedLists", managedLists); sessionVariables.Add("GridColumns", gridColumns); if (generatorConfiguration.CustomQueries.ContainsKey(baseObject)) { var queriesList = generatorConfiguration.CustomQueries[baseObject]; sessionVariables.Add("CustomQueries", queriesList); } sessionVariables.AddModuleAssemblyProperties(moduleAssemblyProperties); filePath = PathCombine(fileLocation, pageName.ToLower() + ".ts"); fileInfo = new FileInfo(filePath); output = host.Generate <NavigationGridClassTemplate>(sessionVariables, false); module.ExportedComponents = sessionVariables.GetExportedComponents(); module.ForChildFile = generatorConfiguration.CreateFile(moduleAssemblyProperties, fileInfo, output, FileKind.Project, () => generatorConfiguration.GenerateInfo(sessionVariables, "Navigation Grid Class")); // sass sessionVariables = new Dictionary <string, object>(); sessionVariables.Add("PageName", pageName); filePath = PathCombine(fileLocation, pageName.ToLower() + ".scss"); fileInfo = new FileInfo(filePath); output = host.Generate <SassStyleSheetTemplate>(sessionVariables, false); generatorConfiguration.CreateFile(fileInfo, output, FileKind.Project, () => generatorConfiguration.GenerateInfo(sessionVariables, "page \r\n{\r\n}")); } catch (Exception e) { generatorConfiguration.AppGeneratorEngine.WriteError(e.ToString()); } }
public static List <Component> GetComponents(string binariesPath, string projectPath, string targetFramework, string targetAssembly, string productFilePath) { var packageFiles = new List <FileInfo>(); var components = new List <Component>(); var document = XDocument.Load(projectPath); var namespaceManager = new XmlNamespaceManager(new NameTable()); var projectName = XName.Get("p", "http://schemas.microsoft.com/developer/msbuild/2003"); var projectFolder = Path.GetDirectoryName(projectPath); var packagesDirectory = new DirectoryInfo(Path.GetFullPath(Path.Combine(projectFolder, @"..\packages"))); var packageSubDirectories = packagesDirectory.GetDirectories().ToList(); var regex = new Regex(@"(?<framework>[a-z]*)?(?<major>\d)\.?(?<minor>\d)"); var dotNetVersion = Version.Parse(Assembly.GetExecutingAssembly().GetFrameworkVersion()); var binariesDirectory = new DirectoryInfo(binariesPath); IEnumerable <XElement> elementReferences; IEnumerable <XElement> elementPackageReferences; FrameworkVersion targetFrameworkVersion; if (regex.IsMatch(targetFramework)) { var match = regex.Match(targetFramework); var major = match.GetGroupValue("major"); var minor = match.GetGroupValue("minor"); var framework = match.GetGroupValue("framework"); targetFrameworkVersion = new FrameworkVersion(framework, Version.Parse(major + "." + minor)); } else { targetFrameworkVersion = null; DebugUtils.Break(); } packagesDirectory = new DirectoryInfo(Path.GetFullPath(Path.Combine(projectFolder, @"..\..\packages"))); packageSubDirectories.AddRange(packagesDirectory.GetDirectories()); packagesDirectory = new DirectoryInfo(Environment.ExpandEnvironmentVariables(@"%userprofile%\.nuget\packages")); packageSubDirectories.AddRange(packagesDirectory.GetDirectories()); packageSubDirectories = packageSubDirectories.OrderBy(p => p.Name).ToList(); namespaceManager.AddNamespace(projectName.LocalName, projectName.NamespaceName); elementReferences = document.XPathSelectElements("/p:Project/p:ItemGroup/p:Reference", namespaceManager); elementPackageReferences = document.XPathSelectElements("/p:Project/p:ItemGroup/p:PackageReference", namespaceManager); foreach (var elementReference in elementReferences) { var hintPath = elementReference.Element(projectName.Namespace + "HintPath"); if (hintPath != null) { var componentFile = new FileInfo(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(projectPath), hintPath.Value))); if (componentFile.Exists) { packageFiles.Add(componentFile); } } } foreach (var elementPackageReference in elementPackageReferences) { var include = elementPackageReference.Attribute("Include"); var versionElement = elementPackageReference.Element(projectName.Namespace + "Version"); DirectoryInfo packageDirectory; DirectoryInfo packageLibDirectory; if (packageSubDirectories.Any(d => d.Name.AsCaseless() == include.Value + "." + versionElement.Value)) { packageDirectory = packageSubDirectories.Single(d => d.Name.AsCaseless() == include.Value + "." + versionElement.Value); } else if (packageSubDirectories.Any(d => d.Name.AsCaseless() == include.Value && d.GetDirectories().Any(d2 => d2.Name == versionElement.Value))) { packageDirectory = packageSubDirectories.Single(d => d.Name.AsCaseless() == include.Value && d.GetDirectories().Any(d2 => d2.Name == versionElement.Value)); packageDirectory = new DirectoryInfo(Path.Combine(packageDirectory.FullName, versionElement.Value)); } else { packageDirectory = null; DebugUtils.Break(); } packageLibDirectory = new DirectoryInfo(Path.Combine(packageDirectory.FullName, "lib")); if (packageLibDirectory.Exists) { var frameworkVersions = new List <FrameworkVersion>(); FrameworkVersion bestFrameworkVersion; DirectoryInfo componentDirectory; foreach (var frameworkDirectory in packageLibDirectory.GetDirectories()) { regex = new Regex(@"net(?<framework>[a-z]*)?(?<major>\d)\.?(?<minor>\d)"); if (regex.IsMatch(frameworkDirectory.Name)) { var match = regex.Match(frameworkDirectory.Name); var major = match.GetGroupValue("major"); var minor = match.GetGroupValue("minor"); var framework = match.GetGroupValue("framework"); var frameworkVersion = new FrameworkVersion(framework, Version.Parse(major + "." + minor)); if (framework == string.Empty) { framework = "net"; } if (framework == targetFrameworkVersion.Framework) { frameworkVersions.Add(frameworkVersion); } else if (framework == "standard") { } } else { DebugUtils.Break(); } } if (frameworkVersions.Count == 0) { // fallback to standard if none found foreach (var frameworkDirectory in packageLibDirectory.GetDirectories()) { regex = new Regex(@"net(?<framework>[a-z]*)?(?<major>\d)\.?(?<minor>\d)"); if (regex.IsMatch(frameworkDirectory.Name)) { var match = regex.Match(frameworkDirectory.Name); var major = match.GetGroupValue("major"); var minor = match.GetGroupValue("minor"); var framework = match.GetGroupValue("framework"); var frameworkVersion = new FrameworkVersion(framework, Version.Parse(major + "." + minor)); if (framework == "standard" && targetFrameworkVersion.Framework == "net") { componentDirectory = frameworkDirectory; foreach (var componentDll in componentDirectory.GetFiles("*.dll")) { packageFiles.Add(componentDll); } } } else { DebugUtils.Break(); } } } else { bestFrameworkVersion = frameworkVersions.FirstOrDefault(v => v.Framework == targetFrameworkVersion.Framework && v.Version <= dotNetVersion); componentDirectory = new DirectoryInfo(Path.Combine(packageLibDirectory.FullName, string.Format("net{0}{1}", bestFrameworkVersion.Version.Major, bestFrameworkVersion.Version.Minor))); if (!componentDirectory.Exists) { DebugUtils.Break(); } foreach (var componentDll in componentDirectory.GetFiles("*.dll")) { packageFiles.Add(componentDll); } } } } foreach (var binary in binariesDirectory.GetFiles().Where(b => b.Extension.IsOneOf(".dll", ".exe"))) { if (packageFiles.Any(f => f.Name == binary.Name)) { var packageFile = packageFiles.Single(f => f.Name == binary.Name); packageFiles.Remove(packageFile); } if (Path.GetFileNameWithoutExtension(binary.Name).AsCaseless() != targetAssembly) { components.Add(new Component(binary, projectFolder, productFilePath)); } } return(components); }
/// <summary> /// Create the template output /// </summary> public override string TransformText() { this.Write(@"using AbstraX; using HydraDevOps.Services.Providers; using Microsoft.AspNetCore.Hosting; using Newtonsoft.Json.Linq; using System.Collections; using System.Collections.Generic; using System.IO; using Utils; using System.Linq; using System.Net.Http; using System; using ApplicationGenerator.Data.Interfaces; using Microsoft.EntityFrameworkCore; using HydraDevOps.Services.Models; using ApplicationGenerator.Data; using "); #line 34 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.RootNamespace)); #line default #line hidden this.Write(".Services.Models."); #line 34 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.Title)); #line default #line hidden this.Write("Service;\r\nusing ApplicationGenerator.Services;\r\n\r\nnamespace "); #line 37 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.RootNamespace)); #line default #line hidden this.Write(".Services.Providers."); #line 37 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.Title)); #line default #line hidden this.Write("Service\r\n{\r\n public interface I"); #line 39 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.ProviderName)); #line default #line hidden this.Write(" : IWebApiProvider\r\n {\r\n"); #line 41 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" foreach (var serviceMethod in this.ServiceMethods) { this.WriteLineSpaceIndent(8, serviceMethod.InterfaceSignature); } #line default #line hidden this.Write(" }\r\n\r\n [WebApiProvider(typeof(I"); #line 49 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.ProviderName)); #line default #line hidden this.Write("), typeof("); #line 49 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.Title)); #line default #line hidden this.Write("DataContext))]\r\n public class "); #line 50 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.ProviderName)); #line default #line hidden this.Write(" : I"); #line 50 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.ProviderName)); #line default #line hidden this.Write(@" { private dynamic jsonConfigObject; private string urlBase; public Dictionary<string, string> ConfigVariables { get; } private IHandlebarsParser handlebarsParser; public AzureDevOpsServiceProvider(IWebHostEnvironment environment, IHandlebarsParser handlebarsParser) { var rootPath = environment.WebRootPath; var configFile = Path.Combine(rootPath, "); #line 60 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.ConfigPathString)); #line default #line hidden this.Write(@"); this.ConfigVariables = new Dictionary<string, string>(); this.handlebarsParser = handlebarsParser; using (var reader = new StreamReader(configFile)) { this.jsonConfigObject = reader.ReadJson<object>(); foreach (var pair in jsonConfigObject) { this.ConfigVariables.Add(pair.Name, (string) pair.Value); } } urlBase = this.ConfigVariables[""urlBase""]; } "); #line 78 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" foreach (var serviceMethod in this.ServiceMethods) { #line default #line hidden this.Write(" "); #line 82 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(serviceMethod.MethodSignature)); #line default #line hidden this.Write(" \r\n {\r\n var decodedId = id.FromBase64ToString();\r\n v" + "ar variables = this.GetVariables(decodedId);\r\n var accessToken = vari" + "ables[\"accessToken\"];\r\n var authorizationKey = (\":\" + accessToken).To" + "Base64();\r\n"); #line 88 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" foreach (var methodVariablePair in serviceMethod.MethodVariables) { this.WriteLineFormatSpaceIndent(12, "var {0} = {1};", methodVariablePair.Key, methodVariablePair.Value); } #line default #line hidden this.Write("\r\n using (var client = new HttpClient())\r\n {\r\n " + " var resultPath = \""); #line 97 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(serviceMethod.ResultPath)); #line default #line hidden this.Write(@"""; // comes from line 30 (resultPath) in json HttpRequestMessage request; JObject jObject = null; JArray jArray; string resultString; client.DefaultRequestHeaders.Add(""Authorization"", ""Basic "" + authorizationKey); "); #line 105 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" switch (serviceMethod.HttpMethod) { case "GET": #line default #line hidden this.Write(@" request = new HttpRequestMessage(new HttpMethod(""GET""), uri); // GET because of List ServiceMethodKind resultString = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result; try { jObject = JObject.Parse(resultString); } catch (Exception ex) { throw new InvalidDataException(""Invalid response: \r\n"" + resultString); } "); #line 123 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" break; default: DebugUtils.Break(); break; } switch (serviceMethod.ReturnType) { case "IEnumerable<dynamic>": #line default #line hidden this.Write(" jArray = (JArray) jObject.SelectToken(resultPath);\r\n\r\n " + " foreach (var obj in jArray)\r\n {\r\n var jIt" + "emObject = (JObject)obj;\r\n var itemId = "); #line 140 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(serviceMethod.UniqueIdFactory(new string[] { "decodedId", "jItemObject[\"id\"]" }))); #line default #line hidden this.Write(" // comes from line 47 (keyPattern) in json\r\n\r\n jObject = (J" + "Object)obj;\r\n\r\n jObject.AddFirst(new JProperty(\"uniqueid\", it" + "emId.ToBase64()));\r\n"); #line 145 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" foreach (var returnPropertyPair in serviceMethod.ReturnProperties) { #line default #line hidden this.Write(" jObject.Add(new JProperty(\""); #line 149 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(returnPropertyPair.Key)); #line default #line hidden this.Write("\", "); #line 149 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(returnPropertyPair.Value)); #line default #line hidden this.Write("));\r\n"); #line 150 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" } #line default #line hidden this.Write("\r\n yield return jObject.ToObject<dynamic>();\r\n " + "}\r\n }\r\n }\r\n"); #line 158 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" break; default: DebugUtils.Break(); break; } } #line default #line hidden this.Write("\r\n public IEnumerator CreateEntitySetEnumerator(DbContext context, string " + "setName, string id)\r\n {\r\n var method = this.GetType().GetMetho" + "d(\"List\" + setName);\r\n var results = (IEnumerable) method.Invoke(this" + ", new object[] { id });\r\n\r\n return results.GetEnumerator();\r\n " + "}\r\n\r\n public IEnumerator CreateNavigationPropertyEnumerator(DbContext con" + "text, string navigationProperty, string id)\r\n {\r\n var method =" + " this.GetType().GetMethod(\"List\" + navigationProperty);\r\n var results" + " = (IEnumerable) method.Invoke(this, new object[] { id });\r\n\r\n return" + " results.GetEnumerator();\r\n }\r\n\r\n public IEnumerator CreateCastEnu" + "merator(DbContext context, string fromType, string toType, string id)\r\n {" + "\r\n var method = this.GetType().GetMethod(\"Cast\" + fromType + \"To\");\r\n" + " var results = (IEnumerable) method.Invoke(this, new object[] { id, t" + "oType });\r\n\r\n return results.GetEnumerator();\r\n }\r\n\r\n p" + "ublic dynamic CreateNavigationPropertyObject(DbContext context, string navigatio" + "nProperty, string id)\r\n {\r\n var method = this.GetType().GetMet" + "hod(\"Get\" + navigationProperty);\r\n var dynamic = (IEnumerable) method" + ".Invoke(this, new object[] { id });\r\n\r\n return dynamic;\r\n }\r\n\r" + "\n public string GetIdBase()\r\n {\r\n return this.ConfigVar" + "iables[\"idBase\"];\r\n }\r\n\r\n public NamingConvention GetNamingConvent" + "ion()\r\n {\r\n return NamingConvention."); #line 208 "D:\MC\CloudIDEaaS\root\ApplicationGenerator\Generators\Server\WebAPIRestServiceProvider\WebAPIRestServiceProviderClassTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(this.NamingConvention.ToString())); #line default #line hidden this.Write("; // comes from line 5 (namingConvention) in json\r\n }\r\n }\r\n}"); return(this.GenerationEnvironment.ToString()); }
public bool Process(Dictionary <string, IWorkspaceTokenContentHandler> tokenContentHandlers, IWorkspaceTemplate workspaceTemplate, Guid projectType, string appName, string rawFileRelativePath, string outputFileName, string content, IGeneratorConfiguration generatorConfiguration) { var processing = true; var options = CSharpParseOptions.Default.WithPreprocessorSymbols(supportedTokens); IEnumerable <Diagnostic> diagnostics = null; this.OutputContent = content; while (processing) { var syntaxTree = CSharpSyntaxTree.ParseText(content, options); var root = syntaxTree.GetCompilationUnitRoot(); var walker = new DirectiveSyntaxWalker(supportedTokens); List <IfDirectiveBlock> generatorDirectiveBlocks; walker.Visit(root); generatorDirectiveBlocks = walker.GeneratorDirectiveBlocks; if (generatorDirectiveBlocks.Count > 0) { var generatorDirectiveBlock = generatorDirectiveBlocks.First(); var childNodes = generatorDirectiveBlock.ChildNodes.Reverse(); IfDirectiveNodeBase branchTakenNode = null; foreach (var childNode in childNodes.Where(n => !n.IsOfType <EndIfBlock>())) { if (childNode.BranchTaken.Value) { branchTakenNode = childNode; } else if (branchTakenNode != null) { var offsetLength = branchTakenNode.Node.FullSpan.Length; var length = childNode.Length - offsetLength; content = content.Remove(childNode.Start, length); childNodes.ShiftUp(childNode.Start, length); } else { content = content.Remove(childNode.Start, childNode.Length); childNodes.ShiftUp(childNode.Start, childNode.Length); } } if (branchTakenNode != null) { var startSpan = new TextSpan(branchTakenNode.Node.FullSpan.Start + branchTakenNode.ShiftAmount, branchTakenNode.Node.FullSpan.Length); var endSpan = new TextSpan(branchTakenNode.NextNode.Node.FullSpan.Start + branchTakenNode.ShiftAmount, branchTakenNode.NextNode.Node.FullSpan.Length); switch (branchTakenNode) { case IfBlock ifBlock: if (tokenContentHandlers.ContainsKey(ifBlock.Condition)) { var tokenContentHandler = tokenContentHandlers[ifBlock.Condition]; var insertContent = tokenContentHandler.Content; content = content.Remove(ifBlock.Start, ifBlock.Length); content = content.Insert(ifBlock.Start, insertContent); } else { content = content.Remove(endSpan.Start, endSpan.Length); content = content.Remove(startSpan.Start, startSpan.Length); } break; case ElifBlock elifBlock: DebugUtils.Break(); // untested if (tokenContentHandlers.ContainsKey(elifBlock.Condition)) { var tokenContentHandler = tokenContentHandlers[elifBlock.Condition]; var insertContent = tokenContentHandler.Content; content = content.Remove(elifBlock.Start, elifBlock.Length); content = content.Insert(elifBlock.Start, insertContent); } else { content = content.Remove(endSpan.Start, endSpan.Length); content = content.Remove(startSpan.Start, startSpan.Length); } break; case ElseBlock elseBlock: content = content.Remove(endSpan.Start, endSpan.Length); content = content.Remove(startSpan.Start, startSpan.Length); break; } } } else { processing = false; } diagnostics = syntaxTree.GetDiagnostics(); } if (diagnostics.Count() > 0) { DebugUtils.Break(); } this.OutputContent = content; return(true); }
protected override void HandleCommand(CommandPacket commandPacket) { try { switch (commandPacket.Command) { case ServerCommands.GENERATE: { var kind = commandPacket.Arguments.Single(a => a.Key == "Kind").Value; var generatorKind = EnumUtils.GetValue <GeneratorKind>(((string)kind).ToTitleCase()); if (generatorKind == GeneratorKind.App) { var entitiesProjectPath = commandPacket.Arguments.Single(a => a.Key == "EntitiesProjectPath").Value; var servicesProjectPath = commandPacket.Arguments.Single(a => a.Key == "ServicesProjectPath").Value; var generatorPass = EnumUtils.GetValue <GeneratorPass>((string)commandPacket.Arguments.Single(a => a.Key == "GeneratorPass").Value); var noFileCreation = bool.Parse(commandPacket.Arguments.Single(a => a.Key == "NoFileCreation").Value.ToString()); var projectFolderRoot = currentWorkingDirectory; object packageCachePath = null; if (commandPacket.Arguments.Any(a => a.Key == "PackageCachePath")) { packageCachePath = commandPacket.Arguments.Single(a => a.Key == "PackageCachePath").Value; } generatorHandler = new GeneratorHandler(); webApiService.GeneratorHandler = generatorHandler; generatorHandler.SuppressDebugOutput = true; generatorHandler.Execute(new Dictionary <string, object> { { "GeneratorKind", generatorKind }, { "EntitiesProjectPath", entitiesProjectPath }, { "ServicesProjectPath", servicesProjectPath }, { "PackageCachePath", packageCachePath }, { "GeneratorMode", GeneratorMode.RedirectedConsole }, { "GeneratorOptions", new RedirectedGeneratorOptions(outputWriter, errorWriter, generatorPass, noFileCreation) } }); } else if (generatorKind == GeneratorKind.BusinessModel) { var generatorPass = EnumUtils.GetValue <GeneratorPass>((string)commandPacket.Arguments.Single(a => a.Key == "GeneratorPass").Value); var noFileCreation = bool.Parse(commandPacket.Arguments.Single(a => a.Key == "NoFileCreation").Value.ToString()); var templateFile = commandPacket.Arguments.Single(a => a.Key == "TemplateFile").Value.ToString(); var projectFolderRoot = currentWorkingDirectory; generatorHandler = new GeneratorHandler(); webApiService.GeneratorHandler = generatorHandler; generatorHandler.SuppressDebugOutput = true; generatorHandler.Execute(new Dictionary <string, object> { { "GeneratorKind", generatorKind }, { "TemplateFile", templateFile }, { "GeneratorMode", GeneratorMode.RedirectedConsole }, { "GeneratorOptions", new RedirectedGeneratorOptions(outputWriter, errorWriter, generatorPass, noFileCreation) } }); } else if (generatorKind == GeneratorKind.Entities) { var generatorPass = EnumUtils.GetValue <GeneratorPass>((string)commandPacket.Arguments.Single(a => a.Key == "GeneratorPass").Value); var noFileCreation = bool.Parse(commandPacket.Arguments.Single(a => a.Key == "NoFileCreation").Value.ToString()); var templateFile = commandPacket.Arguments.Single(a => a.Key == "TemplateFile").Value.ToString(); var jsonFile = commandPacket.Arguments.Single(a => a.Key == "JsonFile").Value.ToString(); var businessModelFile = commandPacket.Arguments.Single(a => a.Key == "BusinessModelFile").Value.ToString(); var entitiesProjectPath = commandPacket.Arguments.Single(a => a.Key == "EntitiesProjectPath").Value; var projectFolderRoot = currentWorkingDirectory; generatorHandler = new GeneratorHandler(); webApiService.GeneratorHandler = generatorHandler; generatorHandler.SuppressDebugOutput = true; generatorHandler.Execute(new Dictionary <string, object> { { "GeneratorKind", generatorKind }, { "TemplateFile", templateFile }, { "JsonFile", jsonFile }, { "BusinessModelFile", businessModelFile }, { "EntitiesProjectPath", entitiesProjectPath }, { "GeneratorMode", GeneratorMode.RedirectedConsole }, { "GeneratorOptions", new RedirectedGeneratorOptions(outputWriter, errorWriter, generatorPass, noFileCreation) } }); } else if (generatorKind == GeneratorKind.Workspace) { var generatorPass = EnumUtils.GetValue <GeneratorPass>((string)commandPacket.Arguments.Single(a => a.Key == "GeneratorPass").Value); var noFileCreation = bool.Parse(commandPacket.Arguments.Single(a => a.Key == "NoFileCreation").Value.ToString()); var appName = commandPacket.Arguments.Single(a => a.Key == "AppName").Value.ToString(); var appDescription = commandPacket.Arguments.Single(a => a.Key == "AppDescription").Value.ToString(); var projectFolderRoot = currentWorkingDirectory; generatorHandler = new GeneratorHandler(); webApiService.GeneratorHandler = generatorHandler; generatorHandler.SuppressDebugOutput = true; generatorHandler.Execute(new Dictionary <string, object> { { "GeneratorKind", generatorKind }, { "AppName", appName }, { "AppDescription", appDescription }, { "GeneratorMode", GeneratorMode.RedirectedConsole }, { "GeneratorOptions", new RedirectedGeneratorOptions(outputWriter, errorWriter, generatorPass, noFileCreation) } }); } } break; case ServerCommands.TERMINATE: { if (generatorHandler != null) { var config = generatorHandler.GeneratorConfiguration; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, "Terminating"); outputWriter.WriteJsonCommand(commandPacket, null); config.StopServices(); outputWriter.WriteLine(Environment.NewLine); } else { commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, "Terminating"); outputWriter.WriteJsonCommand(commandPacket); } this.Stop(); } break; case ServerCommands.CONNECT: { commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, "Connected successfully"); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.PING: { commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, "Success"); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_VERSION: { var version = Assembly.GetEntryAssembly().GetAttributes().Version; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, version); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FOLDER: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var folder = (Folder)config.FileSystem[relativePath]; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, folder); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FILE: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var file = (File)config.FileSystem[relativePath]; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, file); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FOLDERS: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var folder = (Folder)config.FileSystem[relativePath]; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, folder.Folders.ToArray()); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FILES: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var folder = (Folder)config.FileSystem[relativePath]; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, folder.Files.ToArray()); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_PACKAGE_INSTALLS: { var config = generatorHandler.GeneratorConfiguration; var packageInstalls = config.PackageInstalls; // kn todo - comment // packageInstalls = packageInstalls.Randomize().Take(5).ToList(); // packageInstalls = new List<string> { "@gracesnoh/tiny" }; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, packageInstalls.ToArray()); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_PACKAGE_DEV_INSTALLS: { var config = generatorHandler.GeneratorConfiguration; var packageDevInstalls = config.PackageDevInstalls; // kn todo - comment // packageDevInstalls = packageDevInstalls.Randomize().Take(2).ToList(); // packageDevInstalls = new List<string> { "@gracesnoh/tiny" }; commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, packageDevInstalls.ToArray()); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_CACHE_STATUS: { var config = generatorHandler.GeneratorConfiguration; var mode = (string)commandPacket.Arguments.Single(a => a.Key == "mode").Value; var cacheStatus = config.GetCacheStatus(mode, true); commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, cacheStatus); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.SET_INSTALL_STATUS: { var config = generatorHandler.GeneratorConfiguration; var status = (string)commandPacket.Arguments.Single(a => a.Key == "status").Value; var result = config.SetInstallStatus(status); commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, result); outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FILE_ICON: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var file = (File)config.FileSystem[relativePath]; var bitmap = file.Icon.ToBitmap(); bitmap.MakeTransparent(Color.Black); using (var stream = new System.IO.MemoryStream()) { bitmap.Save(stream, ImageFormat.Gif); stream.Flush(); stream.Rewind(); commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, stream.ToBase64() + Environment.NewLine.Repeat(2)); } outputWriter.WriteJsonCommand(commandPacket); } break; case ServerCommands.GET_FILE_CONTENTS: { var relativePath = (string)commandPacket.Arguments.Single(a => a.Key == "relativePath").Value; var config = generatorHandler.GeneratorConfiguration; var file = (File)config.FileSystem[relativePath]; var fileInfo = file.SystemLocalFile; byte[] contents; if (fileInfo.Exists) { contents = System.IO.File.ReadAllBytes(fileInfo.FullName); } else { contents = file.Info.ToString().ToBytes(); } using (var stream = new System.IO.MemoryStream()) { stream.Write(contents, 0, contents.Length); stream.Flush(); stream.Rewind(); commandPacket = new CommandPacket(commandPacket.Command, commandPacket.SentTimestamp, stream.ToBase64() + Environment.NewLine.Repeat(2)); } outputWriter.WriteJsonCommand(commandPacket); } break; default: DebugUtils.Break(); break; } } catch (Exception ex) { #if DEBUG errorWriter.Write(ex.ToString()); #else errorWriter.Write(ex.Message); #endif errorWriter.Flush(); Environment.Exit(1); } }
private void VisitEnter <T>(T node, string contentPart) where T : SyntaxTreeNode { var line = node.Start.LineIndex; if (node is Block) { var block = (Block)(object)node; var type = block.Type; switch (type) { case BlockType.Markup: break; case BlockType.Statement: break; case BlockType.Expression: break; case BlockType.Section: break; case BlockType.Directive: break; case BlockType.Comment: break; default: DebugUtils.Break(); break; } } else if (node is Span) { var span = (Span)(object)node; var kind = span.Kind; switch (kind) { case SpanKind.Code: break; case SpanKind.Markup: break; case SpanKind.MetaCode: break; case SpanKind.Transition: break; case SpanKind.Comment: break; default: DebugUtils.Break(); break; } } else { DebugUtils.Break(); } }