public async void TestRollbackTransaction()
        {
            var expectedCountry = new Country()
            {
                CountryID = "555", CountryName = "NOM COUNTRY"
            };
            var context = new NeoContext(Driver);
            await context.UseTransaction((transaction) =>
            {
                transaction.Insert("CREATE (:Country { CountryID: '555' , countryName: 'NOM COUNTRY'})").GetAwaiter().GetResult();
                var shouldBeNull = context.QueryDefault <Country>("MATCH (n:Country { CountryID: '555' }) RETURN n").GetAwaiter().GetResult();
                Assert.Null(shouldBeNull);
                var resultCountry = transaction.QueryDefault <Country>("MATCH (n:Country { CountryID: '555' }) RETURN n").GetAwaiter().GetResult();
                Assert.True(IsEqual(expectedCountry, resultCountry));
                transaction.RollbackTransaction().GetAwaiter().GetResult();
            });

            var shouldBeNullAgain = await context.QueryDefault <Country>("MATCH (n:Country { CountryID: '555' }) RETURN n");

            Assert.Null(shouldBeNullAgain);
            await context.ExecuteQuery("MATCH (n:Country { CountryID: '555' }) DETACH DELETE n");
        }
示例#2
0
        private async Task Run()
        {
            Console.OutputEncoding = Encoding.Unicode;
            await PrintInfoAsync();

            using (var db = new NeoContext()) {
                db.Database.EnsureCreated();
            }
            EnsureConfigExists();

            _client = new DiscordSocketClient(new DiscordSocketConfig {
                LogLevel         = LogSeverity.Info,
                MessageCacheSize = 5000
            });

            await _client.LoginAsync(TokenType.Bot, Configuration.Load().Token);

            await NeoConsole.Append("Logging in...", ConsoleColor.Cyan);

            await _client.StartAsync();

            await NeoConsole.NewLine("Success...", ConsoleColor.Cyan);

            _services = new ServiceCollection()
                        .AddSingleton(_client)
                        .AddSingleton <CommandHandler>()
                        .AddSingleton <InteractiveService>()
                        .BuildServiceProvider();
            await NeoConsole.NewLine("Activating Services...\nDone.", ConsoleColor.Cyan);

            await _services.GetRequiredService <CommandHandler>().Install(_client, _services);

            await NeoConsole.NewLine("Command Handler starting...\nDone.\n", ConsoleColor.Cyan);

            _client.Log   += Log;
            _client.Ready += _client_Ready;

            await Task.Delay(-1);
        }
        public async void TestMultipleQuery()
        {
            var expectedDic = new Dictionary <string, Country>()
            {
                { "186", new Country()
                  {
                      CountryID = "186", CountryName = "Russia"
                  } },
                { "216", new Country()
                  {
                      CountryID = "216", CountryName = "United States"
                  } }
            };
            var context = new NeoContext(Driver);
            var result  = await context.QueryMultiple <Country>("match(n:Country) WHERE n.countryID IN ['186','216'] return n");

            Assert.NotNull(result);
            Assert.True(result.Count() == expectedDic.Count);
            foreach (var country in result)
            {
                Assert.True(IsEqual(country, expectedDic[country.CountryID]));
            }
        }
示例#4
0
        private async Task HandleTag(SocketUserMessage e)
        {
            using (var db = new NeoContext()) {
                if (!db.Tags.Any(t =>
                                 t.Trigger == e.Content))
                {
                    return;
                }
                var obj = db.Tags.FirstOrDefault(t => t.Trigger == e.Content);
                if (obj.IfAttachment)
                {
                    await NeoConsole.Log(LogSeverity.Critical, "TAG", obj.Value);

                    //await e.Channel.SendFileAsync(obj.Value,"henlo");
                    await e.Channel.SendMessageAsync("", false, NeoEmbeds.Picture(obj.Value, e.Author));
                }
                else
                {
                    await e.Channel.SendMessageAsync(obj.Value);
                }
                db.SaveChanges();
            }
        }
        public async void TestGetNOMRecordsGetSinglePropertiesWithParameters()
        {
            var expectedDic = new Dictionary <string, Country>()
            {
                { "186", new Country()
                  {
                      CountryID = "186", CountryName = "Russia"
                  } },
                { "216", new Country()
                  {
                      CountryID = "216", CountryName = "United States"
                  } }
            };
            var resultDic = new Dictionary <string, Country>();
            var context   = new NeoContext(Driver);
            var result    = await context.GetNeoDataRecordsAsync("match(n:Country) WHERE n.countryID IN [$p1,$p2] return n", new Dictionary <string, object>()
            {
                { "p1", "186" },
                { "p2", "216" }
            });

            Assert.NotNull(result);
            foreach (var neoRecord in result)
            {
                Country c = new Country()
                {
                    CountryID   = neoRecord.GetSingleProperty <string>("n", "countryID"),
                    CountryName = (string)neoRecord.GetSingleProperty("n", "countryName")
                };
                resultDic.Add(c.CountryID, c);
            }
            foreach (var country in expectedDic.Values)
            {
                Assert.True(IsEqual(country, resultDic[country.CountryID]));
            }
        }
示例#6
0
            public async Task playBet([Summary("bet amount")] int cash, [Summary("bet")] int bet)
            {
                var flag1 = false;

                using (var db = new NeoContext()) {
                    if (!db.NeoBet.Any(x => x.ChannelId == Context.Channel.Id))   //no bet
                    {
                        var embed = NeoEmbeds.Error("There is no active bets.", Context.User);
                        await ReplyAsync("", false, embed.Build());
                    }
                    else if (!db.NeoBet.FirstOrDefault(x => x.ChannelId == Context.Channel.Id).open)    //closed bet
                    {
                        var embed = NeoEmbeds.Error("Bet is closed.", Context.User);
                        await ReplyAsync("", false, embed.Build());
                    }
                    else   //yes bet
                    {
                        var uwu = db.NeoBet.FirstOrDefault(x => x.ChannelId == Context.Channel.Id);
                        if (uwu.userBets?.Count > 0)
                        {
                            foreach (var betto in uwu.userBets)
                            {
                                if (betto.User.Id == Context.User.Id)
                                {
                                    var embed = NeoEmbeds.Error("You have already bet.", Context.User);
                                    await ReplyAsync("", false, embed.Build());

                                    flag1 = true;
                                    break;
                                }
                            }
                        }

                        if (flag1 == false)
                        {
                            var maxbet = db.NeoBet.FirstOrDefault(x => x.ChannelId == Context.Channel.Id);
                            var max    = maxbet.Bets.Count;
                            if (bet <= 0 || bet > max)   //thonk
                            {
                                var embed = NeoEmbeds.Error("Wrong bet location.", Context.User);
                                await ReplyAsync("", false, embed.Build());
                            }
                            else
                            {
                                var user = db.Users.FirstOrDefault(x => x.Id == Context.User.Id);
                                if (user.Cash < cash || cash <= 0) //not enough money
                                {
                                    var embed = NeoEmbeds.Error($"Not enough ₺ to play. (Have {user.Cash}₺)", Context.User);
                                    await ReplyAsync("", false, embed.Build());
                                }
                                else     //oh yes time to play baby

                                {
                                    var betobj = db.NeoBet.FirstOrDefault(x => x.ChannelId == Context.Channel.Id);

                                    var newobj = new NeoBets {
                                        BetAmount = cash,
                                        User      = db.Users.FirstOrDefault(a => a.Id == Context.User.Id),
                                        BetLoc    = bet
                                    };

                                    user.Cash -= cash;

                                    betobj.userBets.Add(newobj);

                                    db.Update(user);
                                    db.Update(betobj);
                                    db.SaveChanges();

                                    var embed = NeoEmbeds.Success($"Bet Accepted.", Context.User);
                                    await ReplyAsync("", false, embed.Build());
                                }
                            }
                        }
                    }
                }
            }
示例#7
0
            public async Task CreateBet([Summary("The bet"), Remainder] string betname)
            {
                using (var db = new NeoContext()) {
                    if (db.NeoBet.Any(x => x.ChannelId == Context.Channel.Id))   //there is a bet
                    {
                        var embed = NeoEmbeds.Error("There is already a bet going.", Context.User);
                        await ReplyAsync("", false, embed.Build());
                    }
                    else     //Create bet
                    {
                        var    tuples  = new List <Tuple <string, double> >();
                        var    count   = 0;
                        double answer2 = 0.0;

                        var msg = await ReplyAsync("How many rates?");

                        var response = await NextMessageAsync(true, true, TimeSpan.FromSeconds(30));

                        if (response != null)
                        {
                            if (int.TryParse(response.Content, out count))
                            {
                                if (count <= 0 || count >= 5)
                                {
                                    await ReplyAndDeleteAsync("Please give a number either bigger than 0 or lower than 5.", false, null, TimeSpan.FromSeconds(5));
                                }
                                else     // we gucci lets get the nay nays
                                {
                                    for (int index = 0; index < count; index++)
                                    {
                                        var old1 = await ReplyAsync($"Bet {index + 1}:");

                                        var response1 = await NextMessageAsync(true, true, TimeSpan.FromSeconds(30));

                                        if (response1 != null)
                                        {
                                            var old2 = await ReplyAsync($"Bet rate {index + 1}:");

                                            var response2 = await NextMessageAsync(true, true, TimeSpan.FromSeconds(30));

                                            if (response2 != null)
                                            {
                                                if (double.TryParse(response2.Content, out answer2))
                                                {
                                                    tuples.Add(new Tuple <string, double>(response1.Content, answer2));
                                                    var messages = await Context.Channel.GetMessagesAsync(20).FlattenAsync();

                                                    messages = messages.Where(x => x.Id == msg.Id || x.Id == old1.Id || x.Id == old2.Id || x.Id == response.Id || x.Id == response1.Id || x.Id == response2.Id);
                                                    await(Context.Channel as ITextChannel).DeleteMessagesAsync(messages);
                                                }
                                                else
                                                {
                                                    await ReplyAndDeleteAsync("Please give a corrent number.", false, null, TimeSpan.FromSeconds(5));

                                                    await Task.CompletedTask;
                                                }
                                            }
                                            else
                                            {
                                                await ReplyAndDeleteAsync("You did not reply before the timeout.", false, null, TimeSpan.FromSeconds(5));

                                                await Task.CompletedTask;
                                            }
                                        }
                                        else
                                        {
                                            await ReplyAndDeleteAsync("You did not reply before the timeout.", false, null, TimeSpan.FromSeconds(5));

                                            await Task.CompletedTask;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                await ReplyAndDeleteAsync("Please give a number.", false, null, new TimeSpan(0, 0, 5));

                                await Task.CompletedTask;
                            }
                        }
                        else
                        {
                            await ReplyAndDeleteAsync("You did not reply before the timeout.", false, null, new TimeSpan(0, 0, 5));

                            await Task.CompletedTask;
                        }



                        var msgobj = await ReplyAsync("Creating new bet...");

                        var betobj = new NeoBet {
                            BetName   = betname,
                            ChannelId = Context.Channel.Id,
                            open      = true,
                            msgID     = msgobj.Id
                        };
                        foreach (var tple in tuples)
                        {
                            betobj.Bets.Add(new Bet {
                                BetName = tple.Item1,
                                BetRate = tple.Item2
                            });
                        }

                        db.NeoBet.Attach(betobj);
                        db.SaveChanges();

                        var embed = NeoEmbeds.Bet(
                            betobj.BetName,
                            betobj.Bets,
                            0,
                            ""
                            );
                        await msgobj.ModifyAsync(x => { x.Embed = embed.Build(); x.Content = ""; });
                    }
                }
            }
        public async void TestMultipleQueryInclude()
        {
            var expectedDic = new Dictionary <string, Country>()
            {
                { "186", new Country()
                  {
                      CountryID   = "186",
                      CountryName = "Russia",
                      Cities      = new List <City>()
                      {
                          new City()
                          {
                              CityId   = "2654",
                              CityName = "Sochi"
                          },
                          new City()
                          {
                              CityId   = "2675",
                              CityName = "Kazan"
                          },
                          new City()
                          {
                              CityId   = "2657",
                              CityName = "Chelyabinsk"
                          }
                      }
                  } },
                { "15", new Country()
                  {
                      CountryID   = "15",
                      CountryName = "Germany",
                      Cities      = new List <City>()
                      {
                          new City()
                          {
                              CityId   = "325",
                              CityName = "Berlin"
                          },
                      }
                  } }
            };
            var parameters = new Dictionary <string, object>
            {
                { "rsID", "186" },
                { "geID", "15" }
            };
            var countryHolder = new Dictionary <string, Country>();
            var context       = new NeoContext(Driver);
            var result        = await context.QueryMultipleIncludeable <Country, City>("match(n:Country)<-[:EXISTS_IN]-(c:City) WHERE n.countryID IN [$geID,$rsID] return n,c", parameters,
                                                                                       (country, city) =>
            {
                if (!countryHolder.ContainsKey(country.CountryID))
                {
                    countryHolder.Add(country.CountryID, country);
                    country.Cities = new List <City>();
                }
                countryHolder[country.CountryID].Cities.Add(city);
                return(countryHolder.Values);
            }
                                                                                       );

            Assert.NotNull(result);
            Assert.True(result.Count() == expectedDic.Count);
            foreach (var country in result)
            {
                Assert.True(IsEqual(country, expectedDic[country.CountryID]));
            }
        }
示例#9
0
 public UnitOfWork(NeoContext context)
 {
     _context = context;
 }
示例#10
0
 public PessoaRepository(NeoContext context)
     : base(context)
 {
 }
        public async void TestQueryQuadrupleInclude()
        {
            var expected = new Country()
            {
                CountryID   = "216",
                CountryName = "United States",
                Cities      = new List <City>()
                {
                    new City()
                    {
                        CityId   = "3308",
                        CityName = "Chicago",
                        Airports = new List <Airport>()
                        {
                            new Airport()
                            {
                                AirportId       = "3830",
                                AirportName     = "Chicago O'Hare International Airport",
                                IncomingFlights = new List <Flight>()
                                {
                                    new Flight()
                                    {
                                        FlightId = "8879",
                                        Airline  = new Airline()
                                        {
                                            AirlineId = "137"
                                        }
                                    },
                                    new Flight()
                                    {
                                        FlightId = "9999",
                                        Airline  = new Airline()
                                        {
                                            AirlineId = "137"
                                        }
                                    }
                                }
                            },
                            new Airport()
                            {
                                AirportId       = "3747",
                                AirportName     = "Chicago Midway International Airport",
                                IncomingFlights = new List <Flight>()
                                {
                                    new Flight()
                                    {
                                        FlightId = "8858",
                                        Airline  = new Airline()
                                        {
                                            AirlineId = "137"
                                        }
                                    }
                                }
                            }
                        }
                    },
                }
            };
            var countryHolder = new Dictionary <string, Country>();
            var cityHolder    = new Dictionary <string, City>();
            var airportHolder = new Dictionary <string, Airport>();
            var flightHolder  = new Dictionary <string, Flight>();
            var parameters    = new Dictionary <string, object>
            {
                { "Country", "United States" },
                { "City", "Chicago" }
            };
            var context = new NeoContext(Driver);
            var result  = await context.QueryDefaultIncludeable <Country, City, Airport, Flight, Airline>("match(n:Country {countryName:$Country})<-[e:EXISTS_IN]-(c:City {cityName:$City})<-[:IS_IN]-(a:Airport)<-[:DESTINATION]-(f:Flight)-[:OF]->(al:Airline) return n,c,a,f,al", parameters,
                                                                                                          (country, city, airport, incFlight, airline) =>
            {
                if (!countryHolder.ContainsKey(country.CountryID))
                {
                    countryHolder.Add(country.CountryID, country);
                    country.Cities = new List <City>();
                }
                if (!cityHolder.ContainsKey(city.CityId))
                {
                    cityHolder.Add(city.CityId, city);
                    countryHolder[country.CountryID].Cities.Add(city);
                    city.Airports = new List <Airport>();
                }
                if (!airportHolder.ContainsKey(airport.AirportId))
                {
                    airportHolder.Add(airport.AirportId, airport);
                    cityHolder[city.CityId].Airports.Add(airport);
                    airport.IncomingFlights = new List <Flight>();
                }
                if (!flightHolder.ContainsKey(incFlight.FlightId))
                {
                    flightHolder.Add(incFlight.FlightId, incFlight);
                    airportHolder[airport.AirportId].IncomingFlights.Add(incFlight);
                    incFlight.Airline = airline;
                }
                return(countryHolder[country.CountryID]);
            }
                                                                                                          );

            Assert.NotNull(result);
            Assert.True(IsEqual(result, expected));
        }
示例#12
0
 public Repository(NeoContext context)
 {
     Db    = context;
     DbSet = Db.Set <TEntity>();
 }
示例#13
0
            public async Task Away([Summary("Time and/or Reason")][Remainder] string reason = null)
            {
                using (var db = new NeoContext()) {
                    if (db.Afks.Any(afk => afk.User == db.Users.FirstOrDefault(u => u.Id == Context.User.Id))) //user is afk so he is back now
                    {
                        var obj = db.Afks.FirstOrDefault(afk => afk.User == db.Users.FirstOrDefault(u => u.Id == Context.User.Id));
                        if (string.IsNullOrEmpty(obj?.Reason))
                        {
                            var embed = NeoEmbeds.Afk($"{Context.User} is back!", Context.User);
                            await ReplyAsync("", false, embed.Build());
                        }
                        else
                        {
                            var embed = NeoEmbeds.Afk($"{Context.User} is back from {obj.Reason.TrimStart()}!", Context.User);
                            await ReplyAsync("", false, embed.Build());
                        }
                        db.Afks.Attach(obj ?? throw new InvalidOperationException());
                        db.Afks.Remove(obj);
                        db.SaveChanges();
                    }
                    else
                    {
                        var obj = new Afk();
                        if (reason != null)                                                                                  // there is time and or reason
                        {
                            var time = reason.Substring(0, reason.IndexOf(' ') <= -1 ? reason.Length : reason.IndexOf(' ')); // get first block
                            if (CheckTimeString(time))                                                                       //check if first block is time string
                            {
                                var timestr = HandleTime(time);                                                              //get timespan from that block
                                reason = reason.Replace(time, "");                                                           //get time out of reason
                                if (reason.Length == 0)
                                {
                                    var embed = NeoEmbeds.Afk($"{Context.User} is now afk!", Context.User, null, Thing(timestr));
                                    await ReplyAsync("", false, embed.Build());

                                    obj.Reason = null;
                                    obj.Time   = (DateTime.Now + timestr);
                                    obj.User   = db.Users.FirstOrDefault(u => u.Id == Context.User.Id);
                                }
                                else
                                {
                                    var embed = NeoEmbeds.Afk($"{Context.User} is now afk!", Context.User, reason, Thing(timestr));
                                    await ReplyAsync("", false, embed.Build());

                                    obj.Reason = reason;
                                    obj.Time   = (DateTime.Now + timestr);
                                    obj.User   = db.Users.FirstOrDefault(u => u.Id == Context.User.Id);
                                }
                            }
                            else  //no time just reason
                            {
                                var embed = NeoEmbeds.Afk($"{Context.User} is now afk!", Context.User, reason);
                                await ReplyAsync("", false, embed.Build());

                                obj.Reason = reason;
                                obj.Time   = default(DateTime);
                                obj.User   = db.Users.FirstOrDefault(u => u.Id == Context.User.Id);
                            }
                        }
                        else  //no reason and time
                        {
                            var embed = NeoEmbeds.Afk($"{Context.User} is now afk!", Context.User);
                            await ReplyAsync("", false, embed.Build());

                            obj.Reason = null;
                            obj.Time   = default(DateTime);
                            obj.User   = db.Users.FirstOrDefault(u => u.Id == Context.User.Id);
                        }
                        db.Afks.Add(obj);
                        db.SaveChanges();
                    }
                }
            }
示例#14
0
        private async Task HandleCommand(SocketMessage s)
        {
            var msg = s as SocketUserMessage;

            if (msg == null)
            {
                return;                                           // Check if the received message is from a user.
            }
            var context = new SocketCommandContext(_client, msg); // Create a new command context.

            if (context.User.IsBot)
            {
                return;
            }
            var prefix = Configuration.Load().Prefix;

            using (var db = new NeoContext()) {
                if (!db.Users.Any(x => x.Id == msg.Author.Id)) //if user does net exist in database create it
                {
                    var newobj = new DbUser {
                        Id   = msg.Author.Id,
                        Cash = 500
                    };
                    db.Users.Add(newobj);
                    db.SaveChanges();
                }
                if (!(msg.Channel is ISocketPrivateChannel) && db.Guilds.Any(x => x.Id == (msg.Channel as IGuildChannel).GuildId))
                {
                    prefix = db.Guilds.FirstOrDefault(x => x.Id == (msg.Channel as IGuildChannel).GuildId).Prefix ?? Configuration.Load().Prefix;
                }
                if (db.Blacklist.Any(bl => bl.User == db.Users.FirstOrDefault(u => u.Id == context.User.Id)))
                {
                    return;
                }
            }

            await CheckAfk(msg);
            await HandleTag(msg);

            await NeoConsole.Log(msg);

            var argPos = 0;                                     // Check if the message has either a string or mention prefix.

            if (msg.HasStringPrefix(prefix, ref argPos) ||
                msg.HasStringPrefix(Configuration.Load().Prefix, ref argPos) ||
                msg.HasMentionPrefix(_client.CurrentUser, ref argPos))
            {
                IResult result; // Try and execute a command with the given context.
                try {
                    result = await _cmds.ExecuteAsync(context, argPos, _services);

                    if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                    {
                        var embed = NeoEmbeds.Error(result.ErrorReason, context.User, result.Error != null ? result.Error.ToString() : "Error").Build();
                        await context.Channel.SendMessageAsync("", false, embed);
                    }
                } catch (Exception ex) {
                    var embed = NeoEmbeds.Minimal(ex.Message).AddField("inner", ex.InnerException?.Message ?? "nope");
                    await NeoConsole.NewLine(ex.StackTrace);

                    await context.Channel.SendMessageAsync("", false, embed.Build());
                }
            }
        }
示例#15
0
 public NeoRepository(IDriver driver, string database, NeoContext context)
 {
     _driver         = driver;
     _context        = context;
     _sessionBuilder = o => o.WithDatabase(database);
 }