Exemple #1
0
        private static string BuildDefaultKeySetFile(KeySet keySet)
        {
            var sb = new IndentingStringBuilder();

            sb.AppendLine(GetHeader());
            sb.AppendLine();

            sb.AppendLine("using System;");
            sb.AppendLine();

            sb.AppendLine("namespace LibHac.Common.Keys");
            sb.AppendLineAndIncrease("{");

            sb.AppendLine("internal static partial class DefaultKeySet");
            sb.AppendLineAndIncrease("{");

            BuildArray(sb, "RootKeysDev", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._rootKeysDev));
            BuildArray(sb, "RootKeysProd", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._rootKeysProd));
            BuildArray(sb, "KeySeeds", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._keySeeds));
            BuildArray(sb, "StoredKeysDev", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._storedKeysDev));
            BuildArray(sb, "StoredKeysProd", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._storedKeysProd));
            BuildArray(sb, "DerivedKeysDev", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._derivedKeysDev));
            BuildArray(sb, "DerivedKeysProd", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._derivedKeysProd));
            BuildArray(sb, "DeviceKeys", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._deviceKeys));
            BuildArray(sb, "RsaSigningKeysDev", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._rsaSigningKeysDev));
            BuildArray(sb, "RsaSigningKeysProd", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._rsaSigningKeysProd));
            BuildArray(sb, "RsaKeys", SpanHelpers.AsReadOnlyByteSpan(in keySet.KeyStruct._rsaKeys));

            sb.DecreaseAndAppendLine("}");
            sb.DecreaseAndAppendLine("}");

            return(sb.ToString());
        }
Exemple #2
0
        private static void PrintResult(IndentingStringBuilder sb, string moduleName, ResultInfo result)
        {
            string descriptionArgs;

            if (result.IsRange)
            {
                descriptionArgs = $"{result.DescriptionStart}, {result.DescriptionEnd}";
            }
            else
            {
                descriptionArgs = $"{result.DescriptionStart}";
            }

            sb.AppendLine(GetXmlDoc(result));

            string resultCtor = $"new Result.Base(Module{moduleName}, {descriptionArgs});";

            sb.Append($"public static Result.Base {result.Name} ");

            if (EstimateCilSize(result) > InlineThreshold)
            {
                sb.AppendLine($"{{ [MethodImpl(MethodImplOptions.AggressiveInlining)] get => {resultCtor} }}");
            }
            else
            {
                sb.AppendLine($"=> {resultCtor}");
            }
        }
Exemple #3
0
        private void AppendLine(IndentingStringBuilder sb, BTNode node, string line)
        {
            if (tickedLastFrame[node.index])
            {
                if (node is ConditionalNode conditionalNode)
                {
                    sb.Append($"<color={(conditionalNode.checkPassed ? "green" : "red")}>");
                }
                else if (node is IfNodeSimple ifNode)
                {
                    sb.Append($"<color={(ifNode.CheckPassed ? "green" : "red")}>");
                }
                sb.Append("<b>");
            }

            sb.Append(line);
            if (tickedLastFrame[node.index])
            {
                sb.Append("</b>");
                if (node is ConditionalNode || node is IfNodeSimple)
                {
                    sb.Append("</color>");
                }
            }

            sb.AppendLine();

            if (node is RunSubtree subtree && subtree.currentSubtree != null)
            {
                sb.Indents++;
                subtree.currentSubtree.ShowAsString(sb);
                sb.Indents--;
            }
        }
 public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
 {
     foreach (var n in Nodes)
     {
         n.Codegen(cil, sb);
     }
 }
Exemple #5
0
        private static void BuildArray(IndentingStringBuilder sb, string name, ReadOnlySpan <byte> data)
        {
            sb.AppendSpacerLine();
            sb.Append($"private static ReadOnlySpan<byte> {name} => new byte[]");

            if (data.IsZeros())
            {
                sb.AppendLine(" { };");
                return;
            }

            sb.AppendLine();
            sb.AppendLineAndIncrease("{");

            for (int i = 0; i < data.Length; i++)
            {
                if (i % 16 != 0)
                {
                    sb.Append(" ");
                }
                sb.Append($"0x{data[i]:x2}");

                if (i != data.Length - 1)
                {
                    sb.Append(",");
                    if (i % 16 == 15)
                    {
                        sb.AppendLine();
                    }
                }
            }

            sb.AppendLine();
            sb.DecreaseAndAppendLine("};");
        }
Exemple #6
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            if (cil.CurrentFunction == null)
            {
                throw new NotImplementedException("TODO: Exception for return not in function");
            }
            var funcType = cil.CurrentFunction.TryInferType(cil);

            if (ReturnExpression == null)
            {
                if (funcType != "void")
                {
                    throw new CILTypeMismatchException(SourceInfo, funcType, "void");
                }
                sb.LineDecl(SourceInfo);
                sb.AppendLine("return;");
            }
            else
            {
                var retType = ReturnExpression.TryInferType(cil);
                if ((!CTypes.IsIntegerType(retType) && !CTypes.IsIntegerType(funcType)) &&
                    retType != funcType)
                {
                    throw new CILTypeMismatchException(SourceInfo, funcType, retType);
                }
                ReturnExpression.Codegen(cil, sb);
                sb.LineDecl(SourceInfo);
                sb.AppendLine(string.Format("return {0};", cil.LastUsedVar));
            }
        }
Exemple #7
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            cil.PushScope();
            sb.AppendLine("{");
            sb.Indent();

            Condition.Codegen(cil, sb);
            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("if ({0})", cil.LastUsedVar));
            sb.AppendLine("{");
            sb.Indent();
            foreach (var stmt in TrueBranch)
            {
                stmt.Codegen(cil, sb);
            }
            sb.Dedent();
            sb.AppendLine("}");
            if (FalseBranch.Count > 0)
            {
                sb.AppendLine("else");
                sb.AppendLine("{");
                sb.Indent();
                foreach (var stmt in FalseBranch)
                {
                    stmt.Codegen(cil, sb);
                }
                sb.Dedent();
                sb.AppendLine("}");
            }

            sb.Dedent();
            sb.AppendLine("}");
            cil.PopScope();
        }
        public string GenerateWebApiControllerPartialMethods(
            string namespacePostfix,
            string classNamespace,
            string baseControllerName,
            string efEntityNamespacePrefix,
            string efEntityNamespace,
            string dbContextName,
            IEntityType entity,
            IList <IEntityNavigation> excludedNavigationProperties,
            bool allowUpsertDuringPut)
        {
            var className = $"{Inflector.Pluralize(entity.ClrType.Name)}{namespacePostfix}Controller";

            var sb = new IndentingStringBuilder();

            var usings = new List <NamespaceItem>
            {
                new NamespaceItem("CodeGenHero.Repository"),
                //new NamespaceItem("Microsoft.EntityFrameworkCore"),
                //new NamespaceItem("System.Linq"),
                new NamespaceItem(efEntityNamespacePrefix, efEntityNamespace)
            };

            sb.Append(GenerateHeader(usings, classNamespace));

            sb.AppendLine($"\tpublic partial class {className} : {baseControllerName}");
            sb.AppendLine("\t{");

            sb.Append(GeneratePartialMethods(dbContextName: dbContextName, entity: entity,
                                             efEntityNamespacePrefix: efEntityNamespacePrefix, excludedNavigationProperties: excludedNavigationProperties,
                                             allowUpsertDuringPut: allowUpsertDuringPut));

            return(sb.ToString());
        }
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var tmp = NameGenerator.NewTemp();

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("{0} {1} = {2:R}", TryInferType(cil), tmp, Number));
            cil.LastUsedVar = tmp;
        }
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            What.Codegen(cil, sb);
            var id    = cil.LastUsedVar;
            var deref = string.Format("(*({0}))", id);

            cil.LastUsedVar = deref;
        }
Exemple #11
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            Value.Codegen(cil, sb);
            var valTmp = cil.LastUsedVar;

            Destination.Codegen(cil, sb);
            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("{0} = {1};", cil.LastUsedVar, valTmp));
        }
        public string GenerateGet(IEntityType entity, string tableName, string entityTypeName)
        {
            IndentingStringBuilder sb = new IndentingStringBuilder(2);

            sb.AppendLine("[HttpGet]");
            sb.AppendLine($"[VersionedRoute(template: \"{Inflector.Pluralize(entity.ClrType.Name)}\", allowedVersion: 1, Name = GET_LIST_ROUTE_NAME)]");
            sb.AppendLine("#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously");
            sb.AppendLine("public async Task<IHttpActionResult> Get(string sort = null,");
            sb.AppendLine("string fields = null, string filter = null, int page = 1, int pageSize = maxPageSize)");
            sb.AppendLine("#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously");
            sb.AppendLine("{");
            sb.AppendLine("try");
            sb.AppendLine("{");
            sb.AppendLine("if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }");
            sb.AppendLine(string.Empty);
            sb.AppendLine("var fieldList = GetListByDelimiter(fields);");
            sb.AppendLine("bool childrenRequested = false; // TODO: set this based upon actual fields requested.");
            sb.AppendLine(string.Empty);
            sb.AppendLine("var filterList = GetListByDelimiter(filter);");
            sb.AppendLine($"var dbItems = Repo.GetQueryable_{tableName}().AsNoTracking();");
            sb.AppendLine($"RunCustomLogicAfterGetQueryableList(ref dbItems, ref filterList);");
            sb.AppendLine($"dbItems = dbItems.ApplyFilter(filterList);");
            sb.AppendLine($"dbItems = dbItems.ApplySort(sort ?? (typeof({entityTypeName}).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)).First().Name);");
            sb.AppendLine(string.Empty);
            sb.AppendLine("if (pageSize > maxPageSize)");
            sb.AppendLine("{ // ensure the page size isn't larger than the maximum.");
            sb.AppendLine("pageSize = maxPageSize;");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);
            sb.AppendLine("var urlHelper = new UrlHelper(Request);");
            sb.AppendLine("PageData paginationHeader = BuildPaginationHeader(urlHelper, GET_LIST_ROUTE_NAME, page: page, totalCount: dbItems.Count(), pageSize: pageSize, sort: sort);");
            sb.AppendLine("HttpContext.Current.Response.Headers.Add(\"X-Pagination\", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader));");
            sb.AppendLine(string.Empty);
            sb.AppendLine("// return result");
            sb.AppendLine("return Ok(dbItems");
            sb.AppendLine(".Skip(pageSize * (page - 1))");
            sb.AppendLine(".Take(pageSize)");
            sb.AppendLine(".ToList()");
            sb.AppendLine(".Select(x => _factory.CreateDataShapedObject(x, fieldList, childrenRequested)));");
            sb.AppendLine("}");
            sb.AppendLine("catch (Exception ex)");
            sb.AppendLine("{");
            sb.AppendLine("Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,");
            sb.AppendLine("\texception: ex,");
            sb.AppendLine("\tmessage: \"Unable to get object via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine("if (System.Diagnostics.Debugger.IsAttached)");
            sb.AppendLine("\tSystem.Diagnostics.Debugger.Break();");
            sb.AppendLine(string.Empty);
            sb.AppendLine("return InternalServerError();");
            sb.AppendLine("}");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);
            return(sb.ToString());
        }
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            Subscription.Codegen(cil, sb);
            var subTmp = cil.LastUsedVar;

            Pointer.Codegen(cil, sb);
            var sub = string.Format("{0}[{1}]", cil.LastUsedVar, subTmp);

            cil.LastUsedVar = sub;
        }
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var ty        = Thing.TryInferType(cil);
            var separator = CTypes.IsPointerType(ty) ? "->" : ".";
            var @struct   = cil.SymTable.LookupStruct(ty);
            // TODO: Handle key not found exception
            var member = @struct.Members[Member];

            Thing.Codegen(cil, sb);
            var thingVar = cil.LastUsedVar;

            cil.LastUsedVar = string.Format("{0}{1}{2}", thingVar, separator, member.Name);
        }
Exemple #15
0
 public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
 {
     if (Op == CondType.And)
     {
         CodegenAnd(cil, sb);
         return;
     }
     if (Op == CondType.Or)
     {
         CodegenOr(cil, sb);
         return;
     }
     throw new NotImplementedException();
 }
Exemple #16
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            Referencing.Codegen(cil, sb);
            var tmp    = cil.LastUsedVar;
            var newTmp = NameGenerator.NewTemp();

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format(
                              "{0} {1} = (&({2}));",
                              TryInferType(cil),
                              newTmp,
                              tmp));
            cil.LastUsedVar = newTmp;
        }
Exemple #17
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            Lhs.Codegen(cil, sb);
            var lhsTmp = cil.LastUsedVar;

            Rhs.Codegen(cil, sb);
            var rhsTmp = cil.LastUsedVar;

            var tmp = NameGenerator.NewTemp();

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("{0} {1} = {2} {3} {4};", TryInferType(cil), tmp, lhsTmp, OpString(), rhsTmp));
            cil.LastUsedVar = tmp;
        }
        public string GenerateDelete(IEntityType entity)
        {
            string keylist    = string.Join("}/{", entity.FindPrimaryKey());
            string classmodel = MakeModel(entity.FindPrimaryKey(), "", "", ", ", false, false, lowercaseVariableName: false);
            //string signature = table.Signature("");
            IndentingStringBuilder sb = new IndentingStringBuilder(2);

            sb.AppendLine("[HttpDelete]");
            sb.AppendLine($"[VersionedRoute(template: \"{Inflector.Pluralize(entity.ClrType.Name)}/{{{GetSignatureWithoutFieldTypes("", entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)}}}\", allowedVersion: 1)]");
            sb.AppendLine($"public async Task<IHttpActionResult> Delete({GetSignatureWithFieldTypes("", entity.FindPrimaryKey())})");
            sb.AppendLine("{");
            sb.AppendLine("try");
            sb.AppendLine("{");
            sb.AppendLine("if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"var result = await Repo.Delete_{entity.ClrType.Name}Async({GetSignatureWithoutFieldTypes("", entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)});");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"if (result.Status == cghEnums.RepositoryActionStatus.Deleted)");
            sb.AppendLine("{");
            sb.AppendLine("return StatusCode(HttpStatusCode.NoContent);");
            sb.AppendLine("}");
            sb.AppendLine($"else if (result.Status == cghEnums.RepositoryActionStatus.NotFound)");
            sb.AppendLine("{");
            sb.AppendLine("return NotFound();");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);
            sb.AppendLine("Log.LogWarning(eventId: (int)coreEnums.EventId.Warn_WebApi,");
            sb.AppendLine("\texception: result.Exception,");
            sb.AppendLine("\tmessage: \"Unable to delete object via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine("return BadRequest();");
            sb.AppendLine("}");
            sb.AppendLine("catch (Exception ex)");
            sb.AppendLine("{");
            sb.AppendLine("Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,");
            sb.AppendLine("\texception: ex,");
            sb.AppendLine("\tmessage: \"Unable to delete object via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine("if (System.Diagnostics.Debugger.IsAttached)");
            sb.AppendLine("\tSystem.Diagnostics.Debugger.Break();");
            sb.AppendLine(string.Empty);
            sb.AppendLine("return InternalServerError();");
            sb.AppendLine("}");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);
            return(sb.ToString());
        }
 public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
 {
     cil.DeclareLocalVariable(this);
     if (AssigningValue == null)
     {
         sb.AppendLine(GetDeclaration() + ";");
     }
     else
     {
         sb.LineDecl(SourceInfo);
         AssigningValue.Codegen(cil, sb);
         var tmp = cil.LastUsedVar;
         sb.AppendLine(string.Format("{0} = {1};", GetDeclaration(), tmp));
     }
 }
Exemple #20
0
        public string GenerateApiStatusController(List <NamespaceItem> usingNamespaceItems, string classnamePrefix, string classNamespace, string repositoryname)
        {
            string className = $"{classnamePrefix}APIStatusController";
            var    sb        = new IndentingStringBuilder();

            sb.Append(GenerateUsings(usingNamespaceItems));

            sb.AppendLine(string.Empty);
            sb.AppendLine($"namespace {classNamespace}");
            sb.AppendLine("{");
            sb.AppendLine($"public partial class {className} : {classnamePrefix}BaseApiController");
            sb.AppendLine("{");

            sb.AppendLine($"public {classnamePrefix}APIStatusController(ILogger<{className}> log, {repositoryname} repository)");
            sb.AppendLine("\t: base(log, repository)");
            sb.AppendLine("{");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);

            sb.AppendLine("[HttpGet]");
            sb.AppendLine($"[VersionedRoute(template: \"APIStatus\", allowedVersion: 1, Name = \"{classnamePrefix}APIStatus\")]");
            sb.AppendLine("#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously");
            sb.AppendLine("public async Task<IHttpActionResult> Get()");
            sb.AppendLine("#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously");

            sb.AppendLine("{");
            sb.AppendLine("try");
            sb.AppendLine("{");
            sb.AppendLine("var version = this.GetType().Assembly.GetName().Version;");
            sb.AppendLine("return Ok(version);");
            sb.AppendLine("}");
            sb.AppendLine("catch (Exception ex)");
            sb.AppendLine("{");
            sb.AppendLine($"Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,");
            sb.AppendLine("\texception: ex,");
            sb.AppendLine("\tmessage: \"Unable to get status via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine("if (System.Diagnostics.Debugger.IsAttached)");
            sb.AppendLine("\tSystem.Diagnostics.Debugger.Break();");
            sb.AppendLine(string.Empty);
            sb.AppendLine("return InternalServerError();");
            sb.AppendLine("}");
            sb.AppendLine("}");
            sb.AppendLine("}");
            sb.AppendLine("}");
            return(sb.ToString());
        }
Exemple #21
0
 public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
 {
     sb.LineDecl(SourceInfo);
     sb.AppendLine(GetDeclaration());
     sb.AppendLine("{");
     cil.PushScope();
     sb.Indent();
     foreach (var kvp in Members)
     {
         sb.LineDecl(SourceInfo);
         kvp.Value.Codegen(cil, sb);
     }
     sb.Dedent();
     cil.PopScope();
     sb.AppendLine("};");
 }
        public string GenerateGetByPK(IEntityType entity, string tableName)
        {
            string keylist   = string.Join("}/{", entity.GetKeys());
            string makeModel = MakeModel(entity.FindPrimaryKey(), "", "", ", ", false, false, lowercaseVariableName: false);

            IndentingStringBuilder sb = new IndentingStringBuilder(2);

            sb.AppendLine("[HttpGet]");
            sb.AppendLine($"[VersionedRoute(template: \"{Inflector.Pluralize(entity.ClrType.Name)}/{{{GetSignatureWithoutFieldTypes("", entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)}}}/{{numChildLevels:int=0}}\", allowedVersion: 1)]");
            sb.AppendLine($"public async Task<IHttpActionResult> Get({GetSignatureWithFieldTypes("", entity.FindPrimaryKey())}, int numChildLevels)");
            sb.AppendLine($"{{");
            sb.AppendLine($"try");
            sb.AppendLine($"{{");
            sb.AppendLine("if (!base.OnActionExecuting(out HttpStatusCode httpStatusCode, out string message)) { return Content(httpStatusCode, message); }");
            sb.AppendLine($"var dbItem = await Repo.Get_{tableName}Async({GetSignatureWithoutFieldTypes(string.Empty, entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)}, numChildLevels);");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"if (dbItem == null)");
            sb.AppendLine($"{{");
            sb.AppendLine("Log.LogWarning(eventId: (int)coreEnums.EventId.Warn_WebApi,");
            sb.AppendLine("\tmessage: \"Unable to get object via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"return NotFound();");
            sb.AppendLine($"}}");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"RunCustomLogicOnGetEntityByPK(ref dbItem, {GetSignatureWithoutFieldTypes(string.Empty, entity.FindPrimaryKey(), lowercasePkNameFirstChar: true)}, numChildLevels);");
            //sb.AppendLine($"base.Repo.{dbContextName}.Entry(dbItem).State = EntityState.Detached;"); // Setting an entity to the Detached state used to be important before the Entity Framework supported POCO objects. Prior to POCO support, your entities would have references to the context that was tracking them. These references would cause issues when trying to attach an entity to a second context. Setting an entity to the Detached state clears out all the references to the context and also clears the navigation properties of the entity—so that it no longer references any entities being tracked by the context. Now that you can use POCO objects that don’t contain references to the context that is tracking them, there is rarely a need to move an entity to the Detached state.
            sb.AppendLine($"return Ok(_factory.Create(dbItem));");
            sb.AppendLine($"}}");
            sb.AppendLine($"catch (Exception ex)");
            sb.AppendLine($"{{");
            sb.AppendLine("Log.LogError(eventId: (int)coreEnums.EventId.Exception_WebApi,");
            sb.AppendLine("\texception: ex,");
            sb.AppendLine("\tmessage: \"Unable to get object by PK via Web API for RequestUri {{RequestUri}}\",");
            sb.AppendLine("\tRequest.RequestUri.ToString());");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"if (System.Diagnostics.Debugger.IsAttached)");
            sb.AppendLine($"\tSystem.Diagnostics.Debugger.Break();");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"return InternalServerError();");
            sb.AppendLine($"}}");
            sb.AppendLine($"}}");
            sb.AppendLine(string.Empty);

            return(sb.ToString());
        }
Exemple #23
0
        private static string PrintArchive(ReadOnlySpan <byte> data)
        {
            var sb = new IndentingStringBuilder();

            sb.AppendLine(GetHeader());
            sb.AppendLine();

            sb.AppendLine("using System;");
            sb.AppendLine();

            sb.AppendLine("namespace LibHac");
            sb.AppendLineAndIncrease("{");

            sb.AppendLine("internal partial class ResultNameResolver");
            sb.AppendLineAndIncrease("{");

            sb.AppendLine("private static ReadOnlySpan<byte> ArchiveData => new byte[]");
            sb.AppendLineAndIncrease("{");

            for (int i = 0; i < data.Length; i++)
            {
                if (i % 16 != 0)
                {
                    sb.Append(" ");
                }
                sb.Append($"0x{data[i]:x2}");

                if (i != data.Length - 1)
                {
                    sb.Append(",");
                    if (i % 16 == 15)
                    {
                        sb.AppendLine();
                    }
                }
            }

            sb.AppendLine();
            sb.DecreaseAndAppendLine("};");
            sb.DecreaseAndAppendLine("}");
            sb.DecreaseAndAppendLine("}");

            return(sb.ToString());
        }
Exemple #24
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var argTmps = new List <string>();

            foreach (var arg in Args)
            {
                arg.Codegen(cil, sb);
                argTmps.Add(cil.LastUsedVar);
            }
            Callee.Codegen(cil, sb);

            // This doesn't account for:
            //      calling a returned function pointer
            //      calling from an array subscript
            //      calling a member
            var callee      = cil.SymTable.LookupFunction(cil.LastUsedVar);
            var callRetType = callee.TryInferType(cil);

            sb.LineDecl(SourceInfo);
            if (callRetType == "void")
            {
                sb.Append(string.Format("{0}(", callee.Name));
                cil.LastUsedVar = null;
            }
            else
            {
                var tmp = NameGenerator.NewTemp();
                sb.Append(string.Format(
                              "{0} {1} = {2}(",
                              callee.TryInferType(cil),
                              tmp,
                              callee.Name));
                cil.LastUsedVar = tmp;
            }
            for (int i = 0; i < argTmps.Count; ++i)
            {
                sb.AppendNoIndent(argTmps[i]);
                if (i + 1 < argTmps.Count)
                {
                    sb.AppendNoIndent(", ");
                }
            }
            sb.AppendLineNoIndent(");");
        }
        public static string GenerateConstructors(string className, string repositoryInterfaceName,
                                                  string efEntityNamespacePrefix, string dtoNamespacePrefix, string tableName)
        {
            IndentingStringBuilder sb = new IndentingStringBuilder(2);

            //sb.AppendLine($"public {className}() : base()");
            //sb.AppendLine("{");
            //sb.AppendLine("}");
            //sb.AppendLine(string.Empty);

            sb.AppendLine($"public {className}(ILogger<{className}> log, {repositoryInterfaceName} repository, IMapper mapper)");
            sb.AppendLine($": base(log, repository)");
            sb.AppendLine("{");
            sb.AppendLine($"_factory = new GenericFactory<{efEntityNamespacePrefix}.{tableName}, {dtoNamespacePrefix}.{tableName}>(mapper);");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);

            return(sb.ToString());
        }
Exemple #26
0
        private void CodegenOr(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var tmpResult = NameGenerator.NewTemp();

            sb.AppendLine(string.Format("int {0} = 0;", tmpResult));
            var true_     = new CILInteger(SourceInfo, 1);
            var false_    = new CILInteger(SourceInfo, 0);
            var lhsBranch = new CILBranch(SourceInfo, Lhs);

            lhsBranch.AddTrueBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), true_));
            var rhsBranch = new CILBranch(SourceInfo, Rhs);

            rhsBranch.AddTrueBranchStmt(new CILAssignment(SourceInfo, new CILIdent(SourceInfo, tmpResult), true_));
            lhsBranch.AddFalseBranchStmt(rhsBranch);
            lhsBranch.Codegen(cil, sb);

            cil.LastUsedVar = tmpResult;
            //throw new NotImplementedException();
        }
Exemple #27
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var op = GetOpString();

            Expr.Codegen(cil, sb);
            var tmp    = cil.LastUsedVar;
            var result = NameGenerator.NewTemp();
            var fmt    = GetOpSide() == Side.Pre
                ? "{0} {1} = ({2}({3}));"
                : "{0} {1} = (({3}){2});";

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format(
                              fmt,
                              TryInferType(cil),
                              result,
                              op,
                              tmp));
            cil.LastUsedVar = result;
        }
        public string GenerateLogMethod(string name, bool exnull)
        {
            IndentingStringBuilder sb = new IndentingStringBuilder(2);

            string defaultnull = exnull ? " = null" : "";

            sb.AppendLine($"public Guid {name}(string message, int logMessageType, Exception ex{defaultnull}, string userName = null, string clientIPAddress = null,");
            sb.AppendLine("\t[CallerMemberName] string methodName = null, [CallerFilePath] string sourceFile = null, [CallerLineNumber] int lineNumber = 0,");
            sb.AppendLine("\tDecimal? executionTimeInMilliseconds = null, int? httpResponseStatusCode = null, string url = null)");
            sb.AppendLine("{");
            sb.AppendLine("url = url ?? GetUrl();");
            sb.AppendLine("clientIPAddress = clientIPAddress ?? GetClientIpAddress();");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"return Log.{name}(message: message, logMessageType: logMessageType, ex: ex, userName: userName,");
            sb.AppendLine("\tclientIPAddress: clientIPAddress ?? GetClientIpAddress(), methodName: methodName, sourceFile: sourceFile,");
            sb.AppendLine("\tlineNumber: lineNumber, executionTimeInMilliseconds: executionTimeInMilliseconds, httpResponseStatusCode: httpResponseStatusCode, url: url ?? GetUrl());");
            sb.AppendLine("}");
            sb.AppendLine(string.Empty);
            return(sb.ToString());
        }
Exemple #29
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            cil.PushScope();
            sb.AppendLine("{");
            sb.Indent();
            foreach (var b in Before)
            {
                b.Codegen(cil, sb);
            }
            var lbl = NameGenerator.NewLabel();

            sb.AppendLineNoIndent(string.Format("{0}:", lbl));
            sb.AppendLine("{");
            sb.Indent();
            Condition.Codegen(cil, sb);
            var cond = cil.LastUsedVar;

            sb.LineDecl(SourceInfo);
            sb.AppendLine(string.Format("if ({0})", cond));
            sb.AppendLine("{");
            sb.Indent();
            foreach (var stmt in Body)
            {
                stmt.Codegen(cil, sb);
            }
            foreach (var stmt in After)
            {
                stmt.Codegen(cil, sb);
            }
            sb.AppendLine(string.Format("goto {0};", lbl));
            sb.Dedent();
            sb.AppendLine("}");
            sb.Dedent();
            sb.AppendLine("}");
            sb.Dedent();
            sb.AppendLine("}");
            cil.PopScope();
        }
Exemple #30
0
        public override void Codegen(CIntermediateLang cil, IndentingStringBuilder sb)
        {
            var tmp = cil.CurrentFunction;

            cil.CurrentFunction = this;
            sb.LineDecl(SourceInfo);
            sb.AppendLine(GetDeclaration());
            sb.AppendLine("{");
            sb.Indent();
            cil.PushScope();
            foreach (var par in Params)
            {
                cil.DeclareLocalVariable(par);
            }
            foreach (var stmt in Body)
            {
                stmt.Codegen(cil, sb);
            }
            cil.PopScope();
            sb.Dedent();
            sb.AppendLine("}");
            cil.CurrentFunction = tmp;
        }
Exemple #31
0
 /// <summary>
 /// Builds the SQL fragment representing this clause
 /// </summary>
 /// <returns>SQL fragment</returns>
 public virtual string GetQueryString()
 {
     var builder = new IndentingStringBuilder();
     builder.AppendLine(ClauseVerb, new object[0]);
     builder.In(1);
     builder.Append(GetExpressionsString(), new object[0]);
     builder.Out(1);
     return builder.ToString();
 }
Exemple #32
0
        private string GetQueryStringForCurrentQuery()
        {
            var buf = new IndentingStringBuilder();
            if (selectClause == null)
                selectClause = new SelectClause(this);
            if (selectClause != null)
                buf.AppendLine(selectClause.GetQueryString());

            if (fromClause != null)
                buf.AppendLine(fromClause.GetQueryString());

            if (whereClause != null)
                buf.AppendLine(whereClause.GetQueryString());

            if (groupByClause != null)
                buf.AppendLine(groupByClause.GetQueryString());

            if (havingClause != null)
                buf.AppendLine(havingClause.GetQueryString());

            if (orderByClause != null)
            {
                if (IsSubQuery == false)
                    buf.AppendLine(orderByClause.GetQueryString());
            }

            return buf.ToString();
        }