Beispiel #1
0
        public void TryAwaitTaskRun(string code, bool expected, string expectedCode)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System.Threading.Tasks;

    internal class Foo
    {
        internal async Task Bar()
        {
            var value = // Meh();
        }

        internal static string CreateString() => new string(' ', 1);
    }
}";

            testCode = testCode.AssertReplace("// Meh()", code);
            var syntaxTree    = CSharpSyntaxTree.ParseText(testCode);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.FindEqualsValueClause(code).Value as InvocationExpressionSyntax;

            Assert.AreEqual(expected, AsyncAwait.TryAwaitTaskRun(value, semanticModel, CancellationToken.None, out var result));
            Assert.AreEqual(expectedCode, result?.ToFullString());
        }
Beispiel #2
0
        static async Task Main(string[] args)
        {
            AsyncAwait asyncAwait = new AsyncAwait();
            await asyncAwait.Test();

            Console.ReadLine();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            //ICode code = new BinarySearch();
            //ICode code = new PrintPattern.Pyramid();
            ICode code = new AsyncAwait();

            //ICode code = new BasicDelegate();
            code.Run();
        }
Beispiel #4
0
 public static void Main()
 {
     Prakt1.aufgabe3();
     // dinersProblemNaive();
     Prakt2.parallelPi_C();
     //Prakt2.matrixMultParallel();
     Prakt4.ParallelPi_Tasks();
     Prakt4.Pi_ParallelFor();
     StreamData.Run();
     //Prakt4.Pi_ParallelFor();
     ForEachWithThreadLocal.Run();
     RandomBreak.Run();
     Summary.Run();
     AsyncAwait.Run();
     Prakt5.combineTasks();
 }
Beispiel #5
0
        public static void TryAwaitTaskFromResult(string expression, bool expected, string expectedCode)
        {
            var code          = @"
namespace N
{
    using System.Threading.Tasks;

    internal class C
    {
        internal async Task M()
        {
            var value = // Meh();
        }
    }
}".AssertReplace("// Meh()", expression);
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var compilation   = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes());
            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            var value         = syntaxTree.FindEqualsValueClause(expression).Value as InvocationExpressionSyntax;

            Assert.AreEqual(expected, AsyncAwait.TryAwaitTaskFromResult(value, semanticModel, CancellationToken.None, out var result));
            Assert.AreEqual(expectedCode, result?.ToFullString());
        }
Beispiel #6
0
        private void btnAsyncAndAwait_Click(object sender, EventArgs e)
        {
            var aa = new AsyncAwait();

            aa.GoFunc();
        }
 public void Test1()
 {
     AsyncAwait.Method1Async();
     AsyncAwait.Method2();
 }
Beispiel #8
0
 static void Main(string[] args)
 {
     AsyncAwait.Driver();
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            Console.WriteLine($"Main Thread starting with Id {Thread.CurrentThread.ManagedThreadId}");
            // ArrayTest arrayTest = new ArrayTest();
            // arrayTest.printArray();

            // TypesDemo typesDemo = new TypesDemo();

            // typesDemo.Typetest();

            // OldProps old = new OldProps();
            // old.Name = "Anand";
            // Console.WriteLine(old.Name);

            // NewProps newProps = new NewProps();
            // newProps.Name = "Sardar";
            // Console.WriteLine(newProps.Name);

            // ArrayList names = new ArrayList();
            // names.Add("manish");
            // ExpBodiedMember expBodied = new ExpBodiedMember();
            // expBodied.Names = names;

            // Console.WriteLine(expBodied.Count);
            //  var name  = "Anand";
            // var desg = "microsoft";

            // Console.WriteLine("My name is " + name + " and i work for " + desg);

            // Console.WriteLine($"my name is {name}");

            // AutoImplementedProps.ListProducts();
            // Product product = new Product {Name = "comp", Price = 100}; // This call calls the default constructor for Product class and then calls setters for props
            // Product product = new Product(name: "comp", Price: 100);
            // Console.Write(product.Name);

            // ProductSorting productSorting = new ProductSorting();
            // productSorting.sort();
            // productSorting.sortWithDelegate();
            // productSorting.SortByLambda();
            // productSorting.PrintWithoutSort();
            // productSorting.filter();
            // LinqStart linqStart = new LinqStart();
            // linqStart.filter();
            // linqStart.filterWithJoin();

            // Delegate

            DelDemo delDemo = new DelDemo();
            // Printer pr = new Printer(delDemo.ConsolePrinter);
            // Printer pr1 = delegate(string x) {
            //     Console.WriteLine(x);
            // };

            //  delDemo.print(pr);
            // Implicit conversion from method group to delegate
            // delDemo.print(delDemo.ConsolePrinter);
            // passig delegate as lambda
            // delDemo.print((s) => Console.WriteLine("Delegate through lambda"));
            // passing Delegate as a anonymous method
            // delDemo.print(delegate(string x) {
            //     Console.WriteLine(x);
            // });

            // Program.DemostrateType<int>();

            // int ret;
            // int.TryParse("1", out ret);
            // Console.WriteLine(ret);

            List <int> List = new List <int>();

            // ThreadDemo threadDemo = new ThreadDemo();
            // threadDemo.LegacyWay();
            // threadDemo.AsyncWay();

            // BeginEnd beginEnd = new BeginEnd();
            // beginEnd.doWorkDelegateAsyncTest();

            // AsyncIO asyncIO = new AsyncIO("http://google.com");
            // asyncIO.AsyncDownload();

            // ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo();
            // ManualResetEvent manualSignal = new ManualResetEvent(false);
            // threadPoolDemo.ManualSignal = manualSignal;
            // threadPoolDemo.DoWorkInPool();
            // manualSignal.WaitOne();

            // TaskDemo taskDemo = new TaskDemo();
            // taskDemo.DoWorkInSimpleTask();

            // AsyncIOWithTask asyncIOWithTask = new AsyncIOWithTask {Url = "http://google.com"};
            // asyncIOWithTask.Download();
            // asyncIOWithTask.DoInParallel();

            // AsyncAwait asyncAwaitLongOne = new AsyncAwait {Url = "https://go.microsoft.com/fwlink/p/?linkid=845299"};
            AsyncAwait asyncAwaitShortOne = new AsyncAwait {
                Url = "https://google.com"
            };
            Task <int> asyncResult = asyncAwaitShortOne.download();

            asyncResult.Wait();

            Console.WriteLine($"Main Thread End with Id {Thread.CurrentThread.ManagedThreadId}");
        }
Beispiel #10
0
        public static void Main(string[] args)
        {
            int option    = 1;
            int i_option  = 1;
            int ii_option = 1;

            // YO AMO A MI ESPOSA :) LE VOY A COMPRAR MUCHOS REGALOS :)

            while (option != 0)
            {
                ConsoleUtility.WriteLine("Choose an option based in the next menu");
                ConsoleUtility.WriteLine("1.-Algorithm");
                ConsoleUtility.WriteLine("2.-DataStructures");
                ConsoleUtility.WriteLine("3.-Design Patterns");
                ConsoleUtility.WriteLine("4.-Language DotNet");
                option = Convert.ToInt32(Console.ReadLine());
                switch (option)
                {
                case 1:
                    ConsoleUtility.WriteLine("Algorithm");
                    ConsoleUtility.WriteLine("1.-Linear Table");
                    ConsoleUtility.WriteLine("2.-Linear Table Append");
                    ConsoleUtility.WriteLine("3.-Linear Table Delete");
                    ConsoleUtility.WriteLine("4.-Linear Table Insert");
                    ConsoleUtility.WriteLine("5.-Linear Table Search");
                    ConsoleUtility.WriteLine("6.-Factorial");
                    ConsoleUtility.WriteLine("7.-Bubble Sort");
                    ConsoleUtility.WriteLine("8.-Heap Sort");
                    ConsoleUtility.WriteLine("9.-Insert Sorting");
                    ConsoleUtility.WriteLine("10.-Merge Sort");
                    ConsoleUtility.WriteLine("11.-Quick Sort");
                    ConsoleUtility.WriteLine("12.-Select Sort");
                    ConsoleUtility.WriteLine("13.-Binary Search");
                    ConsoleUtility.WriteLine("14.-Fibonnacci");
                    ConsoleUtility.WriteLine("15.-Fibonacci with Memoization");
                    i_option = Convert.ToInt32(Console.ReadLine());
                    switch (i_option)
                    {
                    case 1:
                        ConsoleUtility.WriteLine("Running example of Linear Table");
                        LinearTable linearTable = new LinearTable();
                        linearTable.Run();
                        break;

                    case 2:
                        ConsoleUtility.WriteLine("Running example of Linear Table Append");
                        LinearTableAppend linearTableAppend = new LinearTableAppend();
                        linearTableAppend.Run();
                        break;

                    case 3:
                        ConsoleUtility.WriteLine("Running example of Linear Table Delete");
                        LinearTableDelete linearTableDelete = new LinearTableDelete();
                        linearTableDelete.Run();
                        break;

                    case 4:
                        ConsoleUtility.WriteLine("Running example of Linear Table Insert");
                        LinearTableInsert linearTableInsert = new LinearTableInsert();
                        linearTableInsert.Run();
                        break;

                    case 5:
                        ConsoleUtility.WriteLine("Running example of Linear Table Search");
                        LinearTableSearch linearTableSearch = new LinearTableSearch();
                        linearTableSearch.Run();
                        break;

                    case 6:
                        ConsoleUtility.WriteLine("Running example of Factorial");
                        Factorial factorial = new Factorial();
                        factorial.Run();
                        break;

                    case 7:
                        ConsoleUtility.WriteLine("Running example of Bubble Sort");
                        BubbleSort bubbleSort = new BubbleSort();
                        bubbleSort.Run();
                        break;

                    case 8:
                        ConsoleUtility.WriteLine("Running example of HeapSort");
                        HeapSort heapSort = new HeapSort();
                        heapSort.Run();
                        break;

                    case 9:
                        ConsoleUtility.WriteLine("Running example of InsertSorting");
                        InsertSorting insertSorting = new InsertSorting();
                        insertSorting.Run();
                        break;

                    case 10:
                        ConsoleUtility.WriteLine("Running example of Merge Sort");
                        MergeSort mergeSort = new MergeSort();
                        mergeSort.Run();
                        break;

                    case 11:
                        ConsoleUtility.WriteLine("Running example pf Quick Sort");
                        QuickSort quickSort = new QuickSort();
                        quickSort.Run();
                        break;

                    case 12:
                        ConsoleUtility.WriteLine("Running example of Select Sort");
                        SelectSort selectSort = new SelectSort();
                        selectSort.Run();
                        break;

                    case 13:
                        ConsoleUtility.WriteLine("Running example of Binary Search");
                        BinarySearch binarySearch = new BinarySearch();
                        binarySearch.Run();
                        break;

                    case 14:
                        ConsoleUtility.WriteLine("Running example of Fibonnacci");
                        Fibonnacci fibonnacci = new Fibonnacci();
                        fibonnacci.Run();
                        break;

                    case 15:
                        ConsoleUtility.WriteLine("Running example of Fibonnaci with Memoization");
                        FibonacciMemoization fibonacciMemoization = new FibonacciMemoization();
                        fibonacciMemoization.Run();
                        break;

                    default:
                        break;
                    }
                    break;

                case 2:
                    ConsoleUtility.WriteLine("Data Structures");
                    ConsoleUtility.WriteLine("1.-Binary Search Tree");
                    ConsoleUtility.WriteLine("2.-Binary Tree");
                    ConsoleUtility.WriteLine("3.-Doubly Linked List");
                    ConsoleUtility.WriteLine("4.-Double Linked List");
                    ConsoleUtility.WriteLine("5.-Hash Table");
                    ConsoleUtility.WriteLine("6.-Linked List");
                    ConsoleUtility.WriteLine("7.-One Way Circular List");
                    ConsoleUtility.WriteLine("8.-Queue");
                    ConsoleUtility.WriteLine("9.-Stack");
                    ConsoleUtility.WriteLine("10.-Two Way Circular List");
                    ConsoleUtility.WriteLine("11.-Unidirectional Linked List");
                    i_option = Convert.ToInt32(Console.ReadLine());
                    ConsoleUtility.WriteLine($"you choose option {i_option}");
                    switch (i_option)
                    {
                    case 1:
                        ConsoleUtility.WriteLine("Running example of Binary Search Tree");
                        BinarySearchTree binarySearchTree = new BinarySearchTree();
                        binarySearchTree.Run();
                        break;

                    case 2:
                        ConsoleUtility.WriteLine("Running example of Binary Tree");
                        BinaryTree binaryTree = new BinaryTree();
                        binaryTree.Run();
                        break;

                    case 3:
                        ConsoleUtility.WriteLine("Running example of DoublyLinkedList");
                        DoublyLinkedList doublyLinkedList = new DoublyLinkedList();
                        doublyLinkedList.Run();
                        break;

                    case 4:
                        ConsoleUtility.WriteLine("Running example of DoubleLinkedList");
                        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
                        doubleLinkedList.Run();
                        break;

                    case 5:
                        ConsoleUtility.WriteLine("Running example of HashTable");
                        HashTable hashTable = new HashTable();
                        hashTable.Run();
                        break;

                    case 6:
                        ConsoleUtility.WriteLine("Running example of Linked List");
                        LinkedList <int> linkedList = new LinkedList <int>();
                        linkedList.Run();
                        break;

                    case 7:
                        ConsoleUtility.WriteLine("Running example of One Way Circular List");
                        OneWayCircularList circularList = new OneWayCircularList();
                        circularList.Run();
                        break;

                    case 8:
                        ConsoleUtility.WriteLine("Running example of Queue");
                        Queue queue = new Queue();
                        queue.Run();
                        break;

                    case 9:
                        ConsoleUtility.WriteLine("Running example of Stack");
                        Stack stack = new Stack();
                        stack.Run();
                        break;

                    case 10:
                        ConsoleUtility.WriteLine("Running example of Two Way Circular List");
                        TwoWayCircularList twoWay = new TwoWayCircularList();
                        twoWay.Run();
                        break;

                    case 11:
                        ConsoleUtility.WriteLine("Running example fo Unidirectional Linked List");
                        UnidirectionalLinkedList unidirectionalLinkedList = new UnidirectionalLinkedList();
                        unidirectionalLinkedList.Run();
                        break;

                    default:
                        break;
                    }
                    break;

                case 3:
                    ConsoleUtility.WriteLine("Design Patterns");
                    ConsoleUtility.WriteLine("1.-Creational");
                    ConsoleUtility.WriteLine("2.-Structural");
                    ConsoleUtility.WriteLine("3.-Behavioral");
                    ConsoleUtility.WriteLine("4.-SOLID Principles");

                    i_option = Convert.ToInt32(Console.ReadLine());
                    ConsoleUtility.WriteLine($"you choose option {i_option}");
                    switch (i_option)
                    {
                    case 1:
                        ConsoleUtility.WriteLine("Example of creational design patterns");
                        ConsoleUtility.WriteLine("1.-Singleton");
                        ConsoleUtility.WriteLine("2.-Factory");
                        ConsoleUtility.WriteLine("3.-Builder");
                        ConsoleUtility.WriteLine("4.-Prototype");
                        ConsoleUtility.WriteLine("5.-Fluent Interface");
                        ConsoleUtility.WriteLine("6.-Factory Method");
                        ConsoleUtility.WriteLine("7.-Abstract Factory");
                        ConsoleUtility.WriteLine("Select one option");
                        ii_option = Convert.ToInt32(Console.ReadLine());
                        switch (ii_option)
                        {
                        case 1:
                            ConsoleUtility.WriteLine("Running example of singleton design pattern");
                            SingletonTest singletonTest = new SingletonTest();
                            singletonTest.Run();
                            break;

                        case 2:
                            ConsoleUtility.WriteLine("Runnig example of Factory design pattern");
                            FactoryTest factoryTest = new FactoryTest();
                            factoryTest.Run();
                            break;

                        case 3:
                            ConsoleUtility.WriteLine("Running example fo Builder Desiogn Pattern");
                            BuilderTest builderTest = new BuilderTest();
                            builderTest.Run();
                            break;

                        case 4:
                            ConsoleUtility.WriteLine("Running example of Prototype Design Pattern");
                            PrototypeTest prototype = new PrototypeTest();
                            prototype.Run();
                            break;

                        case 5:
                            ConsoleUtility.WriteLine("Running example of Fluent Interface Design Patter");
                            FluentInterface fluent = new FluentInterface();
                            fluent.Run();
                            break;

                        case 6:
                            ConsoleUtility.WriteLine("Running example of Factory Method Design Pattern");
                            FactoryMethodTest factory = new FactoryMethodTest();
                            factory.Run();
                            break;

                        case 7:
                            ConsoleUtility.WriteLine("Running example of Abstract Factory");
                            AbstractFactoryTest abstractFactory = new AbstractFactoryTest();
                            abstractFactory.Run();
                            break;

                        default:
                            break;
                        }
                        break;

                    case 2:
                        ConsoleUtility.WriteLine("Example of Structural Design Pattern");
                        ConsoleUtility.WriteLine("1.-Adapter");
                        ConsoleUtility.WriteLine("2.-Facade");
                        ConsoleUtility.WriteLine("3.-Decorator");
                        ConsoleUtility.WriteLine("4.-Composite");
                        ConsoleUtility.WriteLine("5.-Proxy");
                        ConsoleUtility.WriteLine("6.-Flyweight");
                        ConsoleUtility.WriteLine("7.-Bridge");
                        ii_option = Convert.ToInt32(Console.ReadLine());
                        switch (ii_option)
                        {
                        case 1:
                            ConsoleUtility.WriteLine("Running example of Adapter");
                            AdapterTest adapter = new AdapterTest();
                            adapter.Run();
                            break;

                        case 2:
                            ConsoleUtility.WriteLine("Running example of Facade");
                            FacadeTest facade = new FacadeTest();
                            facade.Run();
                            break;

                        case 3:
                            ConsoleUtility.WriteLine("Running example of Decorator");
                            DecoratorTest decorator = new DecoratorTest();
                            decorator.Run();
                            break;

                        case 4:
                            ConsoleUtility.WriteLine("Running example of Composite");
                            CompositeTest composite = new CompositeTest();
                            composite.Run();
                            break;

                        case 5:
                            ConsoleUtility.WriteLine("Running example of Proxy");
                            ProxyTest proxy = new ProxyTest();
                            proxy.Run();
                            break;

                        case 6:
                            ConsoleUtility.WriteLine("Running example of Flyweight");
                            FlyweightTest flyweight = new FlyweightTest();
                            flyweight.Run();
                            break;

                        case 7:
                            ConsoleUtility.WriteLine("Running example of Bridge");
                            BridgeTest bridge = new BridgeTest();
                            bridge.Run();
                            break;

                        default:
                            break;
                        }
                        break;

                    case 3:
                        ConsoleUtility.WriteLine("Example of Behavioral Design Pattern");
                        ConsoleUtility.WriteLine("1.-Chain of Responsability");
                        ConsoleUtility.WriteLine("2.-Command");
                        ConsoleUtility.WriteLine("3.-Observer");
                        ConsoleUtility.WriteLine("4.-Iterator");
                        ConsoleUtility.WriteLine("5.-State");
                        ConsoleUtility.WriteLine("6.-Template Method");
                        ConsoleUtility.WriteLine("7.-Visitor");
                        ConsoleUtility.WriteLine("8.-Strategy");
                        ConsoleUtility.WriteLine("9.-Mediator");
                        ConsoleUtility.WriteLine("10.-Memento");
                        ConsoleUtility.WriteLine("11.-Interpreter");
                        ii_option = Convert.ToInt32(Console.ReadLine());
                        switch (ii_option)
                        {
                        case 1:
                            ConsoleUtility.WriteLine("Running example of Change Of Responsability");
                            ChainOfResponsability chain = new ChainOfResponsability();
                            chain.Run();
                            break;

                        case 2:
                            ConsoleUtility.WriteLine("Running example of Command");
                            CommandTest command = new CommandTest();
                            command.Run();
                            break;

                        case 3:
                            ConsoleUtility.WriteLine("Running example of Observer");
                            ObserverTest observer = new ObserverTest();
                            observer.Run();
                            break;

                        case 4:
                            ConsoleUtility.WriteLine("Running example of Iterator");
                            IteratorTest iterator = new IteratorTest();
                            iterator.Run();
                            break;

                        case 5:
                            ConsoleUtility.WriteLine("Running example of State");
                            StateTest state = new StateTest();
                            state.Run();
                            break;

                        case 6:
                            ConsoleUtility.WriteLine("Running example of Template Method");
                            TemplateMehodTest templateMehod = new TemplateMehodTest();
                            templateMehod.Run();
                            break;

                        case 7:
                            ConsoleUtility.WriteLine("Running example of Visitor");
                            VisitorTest visitor = new VisitorTest();
                            visitor.Run();
                            break;

                        case 8:
                            ConsoleUtility.WriteLine("Running example of stratgegy");
                            StrategyTest strategy = new StrategyTest();
                            strategy.Run();
                            break;

                        case 9:
                            ConsoleUtility.WriteLine("Running example of Mediator");
                            MediatorTest mediator = new MediatorTest();
                            mediator.Run();
                            break;

                        case 10:
                            ConsoleUtility.WriteLine("Running example of Memento");
                            MementoTest memento = new MementoTest();
                            memento.Run();
                            break;

                        case 11:
                            ConsoleUtility.WriteLine("Running example of Interpreter");
                            InterpreterTest interpreter = new InterpreterTest();
                            interpreter.Run();
                            break;

                        default:
                            break;
                        }
                        break;

                    case 4:
                        ConsoleUtility.WriteLine("Example of SOLID Principles");
                        ConsoleUtility.WriteLine("1.-Single Responsibility Principle");
                        ConsoleUtility.WriteLine("2.-Open-Closed Principle");
                        ConsoleUtility.WriteLine("3.-Liskov Substitution Principle");
                        ConsoleUtility.WriteLine("4.-Interface Segregation Principle");
                        ConsoleUtility.WriteLine("5.-Dependency Inversion Principle");
                        ii_option = Convert.ToInt32(Console.ReadLine());
                        switch (ii_option)
                        {
                        case 1:
                            ConsoleUtility.WriteLine("Running example of Single Responsibility");
                            Invoice invoice = new Invoice();
                            invoice.Run();
                            break;

                        case 2:
                            ConsoleUtility.WriteLine("Running example of Open-Closed Principle");
                            InvoiceOCP invoiceOCP = new InvoiceOCP();
                            invoiceOCP.Run();
                            break;

                        case 3:
                            ConsoleUtility.WriteLine("Running example of Liskov Principle");
                            RunFruit run = new RunFruit();
                            run.Run();
                            break;

                        case 4:
                            ConsoleUtility.WriteLine("Running example of Interface Segregation Principle");
                            Printer printer = new Printer();
                            printer.Run();
                            break;

                        case 5:
                            ConsoleUtility.WriteLine("Running example of Dependency Inversion Principle");
                            RunDIP runDIP = new RunDIP();
                            runDIP.Run();
                            break;
                        }
                        break;

                    default:
                        break;
                    }
                    break;

                case 4:
                    ConsoleUtility.WriteLine("Language DotNet");
                    ConsoleUtility.WriteLine("1.-Abstract");
                    ConsoleUtility.WriteLine("2.-Action");
                    ConsoleUtility.WriteLine("3.-AsyncAwait");
                    ConsoleUtility.WriteLine("4.-Delegate");
                    ConsoleUtility.WriteLine("5.-Extensions");
                    ConsoleUtility.WriteLine("6.-Func");
                    ConsoleUtility.WriteLine("7.-Generics");
                    ConsoleUtility.WriteLine("8.-Predicate");
                    ConsoleUtility.WriteLine("9.-Lock");
                    ConsoleUtility.WriteLine("10.-Reflection");
                    ConsoleUtility.WriteLine("11.-IOC Implementation");
                    ConsoleUtility.WriteLine("12.-Task");
                    ConsoleUtility.WriteLine("13.-Out Variable");
                    ConsoleUtility.WriteLine("14.-Pattern Matching");
                    ConsoleUtility.WriteLine("15.-Digit Separator");
                    ConsoleUtility.WriteLine("16.-Tuples");
                    ConsoleUtility.WriteLine("17.-Ref locals and ref return");
                    ConsoleUtility.WriteLine("18.-AsynReturn");
                    i_option = Convert.ToInt32(Console.ReadLine());
                    switch (i_option)
                    {
                    case 1:
                        ConsoleUtility.WriteLine("Running example of Abstract Class");
                        Square square = new Square();
                        square.Run();
                        break;

                    case 2:
                        ConsoleUtility.WriteLine("Running example of Action");
                        LanguageDotNet.Action action = new LanguageDotNet.Action();
                        action.Run();
                        break;

                    case 3:
                        ConsoleUtility.WriteLine("Running example of AsyncAwait");
                        AsyncAwait asyncAwait = new AsyncAwait();
                        asyncAwait.Run();
                        break;

                    case 4:
                        ConsoleUtility.WriteLine("Running example of Delegate");
                        Number number = new Number();
                        number.Run();
                        break;

                    case 5:
                        ConsoleUtility.WriteLine("Running example of Extensions");
                        IntExtensions intExtensions = new IntExtensions();
                        intExtensions.Run();
                        break;

                    case 6:
                        ConsoleUtility.WriteLine("Running example of Func");
                        Func func = new Func();
                        func.Run();
                        break;

                    case 7:
                        ConsoleUtility.WriteLine("Running example of Generics");
                        Generic generic = new Generic();
                        generic.Run();
                        break;

                    case 8:
                        ConsoleUtility.WriteLine("Running example of Predicate");
                        Predicate predicate = new Predicate();
                        predicate.Run();
                        break;

                    case 9:
                        ConsoleUtility.WriteLine("Running example of Lock");
                        LockTest lockTest = new LockTest();
                        lockTest.runTest();
                        break;

                    case 10:
                        ConsoleUtility.WriteLine("Running example of Reflection");
                        Customer customer = new Customer();
                        customer.Run();
                        break;

                    case 11:
                        ConsoleUtility.WriteLine("Running example of IOC Implementation");
                        IOCImplementation.Run();
                        break;

                    case 12:
                        ConsoleUtility.WriteLine("Running example of Tasks");
                        TaskReturnValue taskReturnValue = new TaskReturnValue();
                        taskReturnValue.Run();
                        break;

                    case 13:
                        ConsoleUtility.WriteLine("Running example of Out variable");
                        OutVariables outVariables = new OutVariables();
                        outVariables.Run();
                        break;

                    case 14:
                        ConsoleUtility.WriteLine("Running example of Pattern Matching");
                        PatternMatching patternMatching = new PatternMatching();
                        patternMatching.Run();
                        break;

                    case 15:
                        ConsoleUtility.WriteLine("Running example of Digit Separators");
                        DigitSeparator digitSeparator = new DigitSeparator();
                        digitSeparator.Run();
                        break;

                    case 16:
                        ConsoleUtility.WriteLine("Running example of Tuple");
                        Tuples tuples = new Tuples();
                        tuples.Run();
                        break;

                    case 17:
                        ConsoleUtility.WriteLine("Running example of Ref locals and ref returns");
                        RefLocalRefReturn refLocalRefReturn = new RefLocalRefReturn();
                        refLocalRefReturn.Run();
                        break;

                    case 18:
                        ConsoleUtility.WriteLine("Running example of AsyncReturn");
                        AsyncReturn asyncReturn = new AsyncReturn();
                        asyncReturn.Run();
                        break;

                    default:
                        break;
                    }
                    break;

                default:
                    ConsoleUtility.WriteLine("Exit");
                    break;
                }
            }
        }
Beispiel #11
0
        public static void ExecuteCommands(MessageEventArgs e, string[] MessageArray)
        {
            if (EightBallArray == null) //checks if load text has ran yet
            {
                loadText();
            }

            #region !flipcoin
            if (MessageArray[0].ToString().ToLower() == "!flipcoin")
            {
                //simple coin flip
                int flip = rnd.Next(0, 2);
                if (flip == 0)
                {
                    e.Channel.SendMessage(e.User.Mention + " ` " + " Flipped a coin and it landed Heads up!" + " `");
                }
                if (flip == 1)
                {
                    e.Channel.SendMessage(e.User.Mention + " ` " + " Flipped a coin and it landed Tails up!" + " `");
                }
            }
            #endregion
            #region !ban
            if (MessageArray[0].ToLower() == "!ban")
            {
                //setup for starting a vote ban
                string             ReportedPlayer  = "";
                string             PlayerReporting = "";
                IEnumerable <User> ReportedUsers;
                IEnumerable <User> OnlineUsers;
                bool matchedplayer = false;
                PlayerReporting = e.User.Name;
                OnlineUsers     = e.Server.Users;
                int countUsers = 0;

                if (MessageArray.Length > 1)
                {
                    for (int i = 1; i < MessageArray.Length; i++)
                    {
                        if (i > 1)
                        {
                            ReportedPlayer = ReportedPlayer + " " + MessageArray[i];
                        }
                        else
                        {
                            ReportedPlayer = ReportedPlayer + MessageArray[i];
                        }
                    }
                    foreach (User user in OnlineUsers)
                    {
                        if (user.Status == UserStatus.Online && user.Id != BotID)
                        {
                            countUsers = countUsers + 1;
                        }
                    }

                    if (e.Server.FindUsers(ReportedPlayer, true) != null)
                    {
                        ReportedUsers = e.Server.FindUsers(ReportedPlayer, true);
                        if (e.User.Roles.Contains(Mod) && false)
                        {
                            foreach (User user in ReportedUsers)
                            {
                                if (!user.HasRole(Mod))
                                {
                                    var AsyncClass = new AsyncAwait();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                                    AsyncClass.BanUser(user, e);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                                    admins.SendMessage("`" + "The user " + ReportedPlayer + " was banned by " + e.User.Name + "`");
                                    matchedplayer = false;
                                }
                            }
                        }
                        else if (countUsers > 3)
                        {
                            if (lastplayerReported == "")
                            {
                                foreach (User user in ReportedUsers)
                                {
                                    if (user.Name == ReportedPlayer && !user.HasRole(Mod))
                                    {
                                        matchedplayer = true;
                                    }
                                }
                                if (matchedplayer == true)
                                {
                                    YDCbot.StartBanTimer();
                                    e.User.SendMessage("New Ban starting now! Vote ends in 5 minutes.");
                                    lastplayerReported = ReportedPlayer;
                                    ListofReporters.Add(PlayerReporting);
                                }
                                else
                                {
                                    e.User.SendMessage("No user found by that name!");
                                }
                            }
                            else if (lastplayerReported == ReportedPlayer)
                            {
                                if (ListofReporters.Contains(PlayerReporting))
                                {
                                    e.User.SendMessage("Can only Report Once");
                                }
                                else
                                {
                                    ListofReporters.Add(PlayerReporting);
                                    int countReports = ListofReporters.Count;
                                    e.User.SendMessage("Petition added total count " + countReports + " out of " + countUsers / 2 + " votes needed.");
                                    if (countReports >= countUsers / 2)
                                    {
                                        foreach (User user in ReportedUsers)
                                        {
                                            var AsyncClass = new AsyncAwait();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                                            AsyncClass.BanUser(user, e);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                                            YDCbot.StopBanTimer();
                                        }
                                        foreach (string reporter in ListofReporters)
                                        {
                                            admins.SendMessage("`" + "The user " + ReportedPlayer + " was banned by " + reporter + "`");
                                        }
                                        ListofReporters.Clear();
                                        lastplayerReported = "";
                                    }
                                }
                            }
                            else
                            {
                                e.User.SendMessage("There is already a vote to ban on someone else!");
                            }
                        }
                        else
                        {
                            e.User.SendMessage("There must be more than 4 players online to ban someone");
                        }
                    }
                }
                else
                {
                    e.User.SendMessage("You must enter a name to report a player");
                }
            }
            #endregion
            #region !8ball
            if (MessageArray[0].ToLower() == "!8ball")
            {
                //asks the 8ball a question, then sends the response back into the chat
                int value;
                if (MessageArray.Length > 1)
                {
                    value = rnd.Next(0, EightBallArray.Length);
                    e.Channel.SendMessage(e.User.Mention + "` asked " + e.Message.Text + "--The Eightball:" + EightBallArray[value] + " `");
                }
                else
                {
                    e.User.SendMessage("You must ask the 8ball something");
                }
            }
            #endregion
            #region !roll
            if (e.Message.Text.ToLower().Contains("!roll"))
            {
                int value;
                if (MessageArray[0].ToLower() == "!roll")
                {
                    if (isRoleTimerActive && !e.Message.Channel.IsPrivate)
                    {
                        if (MessageArray.Length > 1)
                        {
                            if (MessageArray[1].ToLower() == "end")
                            {
                                if (e.User == RoleStarter || e.User.HasRole(Mod))
                                {
                                    YDCbot.StopRollTimer();
                                }
                            }
                        }
                        else if (!RolePlayers.Contains(e.User.Name))
                        {
                            int roll = rnd.Next(1, Rolevalue + 1);
                            e.Channel.SendMessage(e.User.Mention + " ` " + "Rolled a " + roll + " out of " + Rolevalue + "`");
                            RolePlayers.Add(e.User.Name);
                            RoleScores.Add(roll);
                        }

                        return;
                    }
                    else if (MessageArray.Length > 1 && !isRoleTimerActive)
                    {
                        if (MessageArray[1].ToLower() == "start" && !isRoleTimerActive && !e.Message.Channel.IsPrivate)
                        {
                            YDCbot.StartRollTimer();
                            isRoleTimerActive = true;
                            RoleCh            = e.Channel;
                            RoleStarter       = e.User;

                            if (MessageArray.Length > 2)
                            {
                                bool isSuccess = int.TryParse(MessageArray[2], out value);
                                if (isSuccess == true)
                                {
                                    value     = Math.Abs(value);
                                    Rolevalue = value;
                                    if (value <= 1000000)
                                    {
                                        int roll = rnd.Next(1, value + 1);
                                        e.Channel.SendMessage(e.User.Mention + " ` " + "Started a roll for the next 60 seconds and then rolled " + roll + " out of " + value + "`");
                                        RolePlayers.Add(e.User.Name);
                                        RoleScores.Add(roll);
                                    }
                                    else
                                    {
                                        int roll = rnd.Next(1, 1000001);
                                        e.Channel.SendMessage(e.User.Mention + " ` " + "Started a roll for the next 60 seconds and then rolled " + roll + " out of " + 1000000 + "`");
                                        RolePlayers.Add(e.User.Name);
                                        RoleScores.Add(roll);
                                    }
                                }
                            }
                            else
                            {
                                Rolevalue = 100;
                                int roll = rnd.Next(1, 101);
                                e.Channel.SendMessage(e.User.Mention + " ` " + "Started for the next 60 seconds a roll and then rolled " + roll + " out of " + 100 + "`");
                                RolePlayers.Add(e.User.Name);
                                RoleScores.Add(roll);
                            }
                        }
                        else
                        {
                            bool isSuccess = int.TryParse(MessageArray[1], out value);
                            if (isSuccess == true)
                            {
                                value = Math.Abs(value);
                                if (value <= 1000000)
                                {
                                    int roll = rnd.Next(1, value);
                                    e.Channel.SendMessage(e.User.Mention + " ` " + "Rolled a " + roll + " out of " + value + "`");
                                }
                                else
                                {
                                    int roll = rnd.Next(1, 1000001);
                                    e.Channel.SendMessage(e.User.Mention + " ` " + "Rolled a " + roll + " out of " + 1000000 + "`");
                                }
                            }
                        }
                    }
                    else if (!isRoleTimerActive)
                    {
                        int roll = rnd.Next(1, 101);
                        e.Channel.SendMessage(e.User.Mention + " ` " + "Rolled a " + roll + " out of 100" + "`");
                    }
                }
            }
            #endregion
            #region !raffle
            if (MessageArray[0].ToLower() == "!raffle" && !e.Channel.IsPrivate)
            {
                int value;
                IEnumerable <User> OnlineUsers;
                OnlineUsers = e.Server.Users;
                int timerV = 1;
                int v;
                int length = MessageArray.Length;
                if (length > 1)
                {
                    if (MessageArray[1].ToLower() == "end" && isRaffleTimerActive && e.User == RaffleStarter)
                    {
                        YDCbot.StopRaffleTimer();
                    }
                    else if (MessageArray[1].ToLower() == "online" && !isRaffleTimerActive)
                    {
                        foreach (User user in OnlineUsers)
                        {
                            if (user.Status == UserStatus.Online && user.Id != BotID)
                            {
                                raffleList.Add(user.Name);
                            }
                        }
                        value = raffleList.Count();
                        int ind = rnd.Next(0, value);
                        e.Channel.SendMessage(" ` " + " The winner of the raffle was " + raffleList[ind] + "`");
                        raffleList.Clear();
                    }
                    else if (MessageArray[1].ToLower() == "signup" && !isRaffleTimerActive)
                    {
                        if (length > 2)
                        {
                            bool isSuccess = int.TryParse(MessageArray[3], out v);
                            timerV = v;
                        }
                        else
                        {
                            timerV = 5;
                        }

                        e.Channel.SendMessage(e.User.Name + " ` " + " Has started a raffle for the next " + timerV + " minutes. If you would like to enter type !raffle" + "`");
                        isRaffleTimerActive = true;
                        RaffleStarter       = e.User;
                        RaffleCh            = e.Channel;
                        YDCbot.StartRaffleTimer(timerV);
                    }
                    else if (MessageArray[1].ToLower() == "group" && length > 2 && !isRaffleTimerActive)
                    {
                        if (MessageArray[2].ToLower() == "member")
                        {
                            foreach (User user in OnlineUsers)
                            {
                                if (user.HasRole(Member) && user.Status == UserStatus.Online)
                                {
                                    raffleList.Add(user.Name);
                                }
                            }
                            value = raffleList.Count();
                            int ind = rnd.Next(0, value);
                            e.Channel.SendMessage(Member.Mention + " ` " + " The winner of the raffle was " + raffleList[ind] + "`");
                            raffleList.Clear();
                        }
                        if (MessageArray[2].ToLower() == "mod")
                        {
                            foreach (User user in OnlineUsers)
                            {
                                if (user.HasRole(Mod) && user.Status == UserStatus.Online)
                                {
                                    raffleList.Add(user.Name);
                                }
                            }
                            value = raffleList.Count();
                            int ind = rnd.Next(0, value);
                            e.Channel.SendMessage(Mod.Mention + " ` " + " The winner of the raffle was " + raffleList[ind] + "`");
                            raffleList.Clear();
                        }
                        if (MessageArray[2].ToLower() == "hasrole")
                        {
                            foreach (User user in OnlineUsers)
                            {
                                if (user.Status == UserStatus.Online)
                                {
                                    if (user.HasRole(Mod) || user.HasRole(Member))
                                    {
                                        raffleList.Add(user.Name);
                                    }
                                }
                            }
                            value = raffleList.Count();
                            int ind = rnd.Next(0, value);
                            e.Channel.SendMessage(Mod.Mention + Member.Mention + " ` " + " The winner of the raffle was " + raffleList[ind] + "`");
                            raffleList.Clear();
                        }
                    }
                    else
                    {
                        e.User.SendMessage("There is already an active Raffle!");
                    }
                }
                else if (isRaffleTimerActive)
                {
                    if (!raffleList.Contains(e.User.Name))
                    {
                        raffleList.Add(e.User.Name);
                    }
                    else
                    {
                        e.User.SendMessage("You are already entered into the raffle!");
                    }
                }
                else
                {
                    e.User.SendMessage("Currently there is no active raffle.");
                }
            }
            #endregion
            #region !Imgur
            if (MessageArray[0].ToLower() == "!imgur")
            {
                string Reddit;
                int    number = 0;
                if (MessageArray.Length > 3)
                {
                    e.User.SendMessage("Format is /imgur Subreddit ImageNumber");
                }
                else if (MessageArray.Length > 2)
                {
                    Reddit = MessageArray[1].ToString();
                    bool isSuccess = int.TryParse(MessageArray[2], out number);
                    if (!e.Channel.IsPrivate)
                    {
                        admins.SendMessage("`" + e.User.Name.ToString() + " posted an image from r/" + Reddit + " in the " + e.Channel.Name.ToString() + " Channel" + "`");
                    }
                    ImgurBot.ImgurUpdate(Reddit, number, e);
                }
                else if (MessageArray.Length > 1)
                {
                    Reddit = MessageArray[1].ToString();
                    if (!e.Channel.IsPrivate)
                    {
                        admins.SendMessage("`" + e.User.Name.ToString() + " posted an image from r/" + Reddit + " in the " + e.Channel.Name.ToString() + " Channel" + "`");
                    }
                    ImgurBot.ImgurUpdate(Reddit, number, e);
                }
                else
                {
                    e.User.SendMessage("Please enter a subreddit to Imgur");
                }
            }
            #endregion
            #region !youtube
            if (MessageArray[0].ToLower() == "!youtube" && !e.Channel.IsPrivate)
            {
                if (MessageArray[1].ToLower() == "stop" && e.User.HasRole(Mod))
                {
                    e.User.SendMessage("Music Stopping!");
                    MusicPlayer.ExitLoop = true;
                }
                else
                {
                    if (!MusicPlayer.IsPlaying)
                    {
                        MusicPlayer.ExitLoop = false;
                        MusicPlayer.PlayYouTube(MessageArray[1], e);
                    }
                    else
                    {
                        e.User.SendMessage("Music is already playing!");
                    }
                }
            }
            #endregion
            #region !help
            if (e.Message.Text.ToLower().Contains("!help"))
            {
                e.Message.Delete();
                e.User.SendMessage("```" + helptext + "```");
            }
            #endregion
        }
Beispiel #12
0
        public static void ExecuteModCommands(MessageEventArgs e, string[] MessageArray)//called from YDCbot.cs
        {
            #region !clear
            if (MessageArray[0].ToLower() == "!clear") //checks if first phrase entered was !clear, because it passes through ToLower, !CLEAR would also enter this command. repeated throughout commands
            {
                //clears public chat of messages
                if (e.Message.Channel.IsPrivate == true)
                {
                    return;                                      //if sent from a PM escapes the loop
                }
                int    value;
                string ReportedPlayer        = "";
                IEnumerable <Message> Imsgs  = null;
                IEnumerable <User>    Iusers = null;

                if (MessageArray.Length > 1) //if the message is longer than 1 will expect the second value is a number and convert it to int
                {
                    int.TryParse(MessageArray[1], out value);
                    Imsgs = e.Channel.Messages.OrderByDescending(x => x.Timestamp).Take(value); //gets x amount of messages in the channe
                }
                else
                {
                    Imsgs = e.Channel.Messages.OrderByDescending(x => x.Timestamp).Take(100); //defaults to 100 messages
                }
                if (MessageArray.Length > 2)                                                  //if the message is longer than 2 will expect third value is a user
                {
                    for (int i = 2; i < MessageArray.Length; i++)                             //forloop that puts together string sections, great if username has a space in it, but otherwise not used. shows up throughout code
                    {
                        ReportedPlayer = ReportedPlayer + MessageArray[i];
                    }
                    if (ReportedPlayer == "imgur")
                    {
                        Iusers = e.Server.FindUsers("YDC", true);
                        Imsgs  = Imsgs.Where(x => Iusers.Contains(x.User));
                        var AsyncClass1 = new AsyncAwait();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        AsyncClass1.Deleteimgur(Imsgs, e, admins, ReportedPlayer);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    }
                    else
                    {
                        Iusers = e.Server.FindUsers(ReportedPlayer, true);
                    }

                    if (Iusers == null)
                    {
                        e.User.SendMessage("No User Found by that name");
                        return;
                    }
                    Imsgs = Imsgs.Where(x => Iusers.Contains(x.User)); //returns messages from the user out of the amount of messages that was collected
                }
                if (Imsgs.Any())                                       //checks if any messages were found
                {
                    var AsyncClass = new AsyncAwait();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    AsyncClass.DeleteMessages(Imsgs, e, admins, ReportedPlayer);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                }
                else
                {
                    e.User.SendMessage("No Messages Found");
                }
            }
            #endregion
            #region !grantchannel
            if (MessageArray[0].ToLower() == "!grantchannel" && YDCbot.ChannelToGrant)
            {
                //creates a new channel and gives rights to the given user
                IEnumerable <User> Iowners;
                List <User>        ListOwners = new List <User>();

                if (MessageArray.Length > 1)
                {
                    for (int i = 1; i < MessageArray.Length; i++)
                    {
                        if (i > 1)
                        {
                            NewChannelOwnerString = NewChannelOwnerString + " " + MessageArray[i];
                        }
                        else
                        {
                            NewChannelOwnerString = NewChannelOwnerString + MessageArray[i];
                        }
                    }

                    if (e.Server.FindUsers(NewChannelOwnerString, true) != null) //checks if entered name is a real user
                    {
                        Iowners    = e.Server.FindUsers(NewChannelOwnerString);
                        ListOwners = Iowners.ToList(); //converts Ienumerable to List
                        if (ListOwners.Count > 1)      //if more than one user found escape loop
                        {
                            e.User.SendMessage("More than one user found by that name");
                            return;
                        }
                        else
                        {
                            NewChannelOwner = ListOwners[0];
                            e.Server.CreateChannel(NewChannelOwnerString, ChannelType.Voice); //creates voice channel with the users name, they can change it later
                        }
                    }
                    else
                    {
                        e.User.SendMessage("No user by that name found!");
                    }
                }
                else
                {
                    e.User.SendMessage("No username entered!");
                }
            }
            #endregion
            #region !save
            if (MessageArray[0].ToLower() == "!save")
            {
                //saves information to file
                //currently only saves twitter info
                TwitterBot.SaveTwitter(); //saves twitter var
            }
            #endregion
            #region !exit
            if (MessageArray[0].ToLower() == "!exitapp")
            {
                Environment.Exit(1);
            }
            #endregion
        }