コード例 #1
0
        public async Task <string> Spam([Author] Member author, MyCouchStore db, ISocketMessageChannel channel, SocketUserMessage message, [Rest] string youtubeUrl)
        {
            if (message.Author is SocketGuildUser discordAuthor && discordAuthor.VoiceChannel != null)
            {
                Spammable spammable;
                try {
                    spammable = await Spammable.Create(youtubeUrl);
                } catch (Exception exception) {
                    Console.WriteLine(exception);
                    return("Could not download youtube video. Maybe try a different video?");
                }

                var bbpCost    = spammable.Length * 100 / 60;
                var walletCost = new Wallet(bbpCost + " BBP");
                author.Wallet.Subtract(walletCost);

                try {
                    await channel.SendMessageAsync($"{author.Name} has triggered a mic spam for {walletCost}.");

                    var client = await discordAuthor.VoiceChannel.ConnectAsync();

                    if (!await spammable.Spam(client))
                    {
                        return("Could not play youtube video in voice channel. Maybe try a different video.");
                    }
                    else
                    {
                        await db.StoreAsync(author);

                        return(null);
                    }
                } finally {
                    await discordAuthor.VoiceChannel.DisconnectAsync();
                }
            }
コード例 #2
0
        public async Task <string> Give([Author] Member author, Member reciever, [Rest] string amountText, MyCouchStore db)
        {
            if (author.Id == reciever.Id)
            {
                throw new CommandFailedException("You can't give to yourself.");
            }

            var amount = new Wallet(amountText);

            author.Wallet.Subtract(amount);
            reciever.Wallet.Add(amount);
            await db.StoreAsync(author);

            await db.StoreAsync(reciever);

            return($"{author} has given {reciever} {amount.ToString()}.");
        }
コード例 #3
0
 /// <summary>
 /// Returns Id of created document
 /// </summary>
 private string CreateDocument(string document)
 {
     using (var c = new MyCouchStore(_uri))
     {
         var header = c.StoreAsync(document).Result;
         return header.Id;
     }
 }
コード例 #4
0
        /// <summary>
        /// Stores a single comment and returns the complete object as it would be found in the dataabase.
        /// </summary>
        /// <param name="comment"></param>
        /// <returns></returns>
        public async Task <Comment> StoreComment(Comment comment)
        {
            if (comment == null)
            {
                return(null);
            }
            comment = await _commentStore.StoreAsync(comment);

            _commentCache.Put(comment.Id, comment);
            return(comment);
        }
コード例 #5
0
        public void Store(BookOrder bookOrder)
        {
            using (var store = new MyCouchStore(_databaseUri, _databaseName))
            {
                // HACK: Concurrency support, lets just get the latest rev
                // Don't do this in production environments !! Implement concurrency properly all the way
                // to the client !!
                string rev = GetRev(store, bookOrder.Id);

                BookOrderDto bookOrderDto = BookOrderMapper.MapTo(bookOrder, rev);

                if (rev == null)
                {
                    store.StoreAsync(bookOrderDto).Wait();
                }
                else
                {
                    bookOrderDto._rev = rev;
                    store.StoreAsync(bookOrderDto).Wait();
                }
            }
        }
コード例 #6
0
ファイル: Tools.cs プロジェクト: HeavyHenke/KarinsFilmer
        public void ImportTestData()
        {
            // Remove the old database
            string connectionString = ConfigurationManager.ConnectionStrings["CouchDb"].ConnectionString;
            var uri = new Uri(connectionString);
            var dbName = uri.LocalPath.Substring(1);

            using (var s = new MyCouchServerClient(uri.Scheme + "://" + uri.Authority))
            {
                s.Databases.DeleteAsync(dbName).Wait();
            }

            // Create new database
            CouchConfig.SetupCouchDb();

            // Fill it with test data
            using (var c = new MyCouchStore(connectionString))
            {
                foreach (var testData in GetTestData())
                {
                    c.StoreAsync(testData).Wait();
                }
            }
        }
コード例 #7
0
 public void Add(LeadType type)
 {
     _store.StoreAsync(type).Wait();
 }
コード例 #8
0
        static void WorkTimerCallback(object state)
        {
            MyCouchClient   couch    = (MyCouchClient)state;
            List <ADAITask> taskList = new List <ADAITask>();

            Console.Write("Getting settings...");
            Task <GetEntityResponse <Settings> > settingsTask = couch.Entities.GetAsync <Settings>("settings");

            settingsTask.Wait();

            Settings settings;

            if (settingsTask.Result.IsSuccess)
            {
                settings = settingsTask.Result.Content;
                Console.WriteLine("done");
            }
            else
            {
                settings = new Settings();
                Console.WriteLine("error - using defaults");
            }
            Console.WriteLine("Current settings: autoWatch = " + settings.autoWatch);

            Console.Write("Polling tasklist...");

            QueryViewRequest req = new QueryViewRequest("tasks", "tasks").Configure(q => q.IncludeDocs(true));
            Task <ViewQueryResponse <string, ADAITask> > queryTask = couch.Views.QueryAsync <string, ADAITask>(req);

            queryTask.Wait();

            Console.WriteLine("done - " + queryTask.Result.TotalRows + " tasks fetched");

            if (queryTask.Result.TotalRows == 0 && !settings.autoWatch)
            {
                Console.WriteLine("Finished! Waiting for next polling interval...");
                return;
            }

            Console.Write("Connecting to " + DB + "...");
            OracleConnection conn = null;

            try
            {
                conn = new OracleConnection(connString);
                conn.Open();

                // Open session
                OracleCommand cmdOpenSession = new OracleCommand("e.env_session_intf#.open_session", conn);
                cmdOpenSession.CommandType = System.Data.CommandType.StoredProcedure;
                cmdOpenSession.ExecuteNonQuery();

                Console.WriteLine("done");

                OracleCommand cmd = new OracleCommand();
                cmd.Connection  = conn;
                cmd.CommandType = System.Data.CommandType.Text;

                // Copy task IDs to a list that we then use in an OracleParameter for the IN clause
                foreach (ViewQueryResponse <string, ADAITask> .Row row in queryTask.Result.Rows)
                {
                    //taskIdList.Add(row.IncludedDoc.TaskID);
                    OracleParameter par = new OracleParameter(":t" + cmd.Parameters.Count, OracleDbType.Int32);
                    par.Value = row.IncludedDoc.TaskID;

                    cmd.Parameters.Add(par);
                }

                StringBuilder inClause = new StringBuilder();
                foreach (OracleParameter par in cmd.Parameters)
                {
                    inClause.AppendFormat("{0},", par.ParameterName);
                }

                if (inClause.Length > 0)
                {
                    inClause.Remove(inClause.Length - 1, 1); // Remove trailing comma
                }
                else
                {
                    inClause.Append("null");
                }

                StringBuilder q = new StringBuilder();
                q.AppendLine("select env_task.id, env_task.name, env_wfc_status.name, env_release.user_id");
                q.AppendLine("  from e.env_task, e.env_wfc_status, e.env_release, env_user");
                q.AppendLine(" where env_task.env_wfc_status_id = env_wfc_status.id");
                q.AppendLine("   and env_task.env_release_id = env_release.id");
                q.AppendLine("   and env_task.resp_env_user_id = env_user.id");
                q.AppendFormat("   and (env_task.id in ({0})", inClause);
                q.AppendLine();

                // Also include new tasks not already watched?
                if (settings.autoWatch)
                {
                    OracleParameter parUser = new OracleParameter();
                    parUser.OracleDbType  = OracleDbType.Varchar2;
                    parUser.ParameterName = ":oracle_user";
                    parUser.Value         = username.ToUpper();
                    cmd.Parameters.Add(parUser);

                    q.AppendFormat("    or env_user.oracle_user = {0}", parUser.ParameterName);
                    q.AppendLine();
                    q.AppendLine("   and env_task.env_wfc_status_id in (2018 /* Integration Test Running */, 2015 /* Ready to Integrate */)");
                }
                q.AppendLine(")");

                cmd.CommandText = q.ToString();
                Console.Write("Running query...");

                Debug.WriteLine(cmd.CommandText);
                OracleDataReader reader = cmd.ExecuteReader();

                Console.WriteLine("done");

                foreach (ViewQueryResponse <string, ADAITask> .Row row in queryTask.Result.Rows)
                {
                    taskList.Add(row.IncludedDoc);
                }

                while (reader.Read())
                {
                    ADAITask t = null;

                    if (taskList.Exists(m => m.TaskID == reader.GetInt32(0)))
                    {
                        t = queryTask.Result.Rows.Where(e => e.IncludedDoc.TaskID == reader.GetInt32(0)).Single().IncludedDoc;
                    }
                    else
                    {
                        t = new ADAITask(reader.GetInt32(0));
                        taskList.Add(t);
                    }
                    t.TaskName    = reader.GetString(1);
                    t.TaskStatus  = reader.GetString(2);
                    t.TaskRelease = reader.GetString(3);
                    t.LastUpdated = DateTime.Now;

                    Debug.WriteLine("Task ID: " + t.TaskID + ", Task Name: " + t.TaskName + ", Task Status: " + t.TaskStatus +
                                    ", Task Release: " + t.TaskRelease);
                }

                reader.Close();
            }
            catch (OracleException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            MyCouchStore store = new MyCouchStore(couch);

            foreach (ADAITask t in taskList)
            {
                Console.Write("Updating doc for task " + t.TaskID + "...");
                Task <ADAITask> storeTask = store.StoreAsync <ADAITask>(t);
                storeTask.Wait();
                Console.WriteLine("done");
            }

            Console.WriteLine("Finished! Waiting for next polling interval...");

            //GetChangesRequest getChangesRequest = new GetChangesRequest
            //{
            //    Feed = ChangesFeed.Normal
            //};

            //Task<ChangesResponse> changesTask = store.Client.Changes.GetAsync(getChangesRequest);
            //changesTask.Wait();
            //changeObserver.SetIgnoreUntilSeqNr(changesTask.Result.LastSeq);
        }
コード例 #9
0
        public bool LoadFrom(string couchdb_host, string db_name, string config_name = null, bool track_changes = false)
        {
            using (var couch_store = new MyCouchStore(couchdb_host, db_name))
            {
                config_name = config_name ?? ((this.Config != null) ? this.Config.Id : typeof(T).Name);

                var task = couch_store.GetByIdAsync <T>(config_name);
                task.Wait();
                if (task.Result != null)
                {
                    if (task.Result.PreLoad())
                    {
                        task.Result.OnLoad();
                        this.Config = task.Result;
                        Logger.InfoFormat("Configuration is loaded from {0}/{1}/{2} successfully:\n\r{3}",
                                          couchdb_host, db_name, config_name, couch_store.Client.Serializer.Serialize(task.Result));
                    }
                    else
                    {
                        Logger.InfoFormat("Failed to load configuration from {0}/{1}/{2}", couchdb_host, db_name, config_name);
                        return(false);
                    }
                }
                else
                {
                    if (this.Config != null)
                    {
                        try
                        {
                            var write_task = couch_store.StoreAsync <T>(this.Config);
                            write_task.Wait();
                            Logger.InfoFormat("Configuration does not exist on {0}/{1}/{2}. So wrote back {3}:\n\r{4}",
                                              couchdb_host, db_name, config_name, write_task.Result, couch_store.Client.Serializer.Serialize(this.Config));
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn("Failed to store back defaut configuration", ex);
                            return(false);
                        }
                    }
                }
            }

            if (false == track_changes)
            {
                return(true);
            }

            throw new NotImplementedException("configuration tracking is not available now");

            /*
             * var getChangesRequest = new GetChangesRequest
             * {
             *      Feed = ChangesFeed.Continuous,
             *      Heartbeat = 1000,
             * };
             *
             * _couch_client = new MyCouchClient(couchdb_host, db_name);
             * _cancellation = new CancellationTokenSource();
             * _couch_client.Changes.GetAsync(getChangesRequest, data => this.FeedData(data), _cancellation.Token);
             *
             * return true;
             */
        }
コード例 #10
0
 public void Add(Lead lead)
 {
     _store.StoreAsync(lead).Wait();
 }
コード例 #11
0
 public void Add(Product product)
 {
     _store.StoreAsync(product).Wait();
 }
コード例 #12
0
        static void WorkTimerCallback(object state)
        {
            MyCouchClient couch = (MyCouchClient) state;
            List<ADAITask> taskList = new List<ADAITask>();

            Console.Write("Getting settings...");
            Task<GetEntityResponse<Settings>> settingsTask = couch.Entities.GetAsync<Settings>("settings");
            settingsTask.Wait();

            Settings settings;

            if (settingsTask.Result.IsSuccess)
            {
                settings = settingsTask.Result.Content;
                Console.WriteLine("done");
            }
            else
            {
                settings = new Settings();
                Console.WriteLine("error - using defaults");
            }
            Console.WriteLine("Current settings: autoWatch = " + settings.autoWatch);

            Console.Write("Polling tasklist...");

            QueryViewRequest req = new QueryViewRequest("tasks", "tasks").Configure(q => q.IncludeDocs(true));
            Task<ViewQueryResponse<string, ADAITask>> queryTask = couch.Views.QueryAsync<string, ADAITask>(req);
            queryTask.Wait();

            Console.WriteLine("done - " + queryTask.Result.TotalRows + " tasks fetched");

            if (queryTask.Result.TotalRows == 0 && !settings.autoWatch)
            {
                Console.WriteLine("Finished! Waiting for next polling interval...");
                return;
            }

            Console.Write("Connecting to " + DB + "...");
            OracleConnection conn = null;

            try
            {
                conn = new OracleConnection(connString);
                conn.Open();

                // Open session
                OracleCommand cmdOpenSession = new OracleCommand("e.env_session_intf#.open_session", conn);
                cmdOpenSession.CommandType = System.Data.CommandType.StoredProcedure;
                cmdOpenSession.ExecuteNonQuery();

                Console.WriteLine("done");

                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.Text;

                // Copy task IDs to a list that we then use in an OracleParameter for the IN clause
                foreach (ViewQueryResponse<string, ADAITask>.Row row in queryTask.Result.Rows)
                {
                    //taskIdList.Add(row.IncludedDoc.TaskID);
                    OracleParameter par = new OracleParameter(":t" + cmd.Parameters.Count, OracleDbType.Int32);
                    par.Value = row.IncludedDoc.TaskID;

                    cmd.Parameters.Add(par);
                }

                StringBuilder inClause = new StringBuilder();
                foreach (OracleParameter par in cmd.Parameters)
                {
                    inClause.AppendFormat("{0},", par.ParameterName);
                }

                if (inClause.Length > 0)
                {
                    inClause.Remove(inClause.Length - 1, 1); // Remove trailing comma
                }
                else
                {
                    inClause.Append("null");
                }

                StringBuilder q = new StringBuilder();
                q.AppendLine("select env_task.id, env_task.name, env_wfc_status.name, env_release.user_id");
                q.AppendLine("  from e.env_task, e.env_wfc_status, e.env_release, env_user");
                q.AppendLine(" where env_task.env_wfc_status_id = env_wfc_status.id");
                q.AppendLine("   and env_task.env_release_id = env_release.id");
                q.AppendLine("   and env_task.resp_env_user_id = env_user.id");
                q.AppendFormat("   and (env_task.id in ({0})", inClause);
                q.AppendLine();

                // Also include new tasks not already watched?
                if (settings.autoWatch)
                {
                    OracleParameter parUser = new OracleParameter();
                    parUser.OracleDbType = OracleDbType.Varchar2;
                    parUser.ParameterName = ":oracle_user";
                    parUser.Value = username.ToUpper();
                    cmd.Parameters.Add(parUser);

                    q.AppendFormat("    or env_user.oracle_user = {0}", parUser.ParameterName);
                    q.AppendLine();
                    q.AppendLine("   and env_task.env_wfc_status_id in (2018 /* Integration Test Running */, 2015 /* Ready to Integrate */)");
                }
                q.AppendLine(")");

                cmd.CommandText = q.ToString();
                Console.Write("Running query...");

                Debug.WriteLine(cmd.CommandText);
                OracleDataReader reader = cmd.ExecuteReader();

                Console.WriteLine("done");

                foreach (ViewQueryResponse<string, ADAITask>.Row row in queryTask.Result.Rows)
                {
                    taskList.Add(row.IncludedDoc);
                }

                while (reader.Read())
                {
                    ADAITask t = null;

                    if (taskList.Exists(m => m.TaskID == reader.GetInt32(0)))
                    {
                        t = queryTask.Result.Rows.Where(e => e.IncludedDoc.TaskID == reader.GetInt32(0)).Single().IncludedDoc;
                    }
                    else
                    {
                        t = new ADAITask(reader.GetInt32(0));
                        taskList.Add(t);
                    }
                    t.TaskName = reader.GetString(1);
                    t.TaskStatus = reader.GetString(2);
                    t.TaskRelease = reader.GetString(3);
                    t.LastUpdated = DateTime.Now;

                    Debug.WriteLine("Task ID: " + t.TaskID + ", Task Name: " + t.TaskName + ", Task Status: " + t.TaskStatus +
                        ", Task Release: " + t.TaskRelease);
                }

                reader.Close();
            }
            catch (OracleException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }

            MyCouchStore store = new MyCouchStore(couch);

            foreach (ADAITask t in taskList)
            {
                Console.Write("Updating doc for task " + t.TaskID + "...");
                Task<ADAITask> storeTask = store.StoreAsync<ADAITask>(t);
                storeTask.Wait();
                Console.WriteLine("done");
            }

            Console.WriteLine("Finished! Waiting for next polling interval...");

            //GetChangesRequest getChangesRequest = new GetChangesRequest
            //{
            //    Feed = ChangesFeed.Normal
            //};

            //Task<ChangesResponse> changesTask = store.Client.Changes.GetAsync(getChangesRequest);
            //changesTask.Wait();
            //changeObserver.SetIgnoreUntilSeqNr(changesTask.Result.LastSeq);
        }