private string ParseObject(string key, JsonSchema schema, IDictionary <string, ApiObject> objects, IDictionary <string, ApiEnum> enums)
        {
            var propertiesSchemas = schema.Properties;

            var obj = new ApiObject
            {
                Name       = NetNamingMapper.GetObjectName(key),
                Properties = ParseSchema(propertiesSchemas, objects, enums)
            };

            AdditionalProperties(obj.Properties, schema);

            if (!obj.Properties.Any())
            {
                return(null);
            }

            // Avoid duplicated keys and names or no properties
            if (objects.ContainsKey(key) || objects.Any(o => o.Value.Name == obj.Name) ||
                otherObjects.ContainsKey(key) || otherObjects.Any(o => o.Value.Name == obj.Name) ||
                schemaObjects.ContainsKey(key) || schemaObjects.Any(o => o.Value.Name == obj.Name))
            {
                if (UniquenessHelper.HasSameProperties(obj, objects, key, otherObjects, schemaObjects))
                {
                    return(key);
                }

                obj.Name = UniquenessHelper.GetUniqueName(objects, obj.Name, otherObjects, schemaObjects);
                key      = UniquenessHelper.GetUniqueKey(objects, key, otherObjects);
            }

            objects.Add(key, obj);
            return(key);
        }
        private void ParseObject(string key, IDictionary <string, Newtonsoft.JsonV4.Schema.JsonSchema> schema, IDictionary <string, ApiObject> objects, IDictionary <string, ApiEnum> enums, Newtonsoft.JsonV4.Schema.JsonSchema parentSchema, string baseClass = null)
        {
            var obj = new ApiObject
            {
                Name       = NetNamingMapper.GetObjectName(key),
                Properties = ParseSchema(schema, objects, enums, parentSchema),
                BaseClass  = baseClass
            };

            // Avoid duplicated keys and names
            if (objects.ContainsKey(key) || objects.Any(o => o.Value.Name == obj.Name) ||
                otherObjects.ContainsKey(key) || otherObjects.Any(o => o.Value.Name == obj.Name) ||
                schemaObjects.ContainsKey(key) || schemaObjects.Any(o => o.Value.Name == obj.Name) ||
                !obj.Properties.Any())
            {
                if (UniquenessHelper.HasSameProperties(obj, objects, key, otherObjects, schemaObjects))
                {
                    return;
                }

                obj.Name = UniquenessHelper.GetUniqueName(objects, obj.Name, otherObjects, schemaObjects);
                key      = UniquenessHelper.GetUniqueKey(objects, key, otherObjects);
            }

            objects.Add(key, obj);
        }
 public object Post(ApiObject obj)
 {
     try
     {
         if (obj.Version == "1.0")
         {
             return(OK.Mobisis.Api.Version10.Global.Execute(obj));
         }
         else if (obj.Version == "1.1")
         {
             return(OK.Mobisis.Api.Version11.Global.Execute(obj));
         }
         else
         {
             return new ResultObject <String>()
                    {
                        Status = false, Message = "Invalid version"
                    }
         };
     }
     catch (Exception ex)
     {
         return(new ResultObject <String>()
         {
             Status = false, Message = "Giriş Başarısız"
         });
     }
 }
Exemple #4
0
        private void GetResultWithPost(RequestObject requestObj)
        {
            try
            {
                var obj = new ApiObject();
                obj.Version  = Global.ApiVersion;
                obj.Username = Global.ApiUsername;
                obj.Password = Global.ApiPassword;
                obj.Request  = requestObj;

                string requestJson = JsonConvert.SerializeObject(obj);
                Global.OnRequestParsed(requestJson);
                _byteArray = Encoding.UTF8.GetBytes(requestJson);

                var request = HttpWebRequest.Create(Global.ApiUrl);
                request.ContentType = "application/json; charset=UTF-8";

                request.Method = "POST";
                request.BeginGetRequestStream(SendDataCallBack, request);
            }
            catch (Exception exp)
            {
                OnError(exp);
            }
        }
        public static CSharpSourceFile FromObject(ApiObject obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            var sourceFile = new CSharpSourceFile
            {
                Name   = obj.Name.ToBeautifiedName(),
                Usings = DefaultUsings
            };

            if (obj.IsEnum())
            {
                sourceFile.Enum = CSharpEnum.FromObject(obj);
            }
            else if (obj.IsClass())
            {
                sourceFile.Class = CSharpClass.Map(obj);
            }
            else
            {
                return(null);
            }

            return(sourceFile);
        }
Exemple #6
0
		private static async Task<string> Send (string method, string path, IDictionary<string, string> args, ApiObject contentObject)
		{
			HttpContent content = null;
			if (contentObject != null) {
				var body = JsonConvert.SerializeObject (contentObject.AsDict ());
				content = new StringContent (body, System.Text.UTF8Encoding.Default, "application/json");
			}
			using (var client = new HttpClient ()) {
				client.Timeout = TimeSpan.FromSeconds (350);

				var url = ApiUrl (path, args);
				var message = new HttpRequestMessage (new HttpMethod (method), url);
				if (content != null)
					message.Content = content;
				client.DefaultRequestHeaders.Add ("Authorization", "token " + AuthToken);

				var response = await client.SendAsync (message);
				var responseBody = await response.Content.ReadAsStringAsync ();
				if (!response.IsSuccessStatusCode) {
					Console.Error.WriteLine ("Error: {0} to `{1}` not successful: {2}", method, url, responseBody);
					return null;
				}
				return responseBody;
			}
		}
        public static void Equal(ApiObject expected, ApiObject actual)
        {
            if (expected == null)
            {
                Assert.Null(actual);
                return;
            }

            Assert.NotNull(actual);

            var expectedCollection = expected.ToList();
            var actualCollection   = actual.ToList();

            Assert.Equal(expectedCollection.Count, actualCollection.Count);

            var count = expectedCollection.Count;

            for (var index = 0; index < count; ++index)
            {
                var expectedObjectProperty = expectedCollection[index];
                var actualObjectProperty   = actualCollection[index];

                ApiPropertyAssert.Equal(expectedObjectProperty, actualObjectProperty);
            }
        }
        public async Task <ApiObject <ContestWorkResponse> > GetContestsWorksAsync(int contestId)
        {
            var query = _bookContext.ContestWorks
                        .Where(c => c.ContestId == contestId)
                        .Select(c => new ContestWorkResponse
            {
                ContestWorkId = c.Id,
                Name          = c.Name,
                RusName       = c.RusName,
                Prefix        = c.Prefix,
                Postfix       = c.Postfix,
                Number        = c.Number,
                IsWinner      = c.IsWinner,
                LinkType      = c.LinkType,
                LinkId        = c.LinkId,
                ContestId     = c.ContestId,
                NominationId  = c.NominationId
            });

            var result = new ApiObject <ContestWorkResponse>();

            result.Values = await query.ToListAsync();

            result.TotalRows = result.Values.Count;

            return(result);
        }
        public static void Equal(ApiObject expected, JToken actualJToken)
        {
            // Handle when 'expected' is null.
            if (expected == null)
            {
                ClrObjectAssert.IsNull(actualJToken);
                return;
            }

            // Handle when 'expected' is not null.
            Assert.NotNull(actualJToken);

            var actualJTokenType = actualJToken.Type;

            Assert.Equal(JTokenType.Object, actualJTokenType);

            var actualJObject = (JObject)actualJToken;

            var expectedCollection = expected.ToList();
            var actualCollection   = actualJObject.Properties().ToList();

            Assert.Equal(expectedCollection.Count, actualCollection.Count);

            var count = expectedCollection.Count;

            for (var index = 0; index < count; ++index)
            {
                var expectedObjectProperty = expectedCollection[index];
                var actualJProperty        = actualCollection[index];

                ApiPropertyAssert.Equal(expectedObjectProperty, actualJProperty);
            }
        }
Exemple #10
0
 public AdsTxtMailer(string to)
 {
     _api   = new ApiObject();
     _host  = Base._config.Host;
     _brand = Base._config.SiteName;
     To     = to;
 }
        // PUBLIC METHODS ///////////////////////////////////////////////////
        #region Assert Methods
        public static void Equal(ApiObject expected, DomNode actual)
        {
            if (expected == null)
            {
                Assert.Null(actual);
                return;
            }
            Assert.NotNull(actual);

            Assert.Equal(DomNodeType.Attributes, actual.NodeType);

            var actualDomNodesContainer = (DomNodesContainer)actual;
            var actualDomAttributes     = actualDomNodesContainer.Nodes()
                                          .Cast <DomAttribute>()
                                          .ToList();

            var actualDomAttributesCount = actualDomAttributes.Count;

            Assert.Equal(expected.Count(), actualDomAttributesCount);

            foreach (var actualDomAttribute in actualDomAttributes)
            {
                var apiPropertyName = actualDomAttribute.ApiPropertyName;

                ApiProperty expectedApiProperty;
                Assert.True(expected.TryGetApiProperty(apiPropertyName, out expectedApiProperty));

                // ReSharper disable once ExpressionIsAlwaysNull
                DomAttributeAssert.Equal(expectedApiProperty, actualDomAttribute);
            }
        }
        public AuthResponse Execute(string stateToken, string link, ApiObject apiObject = null)
        {
            Link href = new Link();

            href.Href = new Uri(link);
            return(_authclient.Execute(stateToken, href, apiObject));
        }
 internal bool InputIsValid()
 {
     if (Source < 1 || Source > 4)
     {
         return(ApiObject.FalseWithErrorMessage("SW41PlusV3.Source({0}): Must be between 1 and 4", Source));
     }
     return(true);
 }
Exemple #14
0
        public AuthResponse GetStatus(string stateToken)
        {
            var apiObject = new ApiObject();

            apiObject.SetProperty("stateToken", stateToken);
            var response = BaseClient.Post(resourcePath, apiObject.ToJson());

            return(Utils.Deserialize <AuthResponse>(response));
        }
Exemple #15
0
        public AuthResponse ActivateTotpFactor(string stateToken, AuthResponse authResponse, string passCode)
        {
            var apiObject = new ApiObject();

            apiObject.SetProperty("passCode", passCode);
            var nextLink = authResponse.Links["next"];

            return(Execute(stateToken, nextLink, apiObject));
        }
Exemple #16
0
        public AuthResponse ValidateToken(string recoveryToken)
        {
            var apiObject = new ApiObject();

            apiObject.SetProperty("recoveryToken", recoveryToken);
            var response = BaseClient.Post(resourcePath + Constants.RecoveryEndpoint + Constants.TokenEndpoint, apiObject.ToJson());

            return(Utils.Deserialize <AuthResponse>(response));
        }
        // PUBLIC METHODS ///////////////////////////////////////////////////
        #region Assert Methods
        public static void Equal(ApiObject expected, string actualJson)
        {
            Assert.NotNull(expected);
            Assert.False(String.IsNullOrEmpty(actualJson));

            var actualJToken = JToken.Parse(actualJson);

            ApiObjectAssert.Equal(expected, actualJToken);
        }
Exemple #18
0
        public AuthResponse Execute(string stateToken, Uri uri, ApiObject apiObject = null)
        {
            // Create a new apiObject if it's null, because we need to add a stateToken
            apiObject = apiObject ?? new ApiObject();
            apiObject.SetProperty("stateToken", stateToken);
            var response = BaseClient.Post(uri, apiObject.ToJson());

            return(Utils.Deserialize <AuthResponse>(response));
        }
Exemple #19
0
        public virtual AuthResponse VerifyPullFactor(string factorId, AuthResponse authResponse)
        {
            var apiObject = new ApiObject();

            apiObject.SetProperty("stateToken", authResponse.StateToken);
            var response = BaseClient.Post(resourcePath + Constants.FactorsEndpoint + "/" + factorId + Constants.VerifyEndpoint, apiObject.ToJson(), true);

            return(Utils.Deserialize <AuthResponse>(response));
        }
Exemple #20
0
        public virtual AuthResponse Skip(string stateToken)
        {
            var apiObject = new ApiObject();

            apiObject.SetProperty("stateToken", stateToken);
            var response = BaseClient.Post(resourcePath + Constants.SkipEndpoint, apiObject.ToJson());

            return(Utils.Deserialize <AuthResponse>(response));
        }
Exemple #21
0
 public static CSharpProperty Map(ApiObject obj)
 {
     return(new CSharpProperty
     {
         Name = obj.Name.ToBeautifiedName(),
         Summary = new CSharpSummary(obj.Description),
         Type = obj.GetCSharpType(preferNullable: true),
         Attributes = obj.Name.StartsWithNumber() ? new[] { GetJsonPropertyAttribute(obj.Name) } : null
     });
 }
Exemple #22
0
 public bool IOsAreValid(int input, int output)
 {
     if (input < 1 || input > InputCount)
     {
         return(ApiObject.FalseWithErrorMessage("HxlPlus.{0}.Input({1}): Must be between 1 and {2}", this.GetType().Name, input, InputCount));
     }
     if (output < 1 || output > OutputCount)
     {
         return(ApiObject.FalseWithErrorMessage("HxlPlus.{0}.Output({1}): Must be between 1 and {2}", this.GetType().Name, output, OutputCount));
     }
     return(true);
 }
Exemple #23
0
        public virtual AuthResponse Execute(string stateToken, string relativeUri, ApiObject apiObject = null)
        {
            // Create a new apiObject if it's null, because we need to add a stateToken
            apiObject = apiObject ?? new ApiObject();
            if (!apiObject.ContainsProperty("stateToken"))
            {
                apiObject.SetProperty("stateToken", stateToken);
            }
            var response = BaseClient.Post(relativeUri, apiObject.ToJson(), true);

            return(Utils.Deserialize <AuthResponse>(response));
        }
Exemple #24
0
        public void TestObjectParse(string name, ApiObject expected)
        {
            // Arrange
            var json = expected.ToJson();

            // Act
            this.Output.WriteLine(json);
            var actual = JsonObject.Parse <Object>(json);

            // Assert
            ApiObjectAssert.Equal(expected, (JToken)actual);
        }
Exemple #25
0
        public void TestObjectToJson(string name, ApiObject expected)
        {
            // Arrange

            // Act
            var actual = expected.ToJson();

            this.Output.WriteLine(actual);

            // Assert
            ApiObjectAssert.Equal(expected, actual);
        }
        public static CSharpClass Map(ApiObject obj)
        {
            var propertyObjects = ExtractProperties(obj);

            return(new CSharpClass
            {
                Name = obj.Name.ToBeautifiedName(),
                Summary = string.IsNullOrWhiteSpace(obj.Description) ? null : new CSharpSummary(obj.Description),
                Properties = propertyObjects.Where(o => !o.IsEnum()).Select(CSharpProperty.Map).ToList(),
                NestedEnums = propertyObjects.Where(o => o.IsEnum()).Select(o => CSharpEnum.FromObject(o)).ToList(),
                Methods = Array.Empty <CSharpMethod>()
            });
        }
Exemple #27
0
        public static string GetCSharpType(this ApiObject obj, bool preferNullable = true)
        {
            // Handle primitive types
            switch (obj.Type)
            {
            case ApiObjectType.Integer:
                return(preferNullable ? "int?" : "int");

            case ApiObjectType.Boolean:
                return(preferNullable ? "bool?" : "bool");

            case ApiObjectType.Number:
                return(preferNullable ? "double?" : "double");

            case ApiObjectType.Multiple:     // TODO: Think about this type
            case ApiObjectType.String:
                return("string");

            case ApiObjectType.Array:

                if (obj.Items != null)
                {
                    var genericType = string.IsNullOrWhiteSpace(obj.Items.Name) ?
                                      obj.Items.GetCSharpType(false) :
                                      obj.Items.Name.ToBeautifiedName();

                    return($"IEnumerable<{genericType}>");
                }

                return("IEnumerable<object>");    // TODO: Maybe throw an exception here later...?
            }

            // Handle references
            if (obj.Reference != null)
            {
                if (TrickyTypesMap.TryGetValue(obj.Reference.Name, out var realType))
                {
                    return(realType);
                }

                if (!obj.Reference.IsClass())
                {
                    return(obj.Reference.GetCSharpType(true));
                }

                return(obj.Reference.Name.ToBeautifiedName());
            }

            return("object"); // TODO: Maybe throw an exception here later...?
        }
Exemple #28
0
        private static string ResolveReferenceType(ApiObject obj)
        {
            if (obj == null)
            {
                return(null);
            }

            if (obj.Type != ApiObjectType.Object && obj.Type != ApiObjectType.Undefined)
            {
                return(CustomTypeMap.TryGetValue(obj.Name, out string remappedType) ?
                       remappedType :
                       ResolveDate(obj.Name, MapType(obj.Type), null));
            }

            return(obj.Name);
        }
Exemple #29
0
        public async Task <ApiObject <WorkRatingResponse> > GetWorkRating(string type)
        {
            var cacheEntryBytes = await _cache.GetAsync($"ratings:works:{type}");

            List <WorkRatingResponse> workRating;

            if (cacheEntryBytes == null)
            {
                var ratings = _bookContext.WorkRatingView
                              .Where(c => c.RatingType == type)
                              .Select(c => new WorkRatingResponse
                {
                    WorkId      = c.WorkId,
                    WorkRusName = "not implemented yet",    // TODO: not implemented yet
                    WorkName    = "not implemented yet",    // TODO: not implemented yet
                    WorkYear    = -1,                       // TODO: not implemented yet
                    Persons     = new List <PersonResponse> // TODO: not implemented yet
                    {
                        new PersonResponse
                        {
                            PersonId     = -1,
                            Name         = "not implemented yet",
                            NameOriginal = "not implemented yet"
                        }
                    },
                    Rating     = c.Rating,
                    MarksCount = c.MarksCount
                });

                workRating = await ratings.ToListAsync();

                string serialized = JsonConvert.SerializeObject(workRating);
                await _cache.SetAsync($"ratings:works:{type}", Encoding.UTF8.GetBytes(serialized),
                                      new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) });
            }
            else
            {
                workRating = JsonConvert.DeserializeObject <List <WorkRatingResponse> >(Encoding.UTF8.GetString(cacheEntryBytes));
            }

            var apiObject = new ApiObject <WorkRatingResponse>();

            apiObject.Values    = workRating;
            apiObject.TotalRows = apiObject.Values.Count;

            return(apiObject);
        }
        public async Task CreateOneOnOneGame(string LobbyName, string enemyId)
        {
            if (League == null)
            {
                League = await LeagueClient.Connect();
            }
            ApiObject api      = new ApiObject();
            var       obj      = api.createCustomGameOneOnOne(LobbyName);
            var       response = await League.MakeApiRequest(HttpMethod.Post, "/lol-lobby/v2/lobby", obj);

            while (true)
            {
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    obj      = api.createCustomGameOneOnOne(LobbyName);
                    response = League.MakeApiRequest(HttpMethod.Post, "/lol-lobby/v2/lobby", obj).Result;
                }
                else
                {
                    break;
                }
            }

            var invites = new List <LobbyInvitation>();

            invites.Add(new LobbyInvitation
            {
                ToSummonerId = enemyId
            });
            await League.MakeApiRequest(HttpMethod.Post, "/lol-lobby/v2/lobby/invitations", invites);

            bool AllIn = false;

            while (!AllIn)
            {
                LobbyPlayerInfo[] players = await League.MakeApiRequestAs <LobbyPlayerInfo[]>(HttpMethod.Get, "/lol-lobby/v2/lobby/members");

                foreach (var item in players)
                {
                    if (item.SummonerId == enemyId)
                    {
                        AllIn = true;
                    }
                }
            }
            await League.MakeApiRequest(HttpMethod.Post, "/lol-lobby/v1/lobby/custom/start-champ-select", new StartGame());
        }
        private static bool HasDuplicatedObjects(IDictionary <string, ApiObject> objects, CodeNamespace codeNamespace)
        {
            foreach (CodeTypeDeclaration typeDeclaration in codeNamespace.Types)
            {
                var obj = new ApiObject {
                    Name = typeDeclaration.Name
                };

                if (objects.ContainsKey(obj.Name) || objects.Any(o => o.Value.Name == obj.Name))
                {
                    return(true);
                }

                objects.Add(obj.Name, obj);
            }
            return(false);
        }
 private void BuildRequest(ClientGeneratorMethod method, ClassObject classObject, ICollection<ApiObject> objects)
 {
     var requestProperties = BuildRequestProperties(method).ToList();
     if (requestProperties.Any())
     {
         var reqObject = new ApiObject
         {
             Name = classObject.Name + method.Name + "Request",
             Description = "Request object for method " + method.Name + " of class " + classObject.Name,
             Properties = requestProperties
         };
         objects.Add(reqObject);
         method.RequestType = ClientGeneratorMethod.ModelsNamespacePrefix + reqObject.Name;
     }
     else
     {
         method.RequestType = "ApiRequest";
     }
 }
        public ApiObject Parse(string key, string jsonSchema, IDictionary<string, ApiObject> objects, IDictionary<string, string> warnings, 
            IDictionary<string, ApiEnum> enums, IDictionary<string, ApiObject> otherObjects, IDictionary<string, ApiObject> schemaObjects)
        {
            this.otherObjects = otherObjects;
            this.schemaObjects = schemaObjects;
            var obj = new ApiObject
                      {
                          Name = NetNamingMapper.GetObjectName(key),
                          Properties = new List<Property>(),
                          JSONSchema = jsonSchema.Replace(Environment.NewLine, "").Replace("\r\n", "").Replace("\n", "")
                                                 .Replace("\\", "\\\\").Replace("\"", "\\\"")
                                                // .Replace("\\/", "\\\\/").Replace("\"", "\\\"").Replace("\\\\\"", "\\\\\\\"")
                      };
            JsonSchema schema = null;
            Newtonsoft.JsonV4.Schema.JsonSchema v4Schema = null;
            if (jsonSchema.Contains("\"oneOf\""))
            {
                v4Schema = ParseV4Schema(key, jsonSchema, warnings, objects);
            }
            else
            {
                schema = ParseV3OrV4Schema(key, jsonSchema, warnings, ref v4Schema, objects);
            }

            if (schema == null && v4Schema == null)
                return obj;

            if (schema != null)
            {
                if (schema.Type == JsonSchemaType.Array)
                {
                    obj.IsArray = true;
                    if (schema.Items != null && schema.Items.Any())
                    {
                        if (schema.Items.First().Properties != null)
                        {
                            ParseProperties(objects, obj.Properties, schema.Items.First().Properties, enums);
                        }
                        else
                        {
                            obj.Type = NetTypeMapper.Map(schema.Items.First().Type);
                        }
                    }
                }
                else
                {
                    ParseProperties(objects, obj.Properties, schema.Properties, enums);
                    AdditionalProperties(obj.Properties, schema);
                }
            }
            else
            {
                if (v4Schema.Type == Newtonsoft.JsonV4.Schema.JsonSchemaType.Array)
                {
                    obj.IsArray = true;
                    if (v4Schema.Items != null && v4Schema.Items.Any())
                    {
                        if (v4Schema.Items.First().Properties != null)
                        {
                            ParseProperties(objects, obj.Properties, v4Schema.Items.First(), enums);
                        }
                        else
                        {
                            obj.Type = NetTypeMapper.Map(v4Schema.Items.First().Type);
                        }
                    }

                }
                else
                {
                    ParseProperties(objects, obj.Properties, v4Schema, enums);
                }
            }
            return obj;
        }
        private string ParseObject(string key, IDictionary<string, JsonSchema> schema, IDictionary<string, ApiObject> objects, IDictionary<string, ApiEnum> enums)
        {
            if (schema == null)
                return null;

            var obj = new ApiObject
            {
                Name = NetNamingMapper.GetObjectName(key),
                Properties = ParseSchema(schema, objects, enums)
            };

            if (obj == null)
                return null;

            if(!obj.Properties.Any())
                return null;

            // Avoid duplicated keys and names or no properties
            if (objects.ContainsKey(key) || objects.Any(o => o.Value.Name == obj.Name)
                || otherObjects.ContainsKey(key) || otherObjects.Any(o => o.Value.Name == obj.Name)
                || schemaObjects.ContainsKey(key) || schemaObjects.Any(o => o.Value.Name == obj.Name))
            {
                if (UniquenessHelper.HasSameProperties(obj, objects, key, otherObjects, schemaObjects))
                    return key;

                obj.Name = UniquenessHelper.GetUniqueName(objects, obj.Name, otherObjects, schemaObjects);
                key = UniquenessHelper.GetUniqueKey(objects, key, otherObjects);
            }

            objects.Add(key, obj);
            return key;
        }
        private void ParseObject(string key, IDictionary<string, Newtonsoft.JsonV4.Schema.JsonSchema> schema, IDictionary<string, ApiObject> objects, IDictionary<string, ApiEnum> enums, Newtonsoft.JsonV4.Schema.JsonSchema parentSchema, string baseClass = null)
        {
            var obj = new ApiObject
                      {
                          Name = NetNamingMapper.GetObjectName(key),
                          Properties = ParseSchema(schema, objects, enums, parentSchema),
                          BaseClass = baseClass
                      };

            // Avoid duplicated keys and names
            if (objects.ContainsKey(key) || objects.Any(o => o.Value.Name == obj.Name)
                || otherObjects.ContainsKey(key) || otherObjects.Any(o => o.Value.Name == obj.Name)
                || schemaObjects.ContainsKey(key) || schemaObjects.Any(o => o.Value.Name == obj.Name)
                || !obj.Properties.Any())
            {
                if (UniquenessHelper.HasSameProperties(obj, objects, key, otherObjects, schemaObjects))
                    return;

                obj.Name = UniquenessHelper.GetUniqueName(objects, obj.Name, otherObjects, schemaObjects);
                key = UniquenessHelper.GetUniqueKey(objects, key, otherObjects);
            }

            objects.Add(key, obj);
        }
Exemple #36
0
		private static async Task<string> Post (string path, IDictionary<string, string> args, ApiObject contentObject)
		{
			return await Send ("POST", path, args, contentObject);
		}
Exemple #37
0
		private static async Task<string> Delete (string path, IDictionary<string, string> args, ApiObject contentObject)
		{
			return await Send ("DELETE", path, args, contentObject);
		}
Exemple #38
0
		// new runset
		public static async Task<string> PutRunset (ApiObject contentObject)
		{
			return await Put ("/runset", null, contentObject);
		}
		private void CreateMultipleType(ClientGeneratorMethod generatedMethod)
		{
			var properties = BuildProperties(generatedMethod);

			var name = NetNamingMapper.GetObjectName("Multiple" + generatedMethod.Name + "Header");

			var apiObject = new ApiObject
			{
				Name = name,
				Description = "Multiple Header Types " + string.Join(", ", properties.Select(p => p.Name)),
				Properties = properties,
				IsMultiple = true
			};
			responseHeadersObjects.Add(new KeyValuePair<string, ApiObject>(name, apiObject));

			generatedMethod.ResponseHeaderType = ClientGeneratorMethod.ModelsNamespacePrefix + name;
		}
        public void should_clean_objects_not_used_as_return_types_client()
        {
            var property = new Property
            {
                Name = "Prop1",
                Type = CollectionTypeHelper.GetCollectionType("Object2"),
                OriginalName = "prop1"
            };

            var property2 = new Property
            {
                Name = "Prop2",
                Type = "int",
                OriginalName = "prop1"
            };

            var o1 = new ApiObject
            {
                Name = "Object1",
                Properties = new[] { property }
            };

            var o2 = new ApiObject
            {
                Name = "Object2",
                IsArray = true,
                Properties = new[] { property2 }
            };

            var o3 = new ApiObject
            {
                Name = "Object3",
                IsArray = true,
                Properties = new[] { property }
            };

            var schemaResponseObjects = new Dictionary<string, ApiObject>();
            schemaResponseObjects.Add("obj1", o1);
            schemaResponseObjects.Add("obj2", o2);
            schemaResponseObjects.Add("obj3", o3);

            var schemaRequestObjects = new Dictionary<string, ApiObject>();
            var cleaner = new ApiObjectsCleaner(schemaRequestObjects, schemaResponseObjects, new Dictionary<string, ApiObject>());
            var classObjects = new List<ClassObject>();

            var methods = new Collection<ClientGeneratorMethod>
            {
                new ClientGeneratorMethod
                {
                    ReturnType = CollectionTypeHelper.GetCollectionType("Object1")
                }
            };
            classObjects.Add(new ClassObject
            {
                Name = "Class1",
                Methods = methods
            });

            cleaner.CleanObjects(classObjects, schemaResponseObjects, cleaner.IsUsedAsResponseInAnyMethod);

            Assert.AreEqual(2, schemaResponseObjects.Count);
            Assert.IsTrue(schemaResponseObjects.ContainsKey("obj1"));
            Assert.IsTrue(schemaResponseObjects.ContainsKey("obj2"));
            Assert.IsFalse(schemaResponseObjects.ContainsKey("obj3"));
        }
Exemple #41
0
		public static async Task<string> PostRun (long runId, ApiObject contentObject)
		{
			return await HttpApi.Post (String.Format ("/run/{0}", runId), null, contentObject);
		}
Exemple #42
0
		// amend existing runset
		public static async Task<string> AmendRunset (long runsetId, ApiObject contentObject)
		{
			return await Post (String.Format ("/runset/{0}", runsetId), null, contentObject);
		}
Exemple #43
0
		private static async Task<string> Delete (string path, IDictionary<string, string> args, ApiObject contentObject)
		{
			return await Helper.RunWithRetry (() => Send ("DELETE", path, args, contentObject));
		}
        private static bool HasDuplicatedObjects(IDictionary<string, ApiObject> objects, CodeNamespace codeNamespace)
        {
            foreach (CodeTypeDeclaration typeDeclaration in codeNamespace.Types)
            {
                var obj = new ApiObject {Name = typeDeclaration.Name};

                if (objects.ContainsKey(obj.Name) || objects.Any(o => o.Value.Name == obj.Name))
                    return true;

                objects.Add(obj.Name, obj);
            }
            return false;
        }