Exemple #1
0
        /// <summary>
        /// Method that creates a customized gambling game.
        /// </summary>
        /// <param name="context">The context for guild data information and the channel to send the reply.</param>
        /// <param name="bet">The amount of money bet.</param>
        /// <param name="odds">The odds on 100 of winning.</param>
        /// <param name="payoutMultiplier">The payout multiplier of the original bet.</param>
        public async Task GambleAsync(DEAContext context, decimal bet, decimal odds, decimal payoutMultiplier)
        {
            var gambleChannel = context.Guild.GetTextChannel(context.DbGuild.GambleChannelId);

            if (gambleChannel != null && context.Channel.Id != context.DbGuild.GambleChannelId)
            {
                throw new DEAException($"You may only gamble in {gambleChannel.Mention}!");
            }
            else if (bet < Config.BET_MIN)
            {
                throw new DEAException($"Lowest bet is {Config.BET_MIN}$.");
            }
            else if (bet > context.DbUser.Cash)
            {
                throw new DEAException($"You do not have enough money. Balance: {context.DbUser.Cash.USD()}.");
            }

            decimal roll = Config.RAND.Next(1, 10001) / 100m;

            if (roll >= odds)
            {
                await _userRepo.EditCashAsync(context, bet *payoutMultiplier);

                await context.Channel.ReplyAsync(context.User, $"You rolled: {roll.ToString("N2")}. Congrats, you won " +
                                                 $"{(bet * payoutMultiplier).USD()}! Balance: {context.DbUser.Cash.USD()}.");
            }
            else
            {
                await _userRepo.EditCashAsync(context, -bet);

                await context.Channel.ReplyAsync(context.User, $"You rolled: {roll.ToString("N2")}. Unfortunately, you lost " +
                                                 $"{bet.USD()}. Balance: {context.DbUser.Cash.USD()}.");
            }
        }
Exemple #2
0
        /// <summary>
        /// Creates a poll.
        /// </summary>
        /// <param name="context">Context of the command use.</param>
        /// <param name="name">Name of the poll.</param>
        /// <param name="choices">Choices in the poll.</param>
        /// <param name="length">Length of the poll before deletion.</param>
        /// <param name="elderOnly">Whether the poll can only be voted on by elder users.</param>
        /// <param name="modOnly">Whether the poll can only be voted on moderators.</param>
        /// <param name="createdByMod">Whether the poll was created by a moderator.</param>
        /// <returns>A task returning a poll.</returns>
        public async Task <Poll> CreatePollAsync(DEAContext context, string name, string[] choices, TimeSpan?length = null, bool elderOnly = false, bool modOnly = false, bool createdByMod = false)
        {
            if (await ExistsAsync(x => x.Name.ToLower() == name.ToLower() && x.GuildId == context.Guild.Id))
            {
                throw new DEAException($"There is already a poll by the name \"{name}\".");
            }
            else if (name.Length > Config.MAX_POLL_SIZE)
            {
                throw new DEAException($"The poll name may not be larger than {Config.MAX_POLL_SIZE} characters.");
            }
            else if (length.HasValue && length.Value.TotalMilliseconds > Config.MAX_POLL_LENGTH.TotalMilliseconds)
            {
                throw new DEAException($"The poll length may not be longer than one week.");
            }

            var createdPoll = new Poll(context.User.Id, context.Guild.Id, name, choices)
            {
                ElderOnly    = elderOnly,
                ModOnly      = modOnly,
                CreatedByMod = createdByMod,
            };

            if (length.HasValue)
            {
                createdPoll.Length = length.Value.TotalMilliseconds;
            }

            await InsertAsync(createdPoll);

            return(createdPoll);
        }
Exemple #3
0
 public static IQueryable <TEntity> GetAll()
 {
     using (var db = new DEAContext())
     {
         return(db.Set <TEntity>());
     }
 }
Exemple #4
0
    void Populate()
    {
        string errorMessage = null;

        if (Session[_contextKey] != null)
        {
            DEAContext context = Session[_contextKey] as DEAContext;
            DataSet    ds      = context.ToDataSet(out errorMessage);
            if (ds != null)
            {
                GridViewProjects.Columns.Clear();
                BoundField bf = new BoundField();
                bf.HeaderText = context.ProjectIDFieldName;
                bf.DataField  = "NAME";
                GridViewProjects.Columns.Add(bf);

                foreach (DataRow r in ds.Tables["VARIABLES"].Rows)
                {
                    string varName = r["NAME"].ToString();
                    bf = new BoundField();
                    bf.HeaderStyle.CssClass      = "text-right";
                    bf.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                    bf.HeaderText       = varName;
                    bf.DataField        = varName;
                    bf.DataFormatString = "{0:f6}";
                    GridViewProjects.Columns.Add(bf);
                }

                bf = new BoundField();
                bf.HeaderStyle.CssClass      = "text-right";
                bf.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                bf.HeaderText       = "Relative Efficiency";
                bf.DataField        = "RELATIVE_Efficiency";
                bf.DataFormatString = "{0:f6}";
                GridViewProjects.Columns.Add(bf);

                if (ds.Tables["CONSTRAINTS"].Rows != null && ds.Tables["CONSTRAINTS"].Rows.Count > 0)
                {
                    bf = new BoundField();
                    bf.HeaderStyle.CssClass      = "text-right";
                    bf.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                    bf.HeaderText = "Selected";
                    bf.DataField  = "SELECTED";
                    bf.ReadOnly   = true;
                    GridViewProjects.Columns.Add(bf);
                }

                bf = new BoundField();
                bf.HeaderStyle.CssClass = "text-right";
                bf.HeaderText           = "Approximate";
                bf.DataField            = "APPROXIMATE";
                bf.DataFormatString     = "{0}";
                GridViewProjects.Columns.Add(bf);

                GridViewProjects.DataSource = ds.Tables["PROJECTS"];
                GridViewProjects.DataBind();
            }
        }
    }
Exemple #5
0
    protected void ButtonRun_Click(object sender, EventArgs e)
    {
        string errorMessage = null;

        try
        {
            DEAContext context = Session[_contextKey] as DEAContext;
            string     jsonIn  = context.ToJsonString(out errorMessage);
            if (string.IsNullOrEmpty(jsonIn))
            {
                throw new Exception(errorMessage);
            }
            string serviceUrl = ConfigurationManager.AppSettings["deaServiceUrl"];
            var    client     = new RestClient();
            client.BaseUrl = new Uri(serviceUrl);
            RestRequest deaRequest = new RestRequest();
            deaRequest.Method = Method.POST;
            deaRequest.AddParameter("text/plain", jsonIn, ParameterType.RequestBody);
            deaRequest.Resource = "json/DEA";
            var response = client.Execute(deaRequest);
            if (response.IsSuccessful && response.ResponseStatus == ResponseStatus.Completed)
            {
                string      jsonOut     = response.Content;
                DEAResponse deaResponse = JsonConvert.DeserializeObject <DEAResponse>(jsonOut);
                if (deaResponse == null)
                {
                    throw new Exception("Unable to de-serialize JSON response.  Please check the log of the service.");
                }
                if (deaResponse.OK == false)
                {
                    throw new Exception(deaResponse.errorMessage);
                }
                Session[_contextKey] = deaResponse.context;
                DEAEventArgs args = new DEAEventArgs();
                args.Cargo = "DEAContextOK";
                RaiseBubbleEvent(this, args);
            }
            else
            {
                if (!string.IsNullOrEmpty(response.ErrorMessage))
                {
                    throw new Exception(response.ErrorMessage);
                }
                else
                {
                    throw new Exception(response.ResponseStatus.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            LabelError.Text    = ex.Message;
            LabelError.Visible = true;
            DEAEventArgs args = new DEAEventArgs();
            args.Cargo = "ERROR: " + ex.Message;
            RaiseBubbleEvent(this, args);
        }
    }
Exemple #6
0
 public static async Task UpdateAsync(TEntity entity)
 {
     using (var db = new DEAContext())
     {
         db.Set <TEntity>().Add(entity);
         db.Entry(entity).State = EntityState.Modified;
         await db.SaveChangesAsync();
     }
 }
Exemple #7
0
 public static async Task DeleteAsync(TEntity entity)
 {
     using (var db = new DEAContext())
     {
         db.Set <TEntity>().Remove(entity);
         db.Entry(entity).State = EntityState.Deleted;
         await db.SaveChangesAsync();
     }
 }
Exemple #8
0
        /// <summary>
        /// Modifies a user's cash.
        /// </summary>
        /// <param name="context">The context of the command use.</param>
        /// <param name="change">The +/- change on the user's cash.</param>
        public async Task EditCashAsync(DEAContext context, decimal change)
        {
            var newCash = Math.Round(context.Cash + change, 2);

            context.Cash        = newCash;
            context.DbUser.Cash = newCash;
            await UpdateAsync(context.DbUser);

            await _rankHandler.HandleAsync(context.Guild, context.User as IGuildUser, context.DbGuild, context.DbUser);
        }
Exemple #9
0
        public void TestXmlSerializationInRequestMode()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath  = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.csv";
            string xmlFilePath  = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots-4.xml";
            string xmlFilePath2 = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots-5.xml";

            bool       ok      = true;
            DEAContext context = new DEAContext("DEAContext", "Depot");

            ok = context.AddVariable("STOCK", "I", 1.0, out errorMessage);
            if (ok)
            {
                ok = context.AddVariable("WAGES", "I", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("ISSUES", "O", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("RECEIPTS", "O", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("REQS", "O", 1.0, out errorMessage);
            }

            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }


            if (ok)
            {
                ok = context.SaveToXmlFile(xmlFilePath, out errorMessage);
                Assert.IsTrue(ok, errorMessage);
            }

            if (ok)
            {
                DEAContext context2 = DEAContext.CreateFromXmlFile(xmlFilePath, out errorMessage);
                Assert.IsNotNull(context2, errorMessage);
                if (context2 != null)
                {
                    ok = context2.SaveToXmlFile(xmlFilePath2, out errorMessage);
                    Assert.IsTrue(ok, errorMessage);
                }
            }
        }
Exemple #10
0
        public void TestCaltransBad()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath = @"C:\Projects\NCHRP 08-103\CALTRANS_PROJECTS.csv";
            string xmlFilePath = @"C:\Projects\NCHRP 08-103\CALTRANS_PROJECTS.xml";


            DEAContext context = new DEAContext("DEAContext", "Project");
            bool       ok      = context.AddVariable("Cost", "I", out errorMessage);

            if (ok)
            {
                ok = context.AddVariable("Goal 1", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Goal 2", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Goal 3", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Goal 4", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Goal 5", "O", out errorMessage);
            }

            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }

            if (ok)
            {
                ok = context.RunDEA(out errorMessage);
            }

            if (ok)
            {
                ok = context.SaveToXmlFile(xmlFilePath, out errorMessage);
            }

            Assert.IsTrue(ok, errorMessage);
        }
Exemple #11
0
        /// <summary>
        /// If the moderation log channel exists, it will log all moderation commands.
        /// </summary>
        /// <param name="context">The context of the command use.</param>
        /// <param name="action">The action that was taken.</param>
        /// <param name="color">The color of the embed.</param>
        /// <param name="reason">The reason for the action.</param>
        /// <param name="subject">The user in question.</param>
        /// <param name="extra">An extra line for more information.</param>
        public async Task ModLogAsync(DEAContext context, string action, Color color, string reason, IUser subject = null, string extra = "")
        {
            var channel = context.Guild.GetTextChannel(context.DbGuild.ModLogChannelId);

            if (channel == null)
            {
                return;
            }

            EmbedFooterBuilder footer = new EmbedFooterBuilder()
            {
                IconUrl = "http://i.imgur.com/BQZJAqT.png",
                Text    = $"Case #{context.DbGuild.CaseNumber}"
            };
            EmbedAuthorBuilder author = new EmbedAuthorBuilder()
            {
                IconUrl = context.User.GetAvatarUrl(),
                Name    = $"{context.User.Username}#{context.User.Discriminator}"
            };

            string userText = string.Empty;

            if (subject != null)
            {
                userText = $"\n**User:** {subject} ({subject.Id})";
            }

            var description = $"**Action:** {action}{extra}{userText}";

            if (reason != null)
            {
                description += $"\n**Reason:** {reason}";
            }

            var builder = new EmbedBuilder()
            {
                Author      = author,
                Color       = color,
                Description = description,
                Footer      = footer
            }.WithCurrentTimestamp();

            try
            {
                await channel.SendMessageAsync(string.Empty, embed : builder);

                await _guildRepo.ModifyAsync(context.DbGuild, x => x.CaseNumber++);
            }
            catch { }
        }
Exemple #12
0
        private async void OnTimedTempMultiplierReset(object source, ElapsedEventArgs e)
        {
            foreach (User user in BaseRepository <User> .GetAll())
            {
                if (user.TemporaryMultiplier != 1)
                {
                    user.TemporaryMultiplier = 1;
                }
            }

            using (var db = new DEAContext())
            {
                await db.SaveChangesAsync();
            }
        }
Exemple #13
0
 private async void OnTimedApplyInterest(object source, ElapsedEventArgs e)
 {
     foreach (var gang in BaseRepository <Gang> .GetAll())
     {
         var InterestRate = 0.025f + ((gang.Wealth / 100) * .000075f);
         if (InterestRate > 0.1)
         {
             InterestRate = 0.1f;
         }
         gang.Wealth *= 1 + InterestRate;
     }
     using (var db = new DEAContext())
     {
         await db.SaveChangesAsync();
     }
 }
Exemple #14
0
        public Task <IRole> GetRankAsync(DEAContext context, User dbUser)
        {
            IRole role = null;

            if (context.DbGuild.RankRoles.ElementCount != 0 && context.Guild != null)
            {
                foreach (var rankRole in context.DbGuild.RankRoles.OrderBy(x => x.Value))
                {
                    if (dbUser.Cash >= (decimal)rankRole.Value.AsDouble)
                    {
                        role = context.Guild.GetRole(ulong.Parse(rankRole.Name));
                    }
                }
            }

            return(Task.FromResult(role));
        }
Exemple #15
0
        public async Task RunAsync(params string[] args)
        {
            PrettyConsole.NewLine("===   DEA   ===");
            PrettyConsole.NewLine();

            Client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel         = LogSeverity.Error,
                MessageCacheSize = 10,
                TotalShards      = Credentials.ShardCount,
                //AlwaysDownloadUsers = true,
            });

            Client.Log += (l)
                          => Task.Run(()
                                      => PrettyConsole.Log(l.Severity, l.Source, l.Exception?.ToString() ?? l.Message));

            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync
            });

            var sw = Stopwatch.StartNew();
            //Connection
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.StartAsync().ConfigureAwait(false);

            //await Client.DownloadAllUsersAsync().ConfigureAwait(false);
            sw.Stop();
            PrettyConsole.Log(LogSeverity.Info, "Successfully connected", $"Elapsed time: {sw.Elapsed.TotalSeconds.ToString()} seconds.");

            var Map = new DependencyMap();

            ConfigureServices(Map);
            await new MessageRecieved().InitializeAsync(Client, Map);
            new Ready(Client);
            PrettyConsole.Log(LogSeverity.Info, "Events and mapping successfully initialized", $"Client ready.");

            using (var db = new DEAContext())
            {
                await db.Database.EnsureCreatedAsync();
            }
            PrettyConsole.Log(LogSeverity.Info, "Database creation ensured", $"Ready for use.");
        }
Exemple #16
0
        /// <summary>
        /// Creates a gang.
        /// </summary>
        /// <param name="context">Context of the command use.</param>
        /// <param name="name">Name of the gang.</param>
        /// <returns>A task returning the created gang.</returns>
        public async Task <Gang> CreateGangAsync(DEAContext context, string name)
        {
            if (await ExistsAsync(x => x.Name.ToLower() == name.ToLower() && x.GuildId == context.Guild.Id))
            {
                throw new DEAException($"There is already a gang by the name {name}.");
            }
            else if (name.Length > Config.GANG_NAME_CHAR_LIMIT)
            {
                throw new DEAException($"The length of a gang name may not be longer than {Config.GANG_NAME_CHAR_LIMIT} characters.");
            }

            var createdGang = new Gang(context.User.Id, context.Guild.Id, name);

            await InsertAsync(createdGang);

            return(createdGang);
        }
Exemple #17
0
        /// <summary>
        /// Checks whether a user is a moderator.
        /// </summary>
        /// <param name="context">The context to get the guild data information.</param>
        /// <param name="user">The user in question.</param>
        /// <returns>The permission level of the user.</returns>
        public int GetPermLevel(DEAContext context, IGuildUser user)
        {
            var permLevel = 0;

            if (context.DbGuild.ModRoles.ElementCount != 0)
            {
                foreach (var role in context.DbGuild.ModRoles.OrderBy(x => x.Value))
                {
                    if (user.Guild.GetRole(ulong.Parse(role.Name)) != null)
                    {
                        if (user.RoleIds.Any(x => x.ToString() == role.Name))
                        {
                            permLevel = role.Value.AsInt32;
                        }
                    }
                }
            }

            return(user.GuildPermissions.Administrator && permLevel < 2 ? 2 : permLevel);
        }
Exemple #18
0
        public static void Guild()
        {
            var db = new DEAContext();

            var    NewGuild = new guild();
            Random randNum  = new Random();
            var    Num1     = randNum.Next(100000000, 999999999);
            var    Num2     = randNum.Next(100000000, 999999999);
            ulong  GuildId  = (ulong)(Num1 + Num2);

            NewGuild.id = GuildId;
            db.guilds.Add(NewGuild);
            db.SaveChanges();
            Console.WriteLine("Saved New Guild");
            var NewGuildId = NewGuild.id;

            Console.WriteLine(NewGuildId);
            var ResultsGuild = GuildRepository.FetchGuildByIdAsync(999999999123456787);

            Console.WriteLine(ResultsGuild.Result.id);
        }
Exemple #19
0
    bool UploadFiles(out string errorMessage)
    {
        errorMessage = null;
        bool   ok         = true;
        string contextKey = "DEACONTEXT";

        try
        {
            string warningMessage = null;
            Session.Remove(contextKey);
            string projColName = ConfigurationManager.AppSettings["csvProjectIDColumnName"];
            if (string.IsNullOrEmpty(projColName))
            {
                projColName = "Project";
            }
            DEAContext context = new DEAContext("DEAContext", projColName);

            ok = context.LoadVariablesFromCsvFile(VarFilePath, out errorMessage);
            if (ok)
            {
                ok = context.UploadCsvFile(ProjFilePath, out warningMessage, out errorMessage);
            }
            if (ok && !string.IsNullOrEmpty(ConstFilePath))
            {
                ok = context.LoadCsvConstraints(ConstFilePath, out errorMessage);
            }

            Session[contextKey] = context;
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            ok           = false;
        }
        return(ok);
    }
Exemple #20
0
        public void TestJsonSerialization()
        {
            string     errorMessage      = null;
            string     xmlInputFilePath  = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.xml";
            string     xmlOutputFilePath = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots-3.xml";
            DEAContext context           = DEAContext.CreateFromXmlFile(xmlInputFilePath, out errorMessage);

            Assert.IsNotNull(context, errorMessage);
            if (context != null)
            {
                string json = context.ToJsonString(out errorMessage);
                Assert.IsNotNull(json, errorMessage);
                if (json != null)
                {
                    DEAContext context2 = DEAContext.CreateFromJsonString(json, out errorMessage);
                    Assert.IsNotNull(context2, errorMessage);
                    if (context2 != null)
                    {
                        bool ok = context2.SaveToXmlFile(xmlOutputFilePath, out errorMessage);
                        Assert.IsTrue(ok, errorMessage);
                    }
                }
            }
        }
Exemple #21
0
        public Stream RunDEAnalysis(Stream request)
        {
            bool         ok           = true;
            string       errorMessage = null;
            DEAContext   context      = null;
            string       jsonRequest  = null;
            string       jsonResponse = null;
            const string fn           = "RunDEAnalysis";

            LOG.DebugFormat("{0} - started", fn);

            UriTemplateMatch utm = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

            LOG.Debug(utm.RequestUri.OriginalString);

            try
            {
                using (StreamReader reader = new StreamReader(request))
                {
                    jsonRequest = reader.ReadToEnd();
                }

                LOG.DebugFormat("Request: {0}", jsonRequest);

                context = DEAContext.CreateFromJsonString(jsonRequest, out errorMessage);
                ok      = (context != null);
                if (ok)
                {
                    ok = context.RunDEA(out errorMessage);
                    if (ok && context.ConstraintsSet)
                    {
                        ok = context.ApplyCostConstraintsToProjectSelection(out errorMessage);
                    }
                    if (ok)
                    {
                        jsonResponse = context.ToJsonString(out errorMessage);
                        ok           = (jsonResponse != null);
                    }
                }
            }
            catch (Exception ex)
            {
                ok           = false;
                errorMessage = ex.Message;
            }

            DEAResponse response = new DEAResponse();

            response.OK           = ok;
            response.errorMessage = errorMessage;
            response.context      = context;

            jsonResponse = JsonConvert.SerializeObject(response, Formatting.Indented);

            LOG.DebugFormat("Response: {0}", jsonResponse);
            Stream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(s: jsonResponse));

            LOG.DebugFormat("{0} - ended", fn);

            return(ms);
        }
Exemple #22
0
    public void Populate(string err = null)
    {
        string  errorMessage = null;
        DataSet ds           = null;

        try
        {
            if (Session[_contextKey] != null)
            {
                DEAContext context = Session[_contextKey] as DEAContext;
                ds = context.ToDataSet(out errorMessage);
                if (ds != null)
                {
                    GridViewParams.DataSource = ds.Tables["PARAMETERS"];
                    GridViewParams.DataBind();

                    GridViewVars.DataSource = ds.Tables["VARIABLES"];
                    GridViewVars.DataBind();

                    GridViewConst.DataSource = ds.Tables["CONSTRAINTS"];
                    GridViewConst.DataBind();

                    if (ds.Tables["CONSTRAINTS"].Rows == null || ds.Tables["CONSTRAINTS"].Rows.Count < 1)
                    {
                        LabelConst.Visible = false;
                    }

                    GridViewProjects.Columns.Clear();
                    BoundField bf = new BoundField();
                    bf.HeaderText = context.ProjectIDFieldName;
                    bf.DataField  = "NAME";
                    GridViewProjects.Columns.Add(bf);

                    foreach (DataRow r in ds.Tables["VARIABLES"].Rows)
                    {
                        string varName = r["NAME"].ToString();
                        bf = new BoundField();
                        bf.HeaderStyle.CssClass      = "text-right";
                        bf.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                        bf.HeaderText       = varName;
                        bf.DataField        = varName;
                        bf.DataFormatString = "{0:f6}";
                        GridViewProjects.Columns.Add(bf);
                    }
                    GridViewProjects.DataSource = ds.Tables["PROJECTS"];
                    GridViewProjects.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            errorMessage       = ex.Message;
            LabelError.Text    = errorMessage;
            LabelError.Visible = true;
            ButtonRun.Visible  = false;
        }

        if (string.IsNullOrEmpty(errorMessage))
        {
            ButtonRun.Visible = true;
            if (ds != null)
            {
                if (ds.Tables["CONSTRAINTS"].Rows != null && ds.Tables["CONSTRAINTS"].Rows.Count > 0)
                {
                    ButtonRun.ToolTip = "Click to rank projects by their relative efficiency and apply constraints to their selection.";
                }
                else
                {
                    ButtonRun.ToolTip = "Click to rank projects by their relative efficiency.";
                }
            }


            if (!string.IsNullOrEmpty(err))
            {
                LabelError.Text    = err;
                LabelError.Visible = true;
            }
        }
    }
Exemple #23
0
        public void TestDataEnvelopedAnalysis()
        {
            string csvFilePath = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.csv";
            string warningMessage, errorMessage;


            try
            {
                bool       ok      = true;
                DEAContext context = new DEAContext("DEAContext", "Depot");
                ok = context.AddVariable("STOCK", "I", out errorMessage);
                if (ok)
                {
                    ok = context.AddVariable("WAGES", "I", out errorMessage);
                }
                if (ok)
                {
                    ok = context.AddVariable("ISSUES", "O", out errorMessage);
                }
                if (ok)
                {
                    ok = context.AddVariable("RECEIPTS", "O", out errorMessage);
                }
                if (ok)
                {
                    ok = context.AddVariable("REQS", "O", out errorMessage);
                }
                if (ok)
                {
                    ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
                }
                if (ok)
                {
                    ok = context.AddCostConstraint("STOCK", 27.0, out errorMessage);
                }
                if (ok)
                {
                    ok = context.AddCostConstraint("WAGES", 40, out errorMessage);
                }

                if (ok)
                {
                    var client = new RestClient();
                    client.BaseUrl = new Uri(@"http://localhost/DEAJsonService/JsonServiceImpl.svc");
                    var request = new RestRequest();
                    request.Method = Method.POST;
                    // request.AddHeader("Accept", "application/json");
                    // request.RequestFormat = DataFormat.Json;
                    string json = context.ToJsonString(out errorMessage);
                    ok = (json != null);
                    if (ok)
                    {
                        request.AddParameter("text/plain", json, ParameterType.RequestBody);
                        request.Resource = "json/DEA";
                    }
                    var response = client.Execute(request);

                    int stop = 0;
                }

                Assert.IsTrue(ok, errorMessage);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #24
0
        public void TestJsonSerializationInRequestMode()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.csv";
            string xmlFilePath = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots-6.xml";


            bool       ok      = true;
            DEAContext context = new DEAContext("DEAContext", "Depot");

            ok = context.AddVariable("STOCK", "I", 1.0, out errorMessage);
            if (ok)
            {
                ok = context.AddVariable("WAGES", "I", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("ISSUES", "O", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("RECEIPTS", "O", 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("REQS", "O", 1.0, out errorMessage);
            }

            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }

            if (ok)
            {
                string json = context.ToJsonString(out errorMessage);
                Assert.IsNotNull(json, errorMessage);
                if (json != null)
                {
                    DEAContext context2 = DEAContext.CreateFromJsonString(json, out errorMessage);
                    Assert.IsNotNull(context2, errorMessage);
                    ok = (context2 != null);

                    if (ok)
                    {
                        ok = context2.RunDEA(out errorMessage);
                    }

                    if (ok)
                    {
                        ok = context2.AddCostConstraint("STOCK", 27.0, out errorMessage);
                        if (ok)
                        {
                            ok = context2.AddCostConstraint("WAGES", 40, out errorMessage);
                        }
                    }

                    if (ok)
                    {
                        ok = context2.ApplyCostConstraintsToProjectSelection(out errorMessage);
                    }


                    if (ok)
                    {
                        ok = context2.SaveToXmlFile(xmlFilePath, out errorMessage);
                    }

                    Assert.IsTrue(ok, errorMessage);
                }
            }
        }
Exemple #25
0
        public void TestVADataUnconstrained()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath  = @"C:\Projects\NCHRP 08-103\VA_TEST.csv";
            string xmlFilePath  = @"C:\Projects\NCHRP 08-103\VA_TEST.xml";
            string xmlFilePath2 = @"C:\Projects\NCHRP 08-103\VA_TEST-2.xml";

            bool       ok      = true;
            DEAContext context = new DEAContext("DEAContext", "Project");

            ok = context.AddVariable("Cost", "I", 1.0e-6, out errorMessage);
            if (ok)
            {
                ok = context.AddVariable("Congestion", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Safety", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Accessibility", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Environmental Quality", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Economic Development", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("Land Use", "O", out errorMessage);
            }
            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }

            if (ok)
            {
                ok = context.RunDEA(out errorMessage);
            }

            /*
             * if (ok)
             * {
             *  ok = context.AddCostConstraint("STOCK", 27.0, out errorMessage);
             *  if (ok)
             *      ok = context.AddCostConstraint("WAGES", 40, out errorMessage);
             * }
             *
             * if (ok)
             * {
             *  ok = context.ApplyCostConstraintsToProjectSelection(out errorMessage);
             * }
             */
            Assert.IsTrue(ok, errorMessage);

            if (ok)
            {
                DataSet ds = context.ToDataSet(out errorMessage);
                Assert.IsNotNull(ds, errorMessage);
                ok = ds != null;
            }

            if (ok)
            {
                ok = context.SaveToXmlFile(xmlFilePath, out errorMessage);
                Assert.IsTrue(ok, errorMessage);
            }

            if (ok)
            {
                DEAContext context2 = DEAContext.CreateFromXmlFile(xmlFilePath, out errorMessage);
                Assert.IsNotNull(context2, errorMessage);
                if (context2 != null)
                {
                    ok = context2.SaveToXmlFile(xmlFilePath2, out errorMessage);
                    Assert.IsTrue(ok, errorMessage);
                }
            }

            if (ok)
            {
                string json = context.ToJsonString(out errorMessage);
                Assert.IsNotNull(json, errorMessage);
            }
        }
Exemple #26
0
        public void TestVACsvDataUnconstrained()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath      = @"C:\Projects\NCHRP 08-103\VA_TEST_PROJECTS.csv";
            string csvConstFilePath = @"C:\Projects\NCHRP 08-103\VA_TEST_CONSTRAINTS.csv";
            string csvVarFilePath   = @"C:\Projects\NCHRP 08-103\VA_TEST_VARIABLES.csv";
            string xmlFilePath      = @"C:\Projects\NCHRP 08-103\VA_TEST-3.xml";
            string xmlFilePath2     = @"C:\Projects\NCHRP 08-103\VA_TEST-4.xml";

            bool       ok      = true;
            DEAContext context = new DEAContext("DEAContext", "Project");

            ok = context.LoadVariablesFromCsvFile(csvVarFilePath, out errorMessage);
            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }

            if (ok)
            {
                ok = context.LoadCsvConstraints(csvConstFilePath, out errorMessage);
            }
            if (ok)
            {
                ok = context.RunDEA(out errorMessage);
            }


            if (ok)
            {
                ok = context.ApplyCostConstraintsToProjectSelection(out errorMessage);
            }

            Assert.IsTrue(ok, errorMessage);

            if (ok)
            {
                DataSet ds = context.ToDataSet(out errorMessage);
                Assert.IsNotNull(ds, errorMessage);
                ok = ds != null;
            }

            if (ok)
            {
                ok = context.SaveToXmlFile(xmlFilePath, out errorMessage);
                Assert.IsTrue(ok, errorMessage);
            }

            if (ok)
            {
                DEAContext context2 = DEAContext.CreateFromXmlFile(xmlFilePath, out errorMessage);
                Assert.IsNotNull(context2, errorMessage);
                if (context2 != null)
                {
                    ok = context2.SaveToXmlFile(xmlFilePath2, out errorMessage);
                    Assert.IsTrue(ok, errorMessage);
                }
            }

            if (ok)
            {
                string json = context.ToJsonString(out errorMessage);
                Assert.IsNotNull(json, errorMessage);
            }
        }
Exemple #27
0
        public Task HandleCommandFailureAsync(DEAContext context, IResult result, int argPos)
        {
            var args        = context.Message.Content.Split(' ');
            var commandName = args.First().StartsWith(context.DbGuild.Prefix) ? args.First().Remove(0, context.DbGuild.Prefix.Length) : args[1];
            var message     = string.Empty;

            switch (result.Error)
            {
            case CommandError.Exception:
                return(Task.CompletedTask);    // Exceptions are handled by the log event from the command service.

            case CommandError.UnknownCommand:
                foreach (var command in _commandService.Commands)
                {
                    foreach (var alias in command.Aliases)
                    {
                        if (alias.Length < 5)
                        {
                            if (LevenshteinDistance.Compute(commandName, alias) == 1)
                            {
                                message = $"Did you mean `{context.DbGuild.Prefix}{alias.UpperFirstChar()}`?";
                            }
                        }
                        else if (alias.Length < 10)
                        {
                            if (LevenshteinDistance.Compute(commandName, alias) <= 2)
                            {
                                message = $"Did you mean `{context.DbGuild.Prefix}{alias.UpperFirstChar()}`?";
                            }
                        }
                        else
                        {
                            if (LevenshteinDistance.Compute(commandName, alias) <= 3)
                            {
                                message = $"Did you mean `{context.DbGuild.Prefix}{alias.UpperFirstChar()}`?";
                            }
                        }
                    }
                }
                break;

            case CommandError.BadArgCount:
                var cmd = _commandService.Search(context, argPos).Commands.First().Command;
                var cmdNameUpperFirst = commandName.UpperFirstChar();
                var example           = cmd.Parameters.Count == 0 ? string.Empty : $"**Example:** `{context.DbGuild.Prefix}{cmdNameUpperFirst}{cmd.GetExample()}`";

                message = $"You are incorrectly using this command. \n\n**Usage:** `{context.DbGuild.Prefix}{cmdNameUpperFirst}{cmd.GetUsage()}`\n\n" + example;
                break;

            case CommandError.ParseFailed:
                message = $"Invalid number.";
                break;

            case CommandError.UnmetPrecondition:
                if (result.ErrorReason.StartsWith("Command requires guild permission "))
                {
                    var permission = result.ErrorReason.Replace("Command requires guild permission ", string.Empty);
                    permission = Regex.Replace(permission, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled).Trim();
                    message    = $"DEA requires the server pemission \"{permission}\" in order to be able to execute this command.";
                }
                else
                {
                    message = result.ErrorReason;
                }

                break;

            default:
                message = result.ErrorReason;
                break;
            }

            if (!string.IsNullOrWhiteSpace(message))
            {
                return(context.Channel.ReplyAsync(context.User, message, null, Config.ERROR_COLOR));
            }
            else
            {
                return(Task.CompletedTask);
            }
        }
Exemple #28
0
        public void Test20DepotsConstrainedWeights()
        {
            string errorMessage   = null;
            string warningMessage = null;

            string csvFilePath  = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.csv";
            string xmlFilePath  = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots.xml";
            string xmlFilePath2 = @"C:\Projects\NCHRP 08-103\DEA-Example-20-depots-2.xml";

            bool       ok      = true;
            DEAContext context = new DEAContext("DEAContext", "Depot");

            ok = context.AddVariable("STOCK", "I", out errorMessage);
            if (ok)
            {
                ok = context.AddVariable("WAGES", "I", out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("ISSUES", "O", 0.0, 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("RECEIPTS", "O", 0.0, 1.0, out errorMessage);
            }
            if (ok)
            {
                ok = context.AddVariable("REQS", "O", 0.0, 1.0, out errorMessage);
            }

            if (ok)
            {
                ok = context.UploadCsvFile(csvFilePath, out warningMessage, out errorMessage);
            }

            if (ok)
            {
                ok = context.RunDEA(out errorMessage);
            }

            if (ok)
            {
                ok = context.AddCostConstraint("STOCK", 27.0, out errorMessage);
                if (ok)
                {
                    ok = context.AddCostConstraint("WAGES", 40, out errorMessage);
                }
            }

            if (ok)
            {
                ok = context.ApplyCostConstraintsToProjectSelection(out errorMessage);
            }
            Assert.IsTrue(ok, errorMessage);

            if (ok)
            {
                DataSet ds = context.ToDataSet(out errorMessage);
                Assert.IsNotNull(ds, errorMessage);
                ok = ds != null;
            }

            if (ok)
            {
                ok = context.SaveToXmlFile(xmlFilePath, out errorMessage);
                Assert.IsTrue(ok, errorMessage);
            }

            if (ok)
            {
                DEAContext context2 = DEAContext.CreateFromXmlFile(xmlFilePath, out errorMessage);
                Assert.IsNotNull(context2, errorMessage);
                if (context2 != null)
                {
                    ok = context2.SaveToXmlFile(xmlFilePath2, out errorMessage);
                    Assert.IsTrue(ok, errorMessage);
                }
            }

            if (ok)
            {
                string json = context.ToJsonString(out errorMessage);
                Assert.IsNotNull(json, errorMessage);
            }
        }
Exemple #29
0
        public Task HandleCommandAsync(SocketMessage s)
        {
            return(Task.Run(async() =>
            {
                _statistics.MessagesRecieved++;
                var msg = s as SocketUserMessage;
                if (msg == null)
                {
                    return;
                }

                var context = new DEAContext(_client, msg, _serviceProvider);
                if (context.Guild == null)
                {
                    return;
                }

                if (context.User.IsBot)
                {
                    return;
                }

                await context.InitializeAsync();

                int argPos = 0;

                if (msg.HasStringPrefix(context.DbGuild.Prefix, ref argPos) ||
                    msg.HasMentionPrefix(_client.CurrentUser, ref argPos))
                {
                    var perms = (context.Guild.CurrentUser as IGuildUser).GetPermissions(context.Channel as SocketTextChannel);

                    if (!perms.SendMessages || !perms.EmbedLinks)
                    {
                        try
                        {
                            var channel = await context.User.CreateDMChannelAsync();

                            await channel.SendAsync($"DEA cannot execute any commands without the permission to send embedded messages.");
                        }
                        catch { }
                        return;
                    }

                    Logger.Log(LogSeverity.Debug, $"Guild: {context.Guild}, User: {context.User}", msg.Content);

                    var result = await _commandService.ExecuteAsync(context, argPos, _serviceProvider);
                    if (!result.IsSuccess)
                    {
                        await _errorHandler.HandleCommandFailureAsync(context, result, argPos);
                    }
                    else
                    {
                        _statistics.CommandsRun++;
                    }
                }
                else if (msg.Content.Length >= Config.MIN_CHAR_LENGTH)
                {
                    await _userRepo.ApplyCash(context.GUser, context.DbUser, context.DbGuild);
                }
            }));
        }