Exemplo n.º 1
0
    private static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Console.WriteLine("Incorrect command line parameters.");
        }
        else
        {
            try
            {
                var allLinesFromText = File.ReadAllLines(args[0]);
                var allLinesFromQueries = File.ReadAllLines(args[1]);

                var textParser = new TextParser(allLinesFromText);
                textParser.ParseText();

                var queries = new Queries(allLinesFromQueries, textParser);
                queries.ProcessAllRequests();
                queries.AllReplies.Print();
            }
            catch (FileNotFoundException exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
    }
Exemplo n.º 2
0
        private void PopulateVersionButtons(Queries.sp_GetApplicationVersionsDataTable dt)
        {
            if (dt.Rows.Count <= 0)
                return;

            Queries.sp_GetApplicationVersionsRow drow = dt.Where(i => i.Name.Contains("Windows Service")).FirstOrDefault();

            lblWinVersion.Text = "Latest Version: " + drow.version;
        }
 /// <summary>
 /// Creates a new Query Window
 /// </summary>
 /// <param name="queries">Queries object</param>
 public QueryDialog(Queries queries)
 {
     _queries = queries;
     InitializeComponent();
     _resources.Add("Cancel", "Cancel");
     _resources.Add("Instructions", "Type in an MQL query and click Run Queries");
     _resources.Add("RemoveQuery", "Remove Query");
     _resources.Add("RunQueries", "Run");
     _resources.Add("SaveQueries", "Save");
     _resources.Add("WindowTitle", "Run Queries");
     Draw();
 }
        public event EventHandler <Query> Queries; // effectively a chain

        public void PerformQuery(object sender, Query q)
        {
            Queries?.Invoke(sender, q);
        }
Exemplo n.º 5
0
        public override string GetHtml()
        {
            var html = string.Empty;

            /////////////////////
            // fetch data sets
            /////////////////////

            // get the latest stored email entry
            var emailsSnapshotResult = Queries.GetEmailsSnapshot(_date.Date);
            var inbox          = emailsSnapshotResult.Item2;
            var inboxUnread    = emailsSnapshotResult.Item3;
            var sent           = emailsSnapshotResult.Item4;
            var received       = emailsSnapshotResult.Item5;
            var receivedUnread = emailsSnapshotResult.Item6;

            var isToday            = (_date.Date == DateTime.Now.Date);
            var lastUpdatedMinsAgo = Math.Abs((DateTime.Now - emailsSnapshotResult.Item1).TotalMinutes);

            // if database entry is outdated or not there, create a live API call and override entries
            if (emailsSnapshotResult.Item1 == DateTime.MinValue ||                            // no emails stored yet
                (isToday && lastUpdatedMinsAgo > Settings.SaveEmailCountsInterval_InMinutes)) // request is for today and saved results are too old // could not fetch sent emails
            {
                // create and save a new email snapshot (inbox, sent, received)
                var res = Queries.CreateEmailsSnapshot(_date.Date, false);
                inbox          = res.Item1;
                inboxUnread    = res.Item2;
                sent           = res.Item3;
                received       = res.Item4;
                receivedUnread = res.Item5;
            }

            // error (only if no data at all)
            if (sent < 0 && (received < 0 || receivedUnread < 0) && inbox < 0 && inboxUnread < 0)
            {
                return(VisHelper.NotEnoughData(Dict.NotEnoughData));
            }

            // get averages over last 2 months
            var averagesSnapshot = Queries.GetEmailsSnapshotAverages(60);


            /////////////////////
            // HTML
            /////////////////////

            html += "<table>";
            if (sent > Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + sent + "</strong></td><td>emails sent" + FormatAverage(sent, averagesSnapshot.Item3) + "</td></tr>";
            }
            if (received > Settings.NoValueDefault && receivedUnread > Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + (received - receivedUnread) + "</strong></td><td>emails received that are read" + FormatAverage((received - receivedUnread), averagesSnapshot.Item4 - averagesSnapshot.Item5) + "</td></tr>";
            }
            if (received > Settings.NoValueDefault && receivedUnread > Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + receivedUnread + "</strong></td><td>emails received that are unread" + FormatAverage(receivedUnread, averagesSnapshot.Item5) + "</td></tr>";
            }
            if (received > Settings.NoValueDefault && receivedUnread == Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + received + "</strong></td><td>emails received" + FormatAverage(received, averagesSnapshot.Item4) + "</td></tr>";
            }
            if (inbox > Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + inbox + "</strong></td><td>emails in your inbox" + FormatAverage(inbox, averagesSnapshot.Item1) + "</td></tr>";
            }
            if (inboxUnread > Settings.NoValueDefault)
            {
                html += "<tr><td><strong style='font-size:2.5em; color:#007acc;'>" + inboxUnread + "</strong></td><td>unread emails in your inbox" + FormatAverage(inboxUnread, averagesSnapshot.Item2) + "</td></tr>";
            }
            html += "</table>";

            return(html);
        }
Exemplo n.º 6
0
 public T Query <T>(Query q)
 {
     Queries?.Invoke(this, q);
     return((T)q.Result);
 }
Exemplo n.º 7
0
        protected virtual long DoEstimateSubscriberCount(GDID gEmitterNode)
        {
            var count = ForNode(gEmitterNode).LoadOneRow(Queries.CountSubscribers <Row>(gEmitterNode));

            return(count[0].AsLong());
        }
Exemplo n.º 8
0
        public FileServer(string path)
        {
            //Console.WriteLine("Server File not started, because path '" + path + "' does not exist");
            Console.WriteLine("Server File Communication started ... ");
            this.directory = path;

            DirectoryInfo di = new DirectoryInfo(@"C:\CommunicationFile\archive\");

            foreach (FileInfo file in di.GetFiles())
            {
                file.Delete();
            }

            while (true)
            {
                DirectoryInfo   dir    = new DirectoryInfo(directory);
                DirectoryInfo[] _dirs  = dir.GetDirectories();
                FileInfo[]      _files = dir.GetFiles("*.in");
                //Console.WriteLine("File1 " + _files.Length);

                if (dir == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                else
                {
                    foreach (var item in _files)
                    {
                        Console.WriteLine("FileName -> " + item.Name);
                        //readFile = File.ReadAllText(directory + "" + item.Name);
                        readFile = ReadCommand(directory + "" + item.Name);
                        Console.WriteLine("FileRead <- " + readFile);
                        recv = Queries.ParseAnswer(readFile);
                        Console.WriteLine("File -> " + recv);
                        File.WriteAllText(Path.ChangeExtension(directory + "" + item.Name, ".out"), recv);
                        //File.WriteAllText(directory + ".out", recv);


                        if (File.Exists(directory + "/archive/" + item.Name))
                        {
                            File.Delete(directory + "/archive/" + item.Name);
                            File.Move(directory + "" + item.Name, directory + "/archive/" + item.Name);
                        }
                        else
                        {
                            File.Move(directory + "" + item.Name, directory + "/archive/" + item.Name);
                        }
                    }
                }

                //fileName = string.Format("{0}Command_{1}_FormClient", directory, commandNumber);

                //while (!File.Exists(fileName + ".in"))
                //    System.Threading.Thread.Sleep(100);

                //readFile = File.ReadAllText(fileName + ".in");
                //Console.WriteLine("File <- " + readFile);
                //recv = Queries.ParseAnswer(readFile);
                //Console.WriteLine("File -> " + recv);

                //File.WriteAllText(fileName + ".out", recv);

                //if (File.Exists(@"C:\CommunicationFile\archive\Command_" + commandNumber + "_FormClient.in"))
                //{
                //    File.Delete(@"C:\CommunicationFile\archive\Command_" + commandNumber + "_FormClient.in");
                //    File.Move(@"C:\CommunicationFile\Command_" + commandNumber + "_FormClient.in", @"C:\CommunicationFile\archive\Command_" + commandNumber + "_FormClient.in");
                //}
                //else
                //{
                //    File.Move(@"C:\CommunicationFile\Command_" + commandNumber + "_FormClient.in", @"C:\CommunicationFile\archive\Command_" + commandNumber + "_FormClient.in");
                //}
                //commandNumber++;
            }
        }
Exemplo n.º 9
0
        public List <Loanbook_Data> GetLoanBookData()
        {
            var qry = Queries.Raw_Data(this._eclId, this._eclType);

            Log4Net.Log.Info("Started");
            var _lstRaw = DataAccess.i.GetData(qry);

            Log4Net.Log.Info("Selected Raw Data from table");
            Console.WriteLine($"Started after Select - {DateTime.Now}");

            var bt_ead      = new CalibrationInput_EAD_Behavioural_Terms_Processor();
            var bt_ead_data = bt_ead.GetBehaviouralData(this._eclId, this._eclType);


            var threads = _lstRaw.Rows.Count / 500;

            threads = threads + 1;

            var taskLst = new List <Task>();

            var tskStatusLst = new List <TaskStatus> {
                TaskStatus.RanToCompletion, TaskStatus.Faulted, TaskStatus.Canceled
            };

            for (int i = 0; i < threads; i++)
            {
                var sub_LoanBook = _lstRaw.AsEnumerable().Skip(i * 500).Take(500).ToList();

                //var contractIds = sub_LoanBook.Select(o => o.ContractNo).ToList();
                //var sub_payment_schedule = payment_schedule.Where(o => contractIds.Contains(o.ContractRefNo)).ToList();

                var task = Task.Run(() =>
                {
                    RunLoanBookReadJob(sub_LoanBook, bt_ead, bt_ead_data);
                });

                taskLst.Add(task);
            }
            Log4Net.Log.Info($"Select Loanbook data Total Task : {taskLst.Count()}");


            while (0 < 1)
            {
                if (taskLst.All(o => tskStatusLst.Contains(o.Status)))
                {
                    break;
                }
                //Do Nothing
            }
            Console.WriteLine($"Done with all Task {taskLst.Count} - {DateTime.Now}");
            //            lstRaw = lstRaw.OrderBy(o => o.CustomerNo).ThenBy(p=>p.AccountNo).ThenBy(p => p.ContractNo).ToList();
            lstRaw = lstRaw.OrderBy(o => o.ContractId).ToList();



            var groupedLoanBook = new List <List <Loanbook_Data> >();

            threads = lstRaw.Count / 500;
            threads = threads + 1;

            for (int i = 0; i < threads; i++)
            {
                var sub_items = lstRaw.Skip(i * 500).Take(500).ToList();
                if (sub_items.Count > 0)
                {
                    groupedLoanBook.Add(sub_items);
                }
            }


            var allAccountsGrouped = false;

            try
            {
                while (!allAccountsGrouped)
                {
                    allAccountsGrouped = true;
                    for (int i = 1; i < groupedLoanBook.Count; i++)
                    {
                        var lstfromPrev = groupedLoanBook[i - 1].LastOrDefault();
                        var fstfromCurr = groupedLoanBook[i].FirstOrDefault();
                        if (lstfromPrev.ContractId == fstfromCurr.ContractId)
                        {
                            groupedLoanBook[i - 1].Add(fstfromCurr);
                            groupedLoanBook[i].RemoveAt(0);
                            allAccountsGrouped = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }



            taskLst = new List <Task>();

            for (int i = 0; i < groupedLoanBook.Count; i++)
            {
                var sub_lstRaw = groupedLoanBook[i];

                //var contractIds = sub_LoanBook.Select(o => o.ContractNo).ToList();
                //var sub_payment_schedule = payment_schedule.Where(o => contractIds.Contains(o.ContractRefNo)).ToList();

                var task = Task.Run(() =>
                {
                    RunLoanBookDistinctFilterJob(sub_lstRaw);
                });

                taskLst.Add(task);
            }


            while (0 < 1)
            {
                if (taskLst.All(o => tskStatusLst.Contains(o.Status)))
                {
                    break;
                }
                //Do Nothing
            }


            //newLoanBook = lstRaw;

            //Console.WriteLine($"Done with all conversion Output C**t: {newLoanBook.Select(o=>o.ContractId).Distinct().Count()} MainList Count : {lstRaw.Select(o=>o.ContractId).Distinct().Count()} Raw Count : {_lstRaw.Rows.Count} - {DateTime.Now}");

            return(newLoanBook);
        }
        public bool ProcessCalibration(Guid calibrationId, long affiliateId)
        {
            var baseAffPath = Path.Combine(Util.AppSettings.CalibrationModelPath, affiliateId.ToString());

            if (!Directory.Exists(baseAffPath))
            {
                Directory.CreateDirectory(baseAffPath);
            }



            var qry = Queries.CalibrationInput_EAD_Behavioural_Terms(calibrationId);
            var _dt = DataAccess.i.GetData(qry);

            //DataView dv = _dt.DefaultView;
            //dv.Sort = "Account_No,Contract_No,Snapshot_Date";
            var dt       = _dt;// dv.ToTable();
            var rowCount = dt.Rows.Count + 1;

            if (dt.Rows.Count == 0)
            {
                return(true);
            }

            var counter = Util.AppSettings.GetCounter(dt.Rows.Count + 48);

            var path  = $"{Path.Combine(Util.AppSettings.CalibrationModelPath, counter.ToString(), "EAD_Behavioural_Term.xlsx")}";
            var path1 = $"{Path.Combine(baseAffPath, $"{Guid.NewGuid().ToString()}_EAD_Behavioural_Term.xlsx")}";
            var path2 = $"{Path.Combine(baseAffPath)}";

            Log4Net.Log.Info(path);
            if (File.Exists(path1))
            {
                try { File.Delete(path1); } catch { };
            }

            Log4Net.Log.Info($"Output File Path - {path1}");

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var package = new ExcelPackage(new FileInfo(path)))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[2];//.FirstOrDefault();

                Log4Net.Log.Info("Read Base File");
                // get number of rows in the sheet
                int rows = worksheet.Dimension.Rows; // 10
                                                     //for (int i = 0; i < dt.Rows.Count - 48; i++)
                                                     //{
                                                     //    worksheet.InsertRow(1, 1, 2);
                                                     //}

                //1 is for header
                //48 is for computation done on the excel
                worksheet.DeleteRow(dt.Rows.Count + 1 + 48, rows - (dt.Rows.Count + 1));
                // loop through the worksheet rows

                //var result_=worksheet.Cells[3, 1,34,3].Value;


                package.Workbook.CalcMode = ExcelCalcMode.Automatic;

                for (int i = 0; i < dt.Rows.Count; i++)// DataRow dr in dt.Rows)
                {
                    Log4Net.Log.Info(i);
                    DataRow dr  = dt.Rows[i];
                    var     itm = DataAccess.i.ParseDataToObject(new EAD_Behavioural_Terms_Data(), dr);

                    if (string.IsNullOrEmpty(itm.Account_No) && string.IsNullOrEmpty(itm.Contract_No) && itm.Snapshot_Date == null)
                    {
                        continue;
                    }

                    worksheet.Cells[i + 2, 1].Value = itm.Customer_No ?? "";
                    worksheet.Cells[i + 2, 2].Value = itm.Account_No ?? "";
                    worksheet.Cells[i + 2, 3].Value = itm.Contract_No ?? "";
                    worksheet.Cells[i + 2, 4].Value = itm.Customer_Name ?? "";
                    if (!itm.Snapshot_Date.ToString().Contains("0001"))
                    {
                        worksheet.Cells[i + 2, 5].Value = itm.Snapshot_Date;
                    }
                    worksheet.Cells[i + 2, 6].Value = itm.Classification ?? "";
                    worksheet.Cells[i + 2, 7].Value = itm.Original_Balance_Lcy;
                    worksheet.Cells[i + 2, 8].Value = itm.Outstanding_Balance_Lcy;
                    worksheet.Cells[i + 2, 9].Value = itm.Outstanding_Balance_Acy;
                    if (!itm.Contract_Start_Date.ToString().Contains("0001"))
                    {
                        worksheet.Cells[i + 2, 10].Value = itm.Contract_Start_Date;
                    }
                    if (!itm.Contract_End_Date.ToString().Contains("0001"))
                    {
                        worksheet.Cells[i + 2, 11].Value = itm.Contract_End_Date;
                    }
                    try { worksheet.Cells[i + 2, 12].Value = Convert.ToDouble(itm.Restructure_Indicator); } catch { worksheet.Cells[i + 2, 12].Value = 0; }
                    worksheet.Cells[i + 2, 13].Value = itm.Restructure_Type ?? "";
                    worksheet.Cells[i + 2, 14].Value = itm.Restructure_Start_Date; // == null ? "" : itm.Restructure_Start_Date;
                    worksheet.Cells[i + 2, 15].Value = itm.Restructure_End_Date;   // == null ? "" : itm.Restructure_End_Date;
                }

                Log4Net.Log.Info("Writing Output File");
                var fi = new FileInfo(path1);

                if (Directory.Exists(baseAffPath))
                {
                    var att1              = fi.Attributes.HasFlag(FileAttributes.ReadOnly);
                    var attr2             = new DirectoryInfo(baseAffPath).Attributes.HasFlag(FileAttributes.ReadOnly);
                    var accessControlList = Directory.GetAccessControl(baseAffPath);
                    var accessRules       = accessControlList.GetAccessRules(true, true,
                                                                             typeof(System.Security.Principal.SecurityIdentifier));
                    foreach (FileSystemAccessRule rule in accessRules)
                    {
                        if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
                        {
                            break;
                        }

                        //if (rule.AccessControlType == AccessControlType.Allow)
                        //    //writeAllow = true;
                        //else if (rule.AccessControlType == AccessControlType.Deny)
                        //    writeDeny = true;
                    }
                }

                package.SaveAs(fi);
                Log4Net.Log.Info("Done Writing Output File");
            }

            string txtLocation = Path.GetFullPath(path1);

            object      _missingValue = System.Reflection.Missing.Value;
            Application excel         = new Application();
            var         theWorkbook   = excel.Workbooks.Open(txtLocation,
                                                             _missingValue,
                                                             false,
                                                             _missingValue,
                                                             _missingValue,
                                                             _missingValue,
                                                             true,
                                                             _missingValue,
                                                             _missingValue,
                                                             true,
                                                             _missingValue,
                                                             _missingValue,
                                                             _missingValue);


            try
            {
                //Sort
                Worksheet calculationSheet = theWorkbook.Sheets[3];
                Range     sortRange        = calculationSheet.Range["A2", "O" + rowCount.ToString()];
                //sortRange.Sort(sortRange.Columns[9], DataOption1: XlSortDataOption.xlSortTextAsNumbers);
                sortRange.Sort(sortRange.Columns[5], DataOption1: XlSortDataOption.xlSortTextAsNumbers);                           //Snapshot date
                sortRange.Sort(sortRange.Columns[3], XlSortOrder.xlDescending, DataOption1: XlSortDataOption.xlSortTextAsNumbers); //Contract No: 3; Account No: 2;

                //refresh and calculate to modify
                theWorkbook.RefreshAll();
                excel.Calculate();
                Log4Net.Log.Info("Reading Output File");
                Worksheet worksheet1 = theWorkbook.Sheets[1];
                Log4Net.Log.Info("Read Sheet 1 of File");
                var Assumption_NonExpired = "";
                try { Assumption_NonExpired = worksheet1.Cells[10, 3].Value.ToString(); } catch { }

                if (Assumption_NonExpired.ToLower().Contains("data"))
                {
                    //Assumption_NonExpired = "0";
                    Assumption_NonExpired = "0";// new Random().Next(2, 25).ToString();
                }

                var Freq_NonExpired = "";
                try { Freq_NonExpired = worksheet1.Cells[10, 4].Value.ToString(); } catch { }

                var Assumption_Expired = "";
                try { Assumption_Expired = worksheet1.Cells[11, 3].Value.ToString(); } catch { }

                if (Assumption_Expired.ToLower().Contains("data"))
                {
                    //Assumption_Expired = "0";
                    Assumption_Expired = "0";// new Random().Next(2, 45).ToString();
                }

                var Freq_Expired = "";
                try { Freq_Expired = worksheet1.Cells[11, 4].Value.ToString(); } catch { }

                theWorkbook.Save();
                theWorkbook.Close(true);
                excel.Quit();
                //File.Delete(path1);

                qry = Queries.CalibrationResult_EAD_Behavioural_Terms_Update(calibrationId, Assumption_NonExpired, Freq_NonExpired, Assumption_Expired, Freq_Expired);
                DataAccess.i.ExecuteQuery(qry);
            }
            catch (Exception ex)
            {
                Log4Net.Log.Error(ex);
                theWorkbook.Save();
                theWorkbook.Close(true);
                excel.Quit();
            }


            return(true);
        }
Exemplo n.º 11
0
        public virtual async Task DeleteFromDatabaseAsync()
        {
            var affectedRows = await DBFactory.GetMySqlDatabase().ExecuteNonQueryAsync(Queries.DeleteMapObject(this));

            if (affectedRows != 1)
            {
                throw new Exception("Error occured during delete. The number of affected rows was unexpected.");
            }
        }
Exemplo n.º 12
0
 public double GetQueryCount()
 {
     return(Queries.Sum(l => l.QueryCount));
 }
Exemplo n.º 13
0
        private async void LoadWriters()
        {
            List <Writer> writers = await _con.QueryAsync <Writer>(Queries.GetAllWriters());

            lstWriter.ItemsSource = writers;
        }
Exemplo n.º 14
0
 public void SaveSetting()
 {
     Common.Setting.Queries = Queries.ToArray();
     Common.SetJsonObject("Setting.json", Common.Setting);
 }
Exemplo n.º 15
0
 public override void UpdateDatabaseTables(int version)
 {
     Queries.UpdateDatabaseTables(version);
 }
Exemplo n.º 16
0
 public override void CreateDatabaseTablesIfNotExist()
 {
     Queries.CreateWindowsActivityTable();
 }
Exemplo n.º 17
0
 protected async Task LoadCategoryAsync(IKey categoryKey)
 {
     Summaries = null;
     Summaries = await Queries.QueryAsync(new ListYearOutcomesForCategory(categoryKey, new YearModel(2015)));
 }
Exemplo n.º 18
0
Arquivo: Ping.cs Projeto: Elk198/Aspid
        public async Task GetCharacter(SocketGuildUser user)
        {
            await Check();

            List <Hero> characters = new List <Hero>();

            SqliteCommand getHero = new SqliteCommand(Queries.GetCharacter(Context.Guild.Id, user.Id), Program.sqliteConnection);

            using (SqliteDataReader reader = getHero.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    foreach (DbDataRecord record in reader)
                    {
                        characters.Add(new Hero
                        {
                            name        = Convert.ToString(record["CHAR_NAME"]),
                            owner       = Convert.ToUInt64(record["CHAR_OWNER"]),
                            description = Convert.ToString(record["DESCRIPTION"])
                        });
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync(Language(21));

                    return;
                }
            }

            if (characters.Count == 1)
            {
                EmbedBuilder builder = new EmbedBuilder();
                SocketUser   guy     = Context.Guild.GetUser(characters[0].owner);
                builder
                .WithColor(Color.DarkBlue)
                .WithTitle(characters[0].name)
                .WithDescription(characters[0].description + Language(20) + user.Mention);
                if (characters[0].image != null)
                {
                    builder.WithImageUrl(characters[0].image);
                }
                await Context.Channel.SendMessageAsync("", false, builder.Build());
            }
            else
            {
                string list = "";
                characters.OrderBy(x => x.name).ToList();
                foreach (Hero hero in characters)
                {
                    list += hero.name;
                    list += "\n";
                }
                EmbedBuilder builder = new EmbedBuilder();
                builder
                .WithDescription(list + $"\n\n{user.Mention}")
                .WithColor(Color.Blue)
                .WithTitle(Language(22));
                await Context.Channel.SendMessageAsync("", false, builder.Build());
            }
        }
Exemplo n.º 19
0
 public virtual async Task <DataMapObject> FromDatabaseAsync()
 {
     // Get a fresh copy of the object from the DB.
     using (var results = await DBFactory.GetMySqlDatabase().DataTableFromQueryStringAsync(Queries.SelectMapObject(this)))
     {
         var newObj = Activator.CreateInstance(this.GetType(), new object[] { results });
         return((DataMapObject)newObj);
     }
 }
Exemplo n.º 20
0
Arquivo: Ping.cs Projeto: Elk198/Aspid
        public async Task Mute(SocketGuildUser user, string timer, [Remainder] string reason = null)
        {
            if (user.IsBot)
            {
                await Context.Message.DeleteAsync();

                return;
            }

            char[] a;
            a = timer.ToCharArray();

            char[] b = new char[a.Count() - 1];

            for (int i = 0; i < b.Count(); i++)
            {
                b[i] = a[i];
            }
            char   time     = a.Last();
            string c        = new string(b);
            int    muteTime = Convert.ToInt32(c);
            int    show     = muteTime;

            string longitud;

            switch (time)
            {
            case 'm': longitud = Language(50); break;

            case 'h': muteTime *= 60; longitud = Language(51); break;

            case 'd': muteTime *= 1440; longitud = Language(52); break;

            case 'w': muteTime *= 10080; longitud = Language(53); break;

            case 'y': muteTime *= 3679200; longitud = Language(54); break;

            default: return;
            }

            await Context.Channel.SendMessageAsync("🔇 " + user.Mention + Language(55) + show + " " + longitud + "**");

            var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Muted");

            SqliteCommand command = new SqliteCommand(Queries.AddMute(Context.Guild.Id, user.Id, (ulong)muteTime), Program.sqliteConnection);
            await command.ExecuteNonQueryAsync();

            await user.AddRoleAsync(role);

            if ((Context.Channel as IGuildChannel).GetPermissionOverwrite(role) == null)
            {
                await Program.AddChannelRestr(Context.Guild);
            }

            var ls = await user.GetOrCreateDMChannelAsync();

            EmbedBuilder builder = new EmbedBuilder();

            if (reason == null)
            {
                reason = Language(56);
            }
            builder.WithTitle(Language(57))
            .WithDescription(Language(58) + Context.Guild.Name + Language(59) + show + " " + longitud + Language(60) + reason)
            .WithColor(Color.Red)
            .WithThumbnailUrl("https://media.discordapp.net/attachments/603600328117583874/615150515709411357/ezgif.com-gif-maker_31.gif")
            .WithCurrentTimestamp();
            await ls.SendMessageAsync("", false, builder.Build());
        }
Exemplo n.º 21
0
 static void Main(string[] args)
 {
     var sqlBookQuery = Queries.SetConnectionStringForBooks();
     var works        = sqlBookQuery.GetBooksByAuthorName("Phillip");
 }
Exemplo n.º 22
0
 public ItemForm()
 {
     InitializeComponent();
     queries = new Queries();
 }
Exemplo n.º 23
0
        public void SetAdmin()
        {
            Queries queries = new Queries();

            queries.ClearTargets();
        }
Exemplo n.º 24
0
 public override void CreateDatabaseTablesIfNotExist()
 {
     Queries.CreateUserEfficiencyTables();
 }
 public ActivitiesView(TGFCContext _ctx, IEnumerable <Claim> _claims)
 {
     CurrentUser   = Queries.GetUserByClaims(_ctx, _claims);
     Disciplines   = Queries.GetAllDisciplines(_ctx);
     ActivityTypes = Queries.GetAllActivityTypes(_ctx);
 }
Exemplo n.º 26
0
        public Query LoadQueryById2(Guid?id)
        {
            var q = Queries.SingleOrDefault(cc => cc.QueryId == id);

            return(q);
        }
Exemplo n.º 27
0
 public void UpdateSettings(SettingsData settingsData)
 {
     settingsData.WebQuerySettings = Queries.ToArray();
 }
Exemplo n.º 28
0
 private static Dictionary <string, object> CreateQueryNames()
 {
     return(Queries.GetQueryNames().ToDictionaryEx(qn => QueryUtils.GetKey(qn), "queryName"));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Obtient toutes les données du projet spécifié.
        /// </summary>
        /// <param name="projectId">L'identifiant du projet.</param>
        public virtual async Task <RestitutionData> GetFullProjectDetails(int projectId) =>
        await Task.Run(async() =>
        {
            using (var context = ContextFactory.GetNewContext(_securityContext.CurrentUser, _localizationManager))
            {
                IDictionary <ProcessReferentialIdentifier, bool> referentialsUsed = await _sharedScenarioActionsOperations.GetReferentialsUse(context, projectId);
                Referentials referentials = await Queries.LoadAllReferentialsOfProject(context, projectId, referentialsUsed);

                //await context.Videos.Where(v => v.ProjectId == projectId).ToArrayAsync();
                await context.ScenarioNatures.ToArrayAsync();
                await context.ScenarioStates.ToArrayAsync();
                await context.ActionTypes.ToArrayAsync();
                await context.ActionValues.ToArrayAsync();

                Project project = await context.Projects
                                  .Include(nameof(Project.Process))
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.Videos)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}.{nameof(UserRoleProcess.User)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}.{nameof(UserRoleProcess.User)}.{nameof(User.DefaultLanguage)}")
                                  .Include(nameof(Project.Scenarios))
                                  .Include($"{nameof(Project.Scenarios)}.{nameof(Scenario.Actions)}")
                                  .Include(nameof(Project.Objective))
                                  .FirstAsync(s => s.ProjectId == projectId);

                project.ScenariosCriticalPath = PrepareService.GetSummary(project, true);

                // Scénarios
                foreach (Scenario scenario in project.Scenarios.Where(s => s.OriginalScenarioId.HasValue))
                {
                    // Remapper l'original
                    scenario.Original = project.Scenarios.Single(s => s.ScenarioId == scenario.OriginalScenarioId);

                    ScenarioCriticalPath matchingCriticalItem = project.ScenariosCriticalPath.FirstOrDefault(i => i.Id == scenario.ScenarioId);
                    if (matchingCriticalItem != null)
                    {
                        matchingCriticalItem.OriginalLabel = scenario.Original.Label;
                    }
                }

                ProjectReferential[] projectReferentials = await context.ProjectReferentials.Where(pr => pr.ProjectId == projectId).ToArrayAsync();

                User user = await context.Users.FirstAsync(u => u.UserId == project.CreatedByUserId);

                ModificationsUsers modificationsUsers = new ModificationsUsers
                {
                    CreatedByFullName      = (await context.Users.FirstAsync(u => u.UserId == project.ModifiedByUserId)).FullName,
                    LastModifiedByFullName = (await context.Users.FirstAsync(u => u.UserId == project.ModifiedByUserId)).FullName
                };

                Scenario[] scenarios = await context.Scenarios
                                       .Where(s => s.ProjectId == projectId)
                                       .ToArrayAsync();

                await Queries.LoadScenariosDetails(context, scenarios, referentialsUsed);

                ILookup <int, KAction> actionsToLoad = scenarios
                                                       .SelectMany(a => a.Actions)
                                                       .Where(a => a.IsReduced && a.OriginalActionId.HasValue)
                                                       .ToLookup(a => a.OriginalActionId.Value, a => a);

                if (actionsToLoad.Any())
                {
                    foreach (var duration in await _sharedScenarioActionsOperations.GetActionsBuildDurations(context, actionsToLoad.Select(g => g.Key)))
                    {
                        foreach (KAction action in actionsToLoad[duration.ActionId])
                        {
                            action.Reduced.Saving = duration.BuildDuration - action.BuildDuration;
                        }
                    }
                }

                ScenarioActionHierarchyHelper.MapScenariosActionsOriginals(scenarios);

                return(new RestitutionData()
                {
                    Project = project,
                    ProjectCreatedByUser = user,
                    Scenarios = scenarios,
                    ActionCategories = referentials.Categories,
                    ModificationsUsers = modificationsUsers,
                    ReferentialsUse = projectReferentials,
                });
            }
        });
Exemplo n.º 30
0
 /// <summary>
 /// Show the query window
 /// </summary>
 /// <param name="queries"></param>
 public void ShowQueryWindow(Queries queries)
 {
     TraceLog.WriteLine(new StackFrame().GetMethod().Name, "I see there are " + queries.Count() + " queries here.");
     var query = new QueryDialog(queries);
     query.ShowDialog();
 }
Exemplo n.º 31
0
        /// <summary>Handles errors reported via the teamspeak responses.</summary>
        public Boolean performResponseHandling(Queries queryCode)
        {
            // Exit if we're fine.
            if (mTsResponse.Id == "0")
                return true;

            // Handle "Always Fine" or "Always Fatal" issues.
            switch (mTsResponse.Id)
            {
                case "-1": // Socket was open and we tried to re-establish a connection.
                case "-5": // Socket was closed and we tried to send a query.
                case "-6": // The query we tried to send was null.
                    consoleWrite("[Error] ^3Minor Error:");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return true;

                case "-2": // Invalid IP Address.
                case "-3": // Invalid Port.
                case "-4": // Error occurred when trying to establish a connection.
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during establishing a connection to the Teamspeak 3 Server.");
                    consoleWrite("[Error] ^8Make sure your ^b\"Server Ip\"^n and ^b\"Query Port\"^n are correct.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    if (!mTsReconnecting && errReconnectOnError && performReconnect()) return true;
                    setPluginState(false);
                    return false;

                case "-7": // Error occurred during sending the query.
                case "-8": // Error occurred during receiving the response.
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during sending and receiving data to the Teamspeak 3 Server.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    if (!mTsReconnecting && errReconnectOnError && performReconnect()) break;
                    setPluginState(false);
                    return false;

                case "3329": // You are temp banned from the server for flooding.
                case "3331": // You are temp banned from the server for 'x' seconds.
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8You were temporarily banned from the Teamspeak 3 Server for flooding.");
                    consoleWrite("[Error] ^8Make sure your ^bProcon's Ip^n is in your ^bTeamspeak 3 Server's Whitelist^n.");
                    consoleWrite("[Error] ^8{0}: {1} ({2})", mTsResponse.Id, mTsResponse.Message, mTsResponse.ExtraMessage);
                    setPluginState(false);
                    return false;
            }

            // Handle "Program Position Specific" issues.
            switch (queryCode)
            {
                // -- Perform Open Connection ---------------------------------
                case Queries.OpenConnectionEstablish:
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during establishing a connection to the Teamspeak 3 Server.");
                    consoleWrite("[Error] ^8Make sure your ^b\"Server Ip\"^n and ^b\"Query Port\"^n are correct.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    setPluginState(false);
                    return false;
                case Queries.OpenConnectionLogin:
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during logging into the Teamspeak 3 Server.");
                    consoleWrite("[Error] ^8Make sure your ^b\"Query Username\"^n and ^b\"Query Password\"^n are correct.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    setPluginState(false);
                    return false;
                case Queries.OpenConnectionUse:
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during finding the virtual server.");
                    consoleWrite("[Error] ^8Make sure your ^b\"Server Port\"^n is correct.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    setPluginState(false);
                    return false;
                case Queries.OpenConnectionStaging:
                    consoleWrite("[Error] ^8Fatal Error:");
                    consoleWrite("[Error] ^8An error occurred during finding the staging channel.");
                    consoleWrite("[Error] ^8Make sure your ^b\"Staging Channel Name\"^n is correct and that the channel exists in the Teamspeak 3 Server.");
                    consoleWrite("[Error] ^8{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    setPluginState(false);
                    return false;
                case Queries.OpenConnectionNickname:
                    consoleWrite("[Error] ^3Minor Error:");
                    consoleWrite("[Error] ^3An error occurred during changing the server query nickname.");
                    consoleWrite("[Error] ^3Make sure your ^b\"Query Nickname\"^n is not already in use.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return true;

                // -- Update Teamspeak Information ----------------------------
                case Queries.TsInfoClientList:
                    consoleWrite("[Error] ^3Minor Error - Update Teamspeak Information:");
                    consoleWrite("[Error] ^3An error occurred during obtaining the Teamspeak Client List.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.TsInfoChannelList:
                    consoleWrite("[Error] ^3Minor Error - Update Teamspeak Information:");
                    consoleWrite("[Error] ^3An error occurred during obtaining the Teamspeak Channel List.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.TsInfoClientInfo:
                    consoleWrite("[Error] ^3Minor Error - Update Teamspeak Information:");
                    consoleWrite("[Error] ^3An error occurred during obtaining an Advanced Client Information.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return true;

                // -- Check Client for Swapping/Removing ----------------------
                case Queries.CheckSwapStaging:
                    consoleWrite("[Error] ^3Minor Error - Check Client for Swapping/Removing:");
                    consoleWrite("[Error] ^3An error occurred during moving a client to the staging channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CheckSwapTeam:
                    consoleWrite("[Error] ^3Minor Error - Check Client for Swapping/Removing:");
                    consoleWrite("[Error] ^3An error occurred during moving a client to a team channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CheckSwapSquad:
                    consoleWrite("[Error] ^3Minor Error - Check Client for Swapping/Removing:");
                    consoleWrite("[Error] ^3An error occurred during moving a client to a squad channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CheckRemove:
                    consoleWrite("[Error] ^3Minor Error - Check Client for Swapping/Removing:");
                    consoleWrite("[Error] ^3An error occurred during removing a client to the staging channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;

                // -- Find or Create Channels ---------------------------------
                case Queries.FindTeamChannelList:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during obtaining the Teamspeak Channel List while looking for a team channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.FindSquadChannelList:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during obtaining the Teamspeak Channel List while looking for a squad channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CreateTeamChannelQuery:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during creating a team channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CreateTeamChannelInfo:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during requesting advanced information about the new team channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CreateSquadChannelQuery:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during creating a squad channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.CreateSquadChannelInfo:
                    consoleWrite("[Error] ^3Minor Error - Find or Create Channels:");
                    consoleWrite("[Error] ^3An error occurred during requesting advanced information about the new squad channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;

                // -- Remove Channels -----------------------------------------
                case Queries.RemoveChannelsList:
                    consoleWrite("[Error] ^3Minor Error - Remove Channels:");
                    consoleWrite("[Error] ^3An error occurred during obtaining the Teamspeak Channel List.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return false;
                case Queries.RemoveChannelsTeamQuery:
                    consoleWrite("[Error] ^3Minor Error - Remove Channels:");
                    consoleWrite("[Error] ^3An error occurred during removing a team channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return true;
                case Queries.RemoveChannelsSquadQuery:
                    consoleWrite("[Error] ^3Minor Error - Remove Channels:");
                    consoleWrite("[Error] ^3An error occurred during removing a squad channel.");
                    consoleWrite("[Error] ^3{0}: {1}", mTsResponse.Id, mTsResponse.Message);
                    return true;
            }

            // Don't know what went wrong?
            return true;
        }
Exemplo n.º 32
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            firebaseAnalytics = FirebaseAnalytics.GetInstance(this);
            base.OnCreate(savedInstanceState);
            Localise.SetLayoutDirectionByCulture(this);
            SetContentView(Resource.Layout.login);

            SupportActionBar.Title = StringResources.login_ui_title;
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            var submit = FindViewById <AppCompatButton>(Resource.Id.submit);

            submit.Text = StringResources.login_ui_submit_button;

            // Have to manually change hints on input layout.
            var _email = FindViewById <TextInputLayout>(Resource.Id.emailTextInput);

            _email.Hint = StringResources.common_ui_forms_email_label;
            var _password = FindViewById <TextInputLayout>(Resource.Id.passwordTextInput);

            _password.Hint = StringResources.common_ui_forms_password_label;

            FindViewById <TextInputEditText>(Resource.Id.password).EditorAction += (_, e) =>
            {
                e.Handled = false;
                if (e.ActionId == Android.Views.InputMethods.ImeAction.Done)
                {
                    FindViewById <AppCompatButton>(Resource.Id.submit).PerformClick();
                    e.Handled = true;
                }
            };

            submit.Click += async delegate
            {
                var imm = (Android.Views.InputMethods.InputMethodManager)GetSystemService(InputMethodService);
                imm.HideSoftInputFromWindow(FindViewById <TextInputEditText>(Resource.Id.password).WindowToken, 0);

                var email = FindViewById <AppCompatEditText>(Resource.Id.email);
                var passw = FindViewById <AppCompatEditText>(Resource.Id.password);

                if (string.IsNullOrWhiteSpace(email.Text))
                {
                    email.Error = StringResources.common_ui_forms_email_validate_empty;
                    email.RequestFocus();
                }
                else if (string.IsNullOrWhiteSpace(passw.Text))
                {
                    passw.Error = StringResources.common_ui_forms_password_validate_empty;
                    passw.RequestFocus();
                }
                else if (!Android.Util.Patterns.EmailAddress.Matcher(email.Text).Matches())
                {
                    email.Error = StringResources.common_ui_forms_email_validate_invalid;
                    email.RequestFocus();
                }
                else
                {
                    FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility = ViewStates.Visible;
                    FindViewById <AppCompatButton>(Resource.Id.submit).Enabled     = false;

                    LOG_EVENT_WITH_ACTION("LOGIN", "ATTEMPT");
                    var response = await RestClient.Login(email.Text.ToLower(), passw.Text);

                    if (response.Meta.Messages.Count > 0)
                    {
                        LOG_EVENT_WITH_ACTION("LOGIN", "ERROR");
                        RunOnUiThread(() =>
                        {
                            response.Meta.Messages.ForEach(MakeError);
                            FindViewById <AppCompatButton>(Resource.Id.submit).Enabled     = true;
                            FindViewById <ProgressBar>(Resource.Id.progressBar).Visibility = ViewStates.Gone;
                        });
                    }
                    // If there are no errors, then tokens exist as the request was a great success.
                    else if (!string.IsNullOrEmpty(response.Data?.Tokens.Access))
                    {
                        LOG_EVENT_WITH_ACTION("LOGIN", "SUCCESS");
                        // When the application is closed, the ActiveUser is reset. The username and tokens
                        // are used to build a new active user.
                        var prefs = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                        // Used in MainActivity to determine if a user has logged in.
                        prefs.Edit().PutString("username", email.Text).Commit();
                        prefs.Edit().PutString("tokens", JsonConvert.SerializeObject(response.Data.Tokens)).Commit();

                        // Set active user on login/register as the user object is in the response.
                        // This prevents us from storing a user object in local storage.
                        Queries.SetActiveUser(response.Data);
                        FirebaseAnalytics.GetInstance(this).SetUserId(Session.ActiveUser.Id.ToString());

                        // We do not want the user to return to ANY gabber recording pages once captured.
                        var intent = new Intent(this, typeof(MainActivity));
                        intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.ClearTask | ActivityFlags.NewTask);
                        StartActivity(intent);
                        // Prevent returning to login once authenticated.
                        Finish();
                    }
                }
            };

            _email.RequestFocus();
            Window.SetSoftInputMode(SoftInput.StateAlwaysVisible);
        }
Exemplo n.º 33
0
        public static List <QueryEntity> GetTypeQueries(TypeEntity typeEntity)
        {
            Type type = TypeLogic.GetType(typeEntity.CleanName);

            return(Queries.GetTypeQueries(type).Keys.Select(GetQueryEntity).ToList());
        }
Exemplo n.º 34
0
        protected async override Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            Categories = await Queries.QueryAsync(new ListAllCategory());
        }
Exemplo n.º 35
0
        protected void bulkApply_Click(object sender, EventArgs e)
        {
            if (UsersRW.Contains(user))
            {
                Dictionary <string, string> Params = new Dictionary <string, string>();
                Params.Add("WebOwnerCondition", "IS NULL");
                Params.Add("WebStoreName", storeDDL.SelectedValue);
                Params.Add("WebArchiveSet", "0");
                Params.Add("WebArchiveWhere", "0");
                Params.Add("WebQtyLogicalOP", opDDL.SelectedValue);
                Params.Add("WebQtyWhere", opTXT.Text);
                Params.Add("WebStartDate", webStartDate.SelectedValue);
                Params.Add("WebStoreNumber", StoreNumberTXT.Text.Trim() == "" ? "NULL" : StoreNumberTXT.Text.Trim());
                Params.Add("WebSalesDate", saleDate.Text.Trim() == "" ? "NULL" : saleDate.Text.Trim());

                Params.Add("Action", "BULKUPDATE");

                switch (bulkDDL.SelectedValue)
                {
                case "update":
                    if (colDDL.SelectedValue == "Qty")
                    {
                        Params.Add("WebQtySet", newVal.Text.Replace("'", ""));
                    }
                    else
                    {
                        Params["Web" + colDDL.SelectedValue] = newVal.Text.Replace("'", "");
                    }
                    break;

                case "pending":
                    Params.Add("WebProgramSet", "");
                    break;

                case "misc":
                    Params.Add("WebProgramSet", "Misc");
                    break;

                case "return":
                    Params.Add("WebProgramSet", "Return");
                    break;

                case "archive":
                    Params["WebArchiveSet"] = "1";
                    break;
                }

                switch (viewDDL.SelectedValue)
                {
                case "Pending":
                    Params.Add("WebProgramWhere", " NOT IN ('Return', 'Misc')");
                    break;

                case "Return":
                    Params.Add("WebProgramWhere", " = 'Return'");
                    break;

                case "Misc":
                    Params.Add("WebProgramWhere", " = 'Misc'");
                    break;

                case "Archive":
                    Params["WebArchiveWhere"] = "1";
                    break;
                }

                if (bulkDDL.SelectedValue != "")
                {
                    Queries.ExecuteFromStoreProcedure("spx_PAYOUTsales", Params);
                }

                salesGrid.DataBind();
            }
        }
        /// <summary>
        /// Returns queries for a particular worksheet
        /// </summary>
        /// <param name="sheet"></param>
        /// <returns></returns>
        public Queries QueriesForSheet(string sheet)
        {
            if(!_sheets.ContainsKey(sheet))
            {
                var queries = new Queries(sheet, Projects, _defaultQuery);
                queries.Fetch += Run;
                queries.Save += Save;
                _sheets[sheet] = queries;
            }

            return _sheets[sheet];
        }