Example #1
0
        public void GenerateClasses_ForEmptyMetadata_Should_GenerateLogicalName()
        {
            // Arrange
            var metadata = new EntityMetadataProxy(new EntityMetadata
            {
                LogicalName = "uber_entity"
            });

            metadata.SetSelected(true);
            var values = new List <EntityMetadataProxy> {
                metadata
            };
            var settings = new Settings();

            settings.InitalizeCommonSettings();
            var    fakeWriter = A.Fake <IConstantFileWriter>();
            string entity     = null;
            var    config     = A.CallTo(() => fakeWriter.WriteEntity(null, null, null))
                                .WithAnyArguments()
                                .Invokes((Settings s, string e, string f) => { entity = e; });

            // Act
            CSharpUtils.GenerateClasses(values, settings, fakeWriter);

            // Assert
            config.MustHaveHappened();
            Assert.IsTrue(entity.Contains("public const string EntityName = \"uber_entity\";"));
        }
Example #2
0
 public static CSharpGMacLanguageServer CSharp4()
 {
     return(new CSharpGMacLanguageServer(
                CSharpUtils.CSharp4CodeGenerator(),
                CSharpUtils.CSharp4SyntaxFactory()
                ));
 }
    public void CreateTeamAIFactory(int i_TeamIndex, tnTeamDescription i_TeamDescription)
    {
        if (!m_SetupDone)
        {
            return;
        }

        if (i_TeamIndex < 0 || i_TeamIndex >= m_AIFactories.Length || i_TeamIndex >= m_TeamSizes.Length)
        {
            return;
        }

        if (i_TeamDescription == null)
        {
            return;
        }

        ClassTypeReference newAIFactoryType = (i_TeamIndex % 2 == 0) ? m_EvenTeamAIFactoryType : m_OddTeamAIFactoryType;

        tnBaseSubbuteoMatchAIFactory newAIFactory = CSharpUtils.Cast <tnBaseSubbuteoMatchAIFactory>(Activator.CreateInstance(newAIFactoryType));

        if (newAIFactory != null)
        {
            newAIFactory.Configure(i_TeamDescription);
        }

        m_AIFactories[i_TeamIndex] = newAIFactory;
        m_TeamSizes[i_TeamIndex]   = i_TeamDescription.charactersCount;
    }
        public void GenerateConstants()
        {
            Settings.InitalizeCommonSettings(); // ToDo: Load CommonSettings
            LoadEntities();
            RestoreSelectedEntities();
            var message = CSharpUtils.GenerateClasses(entities, Settings, Settings.GetWriter(this.crmConnection.WebApplicationUrl));

            Console.Write(message);
        }
Example #5
0
        private RestEaseParameter BuildValidParameter(string identifier, OpenApiSchema schema, bool required, string description, ParameterLocation? parameterLocation, params string[] extraAttributes)
        {
            var attributes = new List<string>();
            string validIdentifier = CSharpUtils.CreateValidIdentifier(identifier, CasingType.Camel);

            string restEaseParameterAnnotation = parameterLocation != null ? parameterLocation.ToString() : string.Empty;
            string isNullPostfix = !required && Settings.MakeNonRequiredParametersOptional ? " = null" : string.Empty;

            if (parameterLocation == ParameterLocation.Header)
            {
                attributes.Add($"\"{identifier}\"");
            }

            object identifierWithType;
            if (identifier != validIdentifier)
            {
                switch (parameterLocation)
                {
                    case ParameterLocation.Path:
                    case ParameterLocation.Query:
                        attributes.Add($"Name = \"{identifier}\"");
                        break;
                }

                attributes.AddRange(extraAttributes);

                identifierWithType = MapSchema(schema, validIdentifier, !required, false, null);

                return new RestEaseParameter
                {
                    Required = required,
                    Identifier = validIdentifier,
                    SchemaType = schema.GetSchemaType(),
                    SchemaFormat = schema.GetSchemaFormat(),
                    IdentifierWithType = $"{identifierWithType}",
                    IdentifierWithRestEase = $"[{restEaseParameterAnnotation}({string.Join(", ", attributes)})] {identifierWithType}{isNullPostfix}",
                    Summary = description
                };
            }

            string extraAttributesBetweenParentheses = extraAttributes.Length == 0 ? string.Empty : $"({string.Join(", ", extraAttributes)})";
            identifierWithType = MapSchema(schema, identifier, !required, false, null);

            return new RestEaseParameter
            {
                Required = required,
                Identifier = identifier,
                SchemaType = schema.GetSchemaType(),
                SchemaFormat = schema.GetSchemaFormat(),
                IdentifierWithType = $"{identifierWithType}",
                IdentifierWithRestEase = $"[{restEaseParameterAnnotation}{extraAttributesBetweenParentheses}] {identifierWithType}{isNullPostfix}",
                Summary = description
            };
        }
Example #6
0
 void onRequestSuccess(string message)
 {
     currentCheckStatus = CheckStatus.CheckVersionOver;
     UpdateUIStatus();
     try
     {
         JsonData res     = JsonMapper.ToObject(message);
         bool     success = (bool)res["success"];
         if (success)
         {
             JsonData note      = res["data"];
             bool     encrypted = (bool)res["encrypted"];
             if (encrypted)
             {
                 //是加密数据
                 note = JsonMapper.ToObject(CSharpUtils.Decrypt((string)note, AppConfig.APP_SALT));
             }
             int serverForceVersion = (int)note["forceVersion"];
             int localForceVersion  = AppConfig.APP_ForceVERSION;
             if (localForceVersion < serverForceVersion)
             {
                 //需要强更换包
                 string replaceAppUrl = (string)note["replaceAppUrl"];
                 MessageBox.Instance.PopOK(StaticText.ChangeApp, () =>
                 {
                     Application.OpenURL(replaceAppUrl);
                     Application.Quit();
                 }, StaticText.GoDownloadApp);
             }
             else
             {
                 string serverWeakVersion = (string)note["weakVersion"];
                 AppConfig.APP_WeakVERSION = serverWeakVersion;
                 hotUpdateUrl = ((string)note["hotUpdateUrl"]);
                 CallHotUpdateHelper();
             }
         }
         else
         {
             //这里是由服务器返回请求失败的原因,例如服务器正在维护,在某某时间段才开服
             MessageBox.Instance.PopOK((string)res["error"], () =>
             {
                 Application.Quit();
             }, StaticText.QuitGame);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Instance.PopOK(StaticText.Data_Error + ex.Message, () =>
         {
             Application.Quit();
         }, StaticText.QuitGame);
     }
 }
Example #7
0
 void onDownloadAssetSuccess(WWW www, object item)
 {
     print("单个ab下载成功");
     if (www.isDone && string.IsNullOrEmpty(www.error))
     {
         if (CSharpUtils.UncompressMemory(AppConfig.HotAssetsPath, www.bytes))
         {
             FileData data = item as FileData;
             data.needUpdate = false;
         }
     }
 }
        public void GenerateConstants()
        {
            Console.WriteLine("Generating Constants...");
            Settings.InitalizeCommonSettings(); // ToDo: Load CommonSettings
            LoadEntities();
            RestoreSelectedEntities();
            var message = CSharpUtils.GenerateClasses(entities, Settings, Settings.GetWriter(this.crmConnection.WebApplicationUrl));

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(message);
            Console.WriteLine("************************* Task End *************************");
            Console.ReadLine();
        }
Example #9
0
    List <string> StartCompressFile(string orignalPath, string targetPath)
    {
        int    stringLengthOfOrignalPath = orignalPath.Length;
        string rootName = orignalPath.Substring(orignalPath.LastIndexOf("/"));

        targetPath += rootName;
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }

        List <string> allOriganlFiles = new List <string>();

        Recursive(orignalPath, allOriganlFiles);

        List <string> md5List = new List <string>();

        foreach (var item in allOriganlFiles)
        {
            if (item.EndsWith(".meta") || item.EndsWith(".manifest") || item.EndsWith(manifestName))
            {
                continue;
            }
            string fileFloderStruct = item.Substring(stringLengthOfOrignalPath);
            string zipFile          = targetPath + fileFloderStruct;
            string itemDir          = Path.GetDirectoryName(zipFile);
            if (!Directory.Exists(itemDir))
            {
                Directory.CreateDirectory(itemDir);
            }

            string fileName = rootName + "/" + fileFloderStruct;
            string md5      = CSharpUtils.FileMD5(item);
            long   size     = compressFile(zipFile, item, fileName);
            md5List.Add(fileName + "|" + md5 + "|" + size);
        }
        return(md5List);
    }
Example #10
0
        public RestEaseInterface Map(OpenApiDocument openApiDocument)
        {
            string name = CSharpUtils.CreateValidIdentifier(Settings.ApiName, CasingType.Pascal);
            string interfaceName = $"I{name}Api";

            var @interface = new RestEaseInterface
            {
                Name = interfaceName,
                Namespace = Settings.Namespace,
                Summary = openApiDocument.Info?.Description ?? name
            };

            foreach (var path in openApiDocument.Paths)
            {
                MapPath(@interface, path.Key, path.Value);
            }
            //var methods = paths.Select(p => MapPath(interfaceName, p.Key, p.Value)).SelectMany(x => x).ToList();

            //var counts = methods
            //    .GroupBy(method => method.RestEaseMethod.Name + method.RestEaseMethod.Parameters)
            //    .Where(grouping => grouping.Count() > 1)
            //    .ToDictionary(grouping => grouping.Key, p => p.Count());

            //// modify the list, going backwards so we can take advantage of our counts.
            //for (int i = methods.Count - 1; i >= 0; i--)
            //{
            //    string key = methods[i].RestEaseMethod.Name + methods[i].RestEaseMethod.Parameters;
            //    if (counts.ContainsKey(key))
            //    {
            //        // add the suffix and decrement the number of duplicates left to tag.
            //        methods[i].RestEaseMethod.Name += $"{counts[key]--}";
            //    }
            //}

            return @interface;
        }
 public static string ToValidIdentifier(this string value, CasingType casingType)
 {
     return(CSharpUtils.CreateValidIdentifier(value, casingType));
 }
Example #12
0
        private RestEaseInterfaceMethodDetails MapOperationToMappingModel(RestEaseInterface @interface, string path, string httpMethod, OpenApiOperation operation)
        {
            string methodRestEaseForAnnotation = httpMethod.ToPascalCase();

            string methodRestEaseMethodName = GeneratedRestEaseMethodName(path, operation, methodRestEaseForAnnotation);

            var headerParameterList = operation.Parameters
                .Where(p => p.In == ParameterLocation.Header && p.Schema.GetSchemaType() != SchemaType.Object)
                .Select(p => BuildValidParameter(p.Name, p.Schema, p.Required, p.Description, p.In))
                .ToList();

            var pathParameterList = operation.Parameters
                .Where(p => p.In == ParameterLocation.Path && p.Schema.GetSchemaType() != SchemaType.Object)
                .Select(p => BuildValidParameter(p.Name, p.Schema, p.Required, p.Description, p.In))
                .ToList();

            var queryParameterList = operation.Parameters
                .Where(p => p.In == ParameterLocation.Query && p.Schema.GetSchemaType() != SchemaType.Object)
                .Select(p => BuildValidParameter(p.Name, p.Schema, p.Required, p.Description, p.In))
                .ToList();

            var extensionMethodParameterList = new List<RestEaseParameter>();
            var bodyParameterList = new List<RestEaseParameter>();

            var requestDetails = operation.RequestBody != null
                ? MapRequest(operation, bodyParameterList, extensionMethodParameterList)
                : null;

            var headers = new List<string>();
            if (requestDetails != null)
            {
                if (requestDetails.DetectedContentType != null)
                {
                    headers.Add($"[Header(\"{HttpKnownHeaderNames.ContentType}\", \"{requestDetails.DetectedContentType.GetDescription()}\")]");
                }
                else if (requestDetails.ContentTypes.Count > 1)
                {
                    headerParameterList.Add(new RestEaseParameter
                    {
                        Required = true,
                        Summary = "The Content-Type",
                        Identifier = "contentType",
                        IdentifierWithRestEase = $"[Header(\"{HttpKnownHeaderNames.ContentType}\")] string contentType",
                        IdentifierWithType = "string contentType",
                        IsSpecial = false,
                        SchemaFormat = SchemaFormat.Undefined,
                        SchemaType = SchemaType.String
                    });
                }
            }

            var methodParameterList = headerParameterList
                .Union(pathParameterList)
                .Union(bodyParameterList)
                .Union(queryParameterList)
                .OrderByDescending(p => p.Required)
                .ToList();

            var response = operation.Responses.First();

            object returnType = null;
            if (response.Value != null && TryGetOpenApiMediaType(response.Value.Content, SupportedContentType.ApplicationJson, out OpenApiMediaType responseJson, out var _))
            {
                switch (responseJson.Schema?.GetSchemaType())
                {
                    case SchemaType.Array:
                        string arrayType = responseJson.Schema.Items.Reference != null ?
                            MakeValidModelName(responseJson.Schema.Items.Reference.Id) :
                            MapSchema(responseJson.Schema.Items, null, false, true, null).ToString();

                        returnType = MapArrayType(arrayType);
                        break;

                    case SchemaType.Object:
                        if (responseJson.Schema.Reference != null)
                        {
                            // Existing defined object
                            returnType = MakeValidModelName(responseJson.Schema.Reference.Id);
                        }
                        else if (responseJson.Schema.AdditionalProperties != null)
                        {
                            // Use AdditionalProperties
                            returnType = MapSchema(responseJson.Schema.AdditionalProperties, null, responseJson.Schema.AdditionalProperties.Nullable, false, null);
                        }
                        else
                        {
                            // Object is defined `inline`, create a new Model and use that one.
                            string className = !string.IsNullOrEmpty(responseJson.Schema.Title)
                                ? CSharpUtils.CreateValidIdentifier(responseJson.Schema.Title, CasingType.Pascal)
                                : $"{methodRestEaseMethodName.ToPascalCase()}Result";

                            var existingModel = @interface.InlineModels.FirstOrDefault(m => m.ClassName == className);
                            if (existingModel == null)
                            {
                                var newModel = new RestEaseModel
                                {
                                    Namespace = Settings.Namespace,
                                    ClassName = className,
                                    Properties = MapSchema(responseJson.Schema, null, false, true, null) as ICollection<string>
                                };
                                @interface.InlineModels.Add(newModel);
                            }

                            returnType = className;
                        }
                        break;

                    default:
                        if (Settings.ReturnObjectFromMethodWhenResponseIsDefinedButNoModelIsSpecified)
                        {
                            returnType = "object";
                        }
                        break;
                }
            }

            var method = new RestEaseInterfaceMethodDetails
            {
                Headers = headers,
                Summary = operation.Summary ?? $"{methodRestEaseMethodName} ({path})",
                SummaryParameters = methodParameterList.Select(mp => $"<param name=\"{mp.Identifier}\">{mp.Summary.StripHtml()}</param>").ToList(),
                RestEaseAttribute = $"[{methodRestEaseForAnnotation}(\"{path}\")]",
                RestEaseMethod = new RestEaseInterfaceMethod
                {
                    ReturnType = MapReturnType(returnType),
                    Name = methodRestEaseMethodName,
                    ParametersAsString = string.Join(", ", methodParameterList.Select(mp => mp.IdentifierWithRestEase)),
                    Parameters = methodParameterList
                }
            };

            if (requestDetails?.IsExtension == true)
            {
                var combinedMethodParameterList = new List<RestEaseParameter>
                {
                    new RestEaseParameter
                    {
                        Identifier = "api",
                        IdentifierWithType = $"this {@interface.Name} api",
                        IdentifierWithRestEase = $"this {@interface.Name} api",
                        Summary = "The Api"
                    }
                };
                combinedMethodParameterList.AddRange(methodParameterList.Where(p => !p.IsSpecial));
                combinedMethodParameterList.AddRange(extensionMethodParameterList);

                method.ExtensionMethodDetails = new RestEaseInterfaceMethodDetails
                {
                    Summary = operation.Summary ?? $"{methodRestEaseMethodName} ({path})",
                    SummaryParameters = combinedMethodParameterList.Select(mp => $"<param name=\"{mp.Identifier}\">{mp.Summary.StripHtml()}</param>").ToList(),
                    RestEaseMethod = new RestEaseInterfaceMethod
                    {
                        ReturnType = method.RestEaseMethod.ReturnType,
                        Name = method.RestEaseMethod.Name,
                        ParametersAsString = string.Join(", ", combinedMethodParameterList.Select(mp => mp.IdentifierWithType)),
                        Parameters = combinedMethodParameterList
                    }
                };
                method.ExtensionMethodParameters = extensionMethodParameterList;
                method.ExtensionMethodContentType = requestDetails.DetectedContentType;
            }

            return method;
        }