void Awake()
        {
            ChildToggles = new List<Toggle>(this.GetComponentsInChildren<Toggle>());
              foreach(var toggle in ChildToggles) {
            var toggleRef = toggle;
            toggle.onValueChanged.AddListener(_ => {
              if(!_) {
            if(ChildToggles.Count(a => a.isOn) < MinActiveElements)
              LastDisabledToggle.isOn = true;
            LastDisabledToggle = toggleRef;
              }

              if(_)
            BoardEditor.Current.Board.ItemTypes.Add((ItemType)Enum.Parse(typeof(ItemType), toggleRef.name));
              else
            BoardEditor.Current.Board.ItemTypes.Remove((ItemType)Enum.Parse(typeof(ItemType), toggleRef.name));
            });

            BoardEditor.Current.OnLevelLoaded += _ => {
              ChildToggles.ForEach(t => t.interactable = false);
              ChildToggles.ForEach(t => t.isOn = _.ItemTypes.Contains((ItemType)Enum.Parse(typeof(ItemType), t.name)));
              ChildToggles.ForEach(t => t.interactable = true);
            };
              }
        }
Beispiel #2
0
        public static void Main()
        {
            var list = new List<String>();
            list.Add("ONE");
            list.Add("TWO");
            list.Add("THREE");
            list.Add("FOUR");

            // Display the contents of the list using the Print method.
            Print("With Print(string) as Action<T>.");
            list.ForEach(Print);

            // Create an anonymous delegate.
            Print("\nWith anonymous delegate.");
            list.ForEach(delegate(String name)
                {
                    name = string.Format("name is {0}", name);
                    Console.WriteLine(name);
                });

            // Let resharper fix up the above anonymous delegate.
            Print("\nWith anonymous delegate.");
            list.ForEach(Console.WriteLine);

            // Print with another method.
            Print("\nWith FancyPrint(string) as Action<T>.");
            list.ForEach(FancyPrint);
        }
    static void Main(string[] args)
    {
        //TEST1
        //11
        //0 11 1 10 5 6 3 4 7 2

        int n = int.Parse(Console.ReadLine());
        string box = string.Join("", Console.ReadLine().Split(' '));
        List<string> input = box.Select(x => x.ToString()).ToList();
        List<List<int>> result = new List<List<int>>();
        int length = input.Count;

        input.ForEach(x => result.Add(new List<int>() { Convert.ToInt32(x) }));
        for (int i = 0; i <= length; i++)
        {
            input = input.SelectMany(x => box, (x, y) => x + y).ToList();
            input.RemoveAll(x => string.IsNullOrEmpty(x));
            input.ForEach(t => result.Add(t.Select(q => (int)Char.GetNumericValue(q)).ToList()));
        }
        result.ForEach(m => m.Sort());
        result.ForEach(x => Console.WriteLine(string.Join("",x)));
        //result = result.Select(x => string.Join("", x)).Distinct().Select(s => s.Select(l => int.Parse(l.ToString())).ToList()) .ToList();
        //List<string> print = new List<string>();
        //foreach (var item in result)
        //{
        //    if (item.Sum() == n)
        //    {
        //        Console.WriteLine(string.Join(" + ",item) + " = " + item.Sum());
        //    }
        //}
    }
        static void Main()
        {
            var films = new List<Film>
            {
                new Film {Name="Jaws", Year=1975},
                new Film {Name="Singing in the Rain", Year=1952},
                new Film {Name="Some like it Hot", Year=1959},
                new Film {Name="The Wizard of Oz", Year=1939},
                new Film {Name="It's a Wonderful Life", Year=1946},
                new Film {Name="American Beauty", Year=1999},
                new Film {Name="High Fidelity", Year=2000},
                new Film {Name="The Usual Suspects", Year=1995}
            };

            Action<Film> print =
                film => Console.WriteLine("Name={0}, Year={1}", film.Name, film.Year);

            // Note: extra lines added for clarity when running
            Console.WriteLine("All films");
            films.ForEach(print);
            Console.WriteLine();

            Console.WriteLine("Oldies");
            films.FindAll(film => film.Year < 1960)
                 .ForEach(print);
            Console.WriteLine();

            Console.WriteLine("Sorted");
            films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));
            films.ForEach(print);
        }
        //In this example i need to sort a collection of employee by hierarchical code splited by '.'
        //so i use an EmployeeAscendingHierachicalComparer class  wich implements IComparer<T> interface
        //and  i pass an instance of to Sort method of List<T>
        static void Main(string[] args)
        {
            var employees = new List<Employee>
            {
                new Employee{Code = "1",Name = "Joe"},
                new Employee{Code = "1.1.1",Name = "Joe"},
                new Employee{Code = "1.1",Name = "Joe"},
                new Employee{Code = "1.1.2",Name = "Joe"},
                new Employee{Code = "1.2.2",Name = "Joe"},
                new Employee{Code = "1.2",Name = "Joe"},
                new Employee{Code = "2",Name = "Joe"},
                new Employee{Code = "3",Name = "Joe"},
                new Employee{Code = "3.1",Name = "Joe"},
                new Employee{Code = "3.3",Name = "Joe"},
                new Employee{Code = "2.1",Name = "Joe"},
                new Employee{Code = "2.1.3",Name = "Joe"},
                new Employee{Code = "2.1.3.1",Name = "Joe"},
                new Employee{Code = "3.2",Name = "Joe"},
                new Employee{Code = "3.2.1",Name = "Joe"},
                new Employee{Code = "3.1.1",Name = "Joe"},
                new Employee{Code = "3.1.4",Name = "Joe"},
                new Employee{Code = "1.1.2.3",Name = "Joe"},
                new Employee{Code = "1.1.2.1",Name = "Joe"},
            };

            Console.WriteLine("** Employees **");
            Console.WriteLine();
            employees.ForEach(Console.WriteLine);
            Console.WriteLine();
            Console.WriteLine("** Employees ** Ordered");
            Console.WriteLine();
            employees.Sort(new EmployeeAscendingHierachicalComparer());
            employees.ForEach(Console.WriteLine);
            Console.ReadKey();
        }
Beispiel #6
0
        /// <summary>Foreach
        /// </summary>
        public static void MethodForeach()
        {
            List<String> names = new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            names.ForEach(Print);

            // The following demonstrates the anonymous method feature of C#
            // to display the contents of the list to the console.
            names.ForEach(delegate(String name)
            {
                Thread.Sleep(1000);
                Console.WriteLine(name);
            });
            names.ForEach(new Action<string>((s) =>
            {
                Thread.Sleep(1000);
                Print(s);
            }));
            names.ForEach(new Action<string>((s) =>
            {
                //这个是异步的
                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    Print(s+"sssss");
                });
            }));
            Console.ReadLine();
        }
Beispiel #7
0
        static void ConfigureLogging(Arguments arguments)
        {
            var writeActions = new List<Action<string>>();

            if (arguments.Output == OutputType.BuildServer)
            {
                writeActions.Add(Console.WriteLine);
            }

            if (arguments.LogFilePath == "console")
            {
                writeActions.Add(Console.WriteLine);
            }
            else if (arguments.LogFilePath != null)
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(arguments.LogFilePath));
                    if (File.Exists(arguments.LogFilePath))
                    {
                        using (File.CreateText(arguments.LogFilePath)) { }
                    }

                    writeActions.Add(x => WriteLogEntry(arguments, x));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to configure logging: " + ex.Message);
                }
            }

            Logger.WriteInfo = s => writeActions.ForEach(a => a(s));
            Logger.WriteWarning = s => writeActions.ForEach(a => a(s));
            Logger.WriteError = s => writeActions.ForEach(a => a(s));
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            List<string> nameList = new List<string>();
            nameList.Add("AJ");
            nameList.Add("Sandra");
            nameList.Add("Theodore");
            nameList.Add("Akwasi");
            nameList.Add("Thommy");
            nameList.Add("AkwasiiJunior");
            nameList.Add("Christina");
            nameList.Add("Millie");
            nameList.Add("Akwasi Junior");
            nameList.Add("Pappa");
            nameList.Add("Kofi");
            nameList.Add("A. Junior");

            Console.WriteLine("1 - View all names");
            Console.WriteLine("2 - View all names that beings with A");
            string userChoice = Console.ReadLine();

            if (userChoice == "1")
            {
                Console.WriteLine($"You Selected 1 \r\n");
                nameList.ForEach(name => Console.WriteLine(name));

            }
            else if (userChoice == "2")
            {
                Console.WriteLine("You Selected 2");
                nameList.ForEach(name => Console.WriteLine(name));
            }
            System.Threading.Thread.Sleep(9000);
        }
        public KeyValueAndTimeSpanGroup(string name, List<KeyValueAndTimeSpan> keyValueAndTimeSpans)
        {
            this.name = name;
            this.keyValueAndTimeSpans = keyValueAndTimeSpans;

            Action calculateCommonTimeSpan = () =>
            {
                monitorHierarchy = false;
                CommonTimeSpanTotalMilliseconds = keyValueAndTimeSpans.Any()
                                              && keyValueAndTimeSpans.Select(kvats => kvats.TimeSpanTotalMilliseconds)
                                                  .Distinct()
                                                  .Count() == 1
                    ? keyValueAndTimeSpans.First().TimeSpanTotalMilliseconds
                    : null;
                monitorHierarchy = true;
            };

            //Monitor children for a common timespan
            keyValueAndTimeSpans.ForEach(kvats1 => 
                kvats1.OnPropertyChanges(kvats2 => kvats2.TimeSpanTotalMilliseconds)
                    .Where(tstm => monitorHierarchy)
                    .Subscribe(timeSpan => calculateCommonTimeSpan()));
            
            //Propogate common time span changes to children
            this.OnPropertyChanges(kwatsg => kwatsg.CommonTimeSpanTotalMilliseconds)
                .Where(tstm => monitorHierarchy)
                .Subscribe(commonTimeSpan =>
                {
                    monitorHierarchy = false;
                    keyValueAndTimeSpans.ForEach(kvats => kvats.TimeSpanTotalMilliseconds = commonTimeSpan);
                    monitorHierarchy = true;
                });

            calculateCommonTimeSpan();
        }
        public static void Main(string[] args)
        {
            IEnumerable<int> enumerable = new List<int>() {5, 10, 100 };

            enumerable.ForEach(Console.WriteLine);
            enumerable.ForEach(x => Console.WriteLine(x + 1011100));
        }
        public List<GroupBuyItem> Get(int id,string action = "")
        {
            List<GroupBuyItem> order = new List<GroupBuyItem>();
            using (var db = new HoGameEISContext())
            {
                order = db.GroupBuyItems.Where(o => o.GroupBuyId == id).ToList();

                order.ForEach((m) =>
                {
                    m.SubItems = db.GroupBuySubItems.Where(s => s.ItemId == m.ItemId).ToList();
                    List<GroupBuySubItem> subItems = m.SubItems.ToList();
                    subItems.ForEach((si) =>
                    {
                        si.GroupBuySubscribers = db.GroupBuySubscribers.Where(gs => gs.SubItemId == si.SubItemId).ToList();
                    });
                });

                if (action == "orderDetail") {
                    //過濾未被選擇的子項目
                    order.ForEach((m) =>
                    {
                        m.SubItems = m.SubItems.Where(o => o.GroupBuySubscribers.Count > 0).ToList();
                    });
                }

            }
            return order;
        }
        // optionally receive values specified with Html helper
        public ActionResult UploadFile(int? entityId)
        {
            // here we can send in some extra info to be included with the delete url
            var statuses = new List<ViewDataUploadFileResult>();
            for (var i = 0; i < Request.Files.Count; i++)
            {
                var st = FileSaver.StoreFile(x =>
                {
                    x.File = Request.Files[i];
                    //note how we are adding an additional value to be posted with delete request
                    //and giving it the same value posted with upload
                    x.DeleteUrl = Url.Action("DeleteFile", new { entityId = entityId });
                    x.StorageDirectory = Server.MapPath("~/Content/uploads");
                    x.UrlPrefix = "/Content/uploads";

                    //overriding defaults
                    x.FileName = Request.Files[i].FileName;// default is filename suffixed with filetimestamp
                    x.ThrowExceptions = true;//default is false, if false exception message is set in error property
                });

                statuses.Add(st);
            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnail_url = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            return Json(new { files = statuses });
        }
        static void Main(string[] args)
        {
            List<Account> accounts = new List<Account>()
            {
                Account.CreateAccount("Karl Checking", 0.05), //Defaults to a no interest
                Account.CreateAccount("Karl Savings", 0.12, InterestTypes.Yearly),
                Account.CreateAccount("Karl Mutual", 0.8, InterestTypes.Monthly),
                Account.CreateAccount("Karl 401K", 0.25, InterestTypes.Quarterly)
            };

            //Deposit initial balance.
            accounts.ForEach(acc => acc.Deposit(150));
            //Set accounts to their end balance.
            accounts.ForEach(acc =>
                {
                    decimal endBalance = acc.EstimateBalance(10);
                    acc.Withdraw(150);
                    acc.Deposit(endBalance);
                });
            //Display account information.
            accounts.ForEach(acc =>
                {
                    Console.WriteLine("{0,-20} - {1,30}: {2:c}", acc.AccountHolder, acc.AccountNumber, acc.Balance);
                });

            Console.ReadKey();
        }
        public static void Run(Action test, int threads, int iterations)
        {
            var threadList = new List<Thread>();

            Exception exeptionResult = null;
            for (int i = 0; i < threads; i++)
            {
                var t = new Thread(new ThreadStart(() =>
                {
                    for (var iter = 0; iter < iterations; iter++)
                    {
                        try
                        {
                            test();
                        }
                        catch (Exception ex)
                        {
                            exeptionResult = ex;
                        }
                    }
                }));
                threadList.Add(t);
            }

            threadList.ForEach(p => p.Start());
            threadList.ForEach(p => p.Join());

            if (exeptionResult != null)
            {
                Trace.TraceError(exeptionResult.Message + "\n\r" + exeptionResult.StackTrace);
                throw exeptionResult;
            }
        }
Beispiel #15
0
        static void Main( string[] args )
        {
            List<Action> actionList = new List<Action>();

            Console.WriteLine("FOR");
            for (int i = 0; i < 10; i++)
            {
                int i1 = i;
                actionList.Add(() => Console.WriteLine(i1));
            }

            actionList.ForEach(x => x.Invoke());

            Console.WriteLine("Foreach");
            actionList.Clear();

            foreach (var i in Enumerable.Range(0, 10))
            {
                actionList.Add(() => Console.WriteLine(i));
            }
            actionList.ForEach(x => x.Invoke());

            Console.ReadKey();

            //            List<object> objlList = new List<object>();
            //            var result = objlList.SingleOrDefault();
            //            Console.WriteLine(result.GetHashCode());
        }
        //Convert List to Data Table
        public DataTable ConvertToDataTable()
        {
            //Instantiate New Data Table
            DataTable dt = new DataTable();

            //Add Columns to the Newly created DataTable
            dt.Columns.Add(new DataColumn("AssessmentTypeID"));
            dt.Columns.Add(new DataColumn("Description"));
            dt.Columns.Add(new DataColumn("Status"));
            dt.Columns.Add(new DataColumn("UserCreated"));
            dt.Columns.Add(new DataColumn("DateCreated"));
            dt.Columns.Add(new DataColumn("LastUpdateUser"));
            dt.Columns.Add(new DataColumn("LastUpdateDate"));

            //Instantiate New List of AssessmentTypes
            AssessmentTypeList = new List<Constructors.AssessmentType>(new Collections().getAssessmentType());

            //Search Dialog Box
            switch (cboSearchQuery.SelectedValue)
            {
                case "Description":
                    AssessmentTypeList.ForEach(at =>
                    {
                        if (at.Description.ToLower().Contains(txtSearchQuery.Text.ToLower()))
                        {
                            dt.Rows.Add(at.AssessmentTypeID, at.Description, at.Status, at.UserCreated, at.DateCreated, at.LastUpdateUser, at.LastUpdateDate);
                        }

                    });
                    break;
                case "A":
                    AssessmentTypeList.ForEach(at =>
                    {
                        if (at.Status == "A")
                        {
                            dt.Rows.Add(at.AssessmentTypeID, at.Description, at.Status, at.UserCreated, at.DateCreated, at.LastUpdateUser, at.LastUpdateDate);
                        }

                    });
                    break;
                case "D":
                    AssessmentTypeList.ForEach(at =>
                    {
                        if (at.Status == "D")
                        {
                            dt.Rows.Add(at.AssessmentTypeID, at.Description, at.Status, at.UserCreated, at.DateCreated, at.LastUpdateUser, at.LastUpdateDate);
                        }

                    });
                    break;
            }

            //If Rows in the DataTable is Empty
            if (dt.Rows.Count == 0)
            {
                dt.Rows.Add(0, "No Record Found");
            }

            return dt;
        }
Beispiel #17
0
        static void Main()
        {
            var graham = new Racer(7, "Graham", "Hill", "UK", 14);
            var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);
            var mario = new Racer(16, "Mario", "Andretti", "USA", 12);

            var racers = new List<Racer>(20) { graham, emerson, mario };

            racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91));
            racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20));
            racers.Add(new Racer(17, "Jack", "ss", "Austria", 22));

            racers.AddRange(new Racer[] {
               new Racer(14, "Niki", "Lauda", "Austria", 25),
               new Racer(21, "Alain", "Prost", "France", 51)});

            var racers2 = new List<Racer>(new Racer[] {
               new Racer(12, "Jochen", "Rindt", "Austria", 6),
               new Racer(14, "Jack", "dd", "Austria", 63),
               new Racer(22, "Ayrton", "Senna", "Brazil", 41) });

            //这个比较实用
            racers.ForEach(r=>Console.WriteLine("{0:A}",r));
            racers.ForEach(r => Console.WriteLine("{0}", r.FirstName));
            racers.ForEach(ActionHandler);
            //排序
            Console.WriteLine("-----------Order---------");
            racers.Sort(new RacerComparer(CompareType.Country));
            racers.ForEach(ActionHandler);
            Console.WriteLine("-----------OverLoad Order---------");
            racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins));
            racers.ForEach(r=>Console.WriteLine("{0}",r.Wins));
            Console.ReadKey();

        }
        static void Main()
        {
            Triangle myTriangle = new Triangle(4, 8);
            Rectangle myRectangle = new Rectangle(4, 8);
            Circle myCircle = new Circle(6);

            List<IShape> shapes = new List<IShape>()
            {
                myCircle, myRectangle, myTriangle
            };

            shapes.ForEach(shape => Console.WriteLine(shape
                .GetType().ToString() + " - Area = " +  shape.CalculateArea()));

            shapes.ForEach(shape => Console.WriteLine(shape
                .GetType().ToString() + " - Perimeter = " + shape.CalculatePerimeter()));

            double shapesAreasTogether = 0;
            shapes.ForEach(shape => shapesAreasTogether += shape.CalculateArea());
            Console.WriteLine("\nShapes Areas Together = {0}", shapesAreasTogether);

            double shapesPerimetersTogether = 0;
            shapes.ForEach(shape => shapesPerimetersTogether += shape.CalculatePerimeter());
            Console.WriteLine("\nShapes Perimeters Together = {0}", shapesPerimetersTogether);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("** Players ** (Not Ordered)");
            Console.WriteLine();
            var players = new List<Player>
            {
                new Player{Nickname = "Ash",Score = 100},
                new Player{Nickname = "Bender",Score = 33},
                new Player{Nickname = "Tony",Score = 999},
                new Player{Nickname = "Cary",Score = 834},
                new Player{Nickname = "Dundie",Score = 666},
                new Player{Nickname = "Faker",Score = 255},
                new Player{Nickname = "Emy",Score = 750},
            };

            players.ForEach(Console.WriteLine);
            Console.WriteLine();
            Console.WriteLine("** Players ** (Ordered Descending by Score)");
            Console.WriteLine();
            //Sort() use the method CompareTo that was implemented in the Player class
            players.Sort();
            players.ForEach(Console.WriteLine);

            Console.ReadKey();
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            var random = new Random();
            var list = new List<int>();

            for (int i = 0; i < 10; i++)
            {
                var command = new AddObjectCommand(list,random.Next(0,20));
                command.DoAction();
            }

            list.ForEach(a => Write($"{a} "));
            WriteLine();
            
            var deleteCommand = new DeleteObjectCommand(list.First(),list);
            deleteCommand.DoAction();

            list.ForEach(a => Write($"{a} "));
            WriteLine();

            CommandsTools.UndoAction();
            list.ForEach(a => Write($"{a} "));

            ReadKey();
        }
    static void Main()
    {
        int sum = int.Parse(Console.ReadLine());
        int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).Distinct().ToArray();
        Console.Clear();
        List<List<int>> allSubsets = new List<List<int>>();

        for (int mask = 1; mask < Math.Pow(2, arr.Length); mask++)
        {
            List<int> currCombo = new List<int>();
            for (int bit = 0; bit < arr.Length; bit++)
            {
                if ((mask >> bit & 1) == 1)
                {
                    currCombo.Add(arr[bit]);
                }
            }

            if (currCombo.Sum() != sum) continue;
            allSubsets.Add(currCombo);
        }

        if (allSubsets.Count == 0)
        {
            Console.WriteLine("No matching subsets.");
        }
        else
        {
            allSubsets.ForEach(list => list.Sort());
            allSubsets = allSubsets.OrderBy(a => a.Count).ThenBy(b => b.First()).ToList();
            allSubsets.ForEach(list => Console.WriteLine("{0} = {1}", string.Join(" + ", list), sum));
        }
    }
Beispiel #22
0
        /// <summary>
        /// Main Execution 
        /// </summary>
        static void Main()
        {
            var hosts = new List<ServiceHost>();
            var services = Gateway.GetCloudServices();

            foreach (var cloudServiceType in services)
            {
                if (cloudServiceType.IsInterface) continue; // Skip the interfaces

                Console.WriteLine("Starting {0}...", cloudServiceType.Name);

                // Add to the Hosts collection
                hosts.Add(new ServiceHost(cloudServiceType));
            }

            // Start each Host
            hosts.ForEach(h => h.Open());

            Console.WriteLine("Listening...");
            Console.WriteLine("[Hit Enter to Exit]");
            Console.ReadLine();

            // Close each Host
            hosts.ForEach(h => h.Close());
        }
Beispiel #23
0
        static void ConfigureLogging(Arguments arguments)
        {
            var writeActions = new List<Action<string>>
            {
                s => log.AppendLine(s)
            };

            if (arguments.Output == OutputType.BuildServer || arguments.LogFilePath == "console" || arguments.Init)
            {
                writeActions.Add(Console.WriteLine);
            }

            if (arguments.LogFilePath != null && arguments.LogFilePath != "console")
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(arguments.LogFilePath));
                    if (File.Exists(arguments.LogFilePath))
                    {
                        using (File.CreateText(arguments.LogFilePath)) { }
                    }

                    writeActions.Add(x => WriteLogEntry(arguments, x));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to configure logging: " + ex.Message);
                }
            }

            Logger.SetLoggers(
                s => writeActions.ForEach(a => a(s)),
                s => writeActions.ForEach(a => a(s)),
                s => writeActions.ForEach(a => a(s)));
        }
        internal override TestResult Execute()
        {
            var result = new TestResult();
            var threads = new List<Thread>();

            var threadCounter = 0;

            while(threadCounter < numberOfThreads_)
            {
                foreach (var action in toTest_)
                {
                    var unmodifiedClosure = action;
                    threads.Add(new Thread(()=>RunTest(result.Exceptions, unmodifiedClosure)));
                    threadCounter++;
                    if(threadCounter >= numberOfThreads_)
                    {
                        break;
                    }
                }

            }

            threads.ForEach(t=>t.Start());
            threads.ForEach(t=>ForceJoin(t, result));

            return result;
        }
Beispiel #25
0
        void assetsControlLoad(object sender, EventArgs e)
        {
            if( Helper.IsInDesignMode )
            {
                return ;
            }

            var extensibility = ObjectFactory.GetInstance<IExtensibility>( ) ;
            var imageRepository=ObjectFactory.GetInstance<IImageRepository>( ) ;

            _imageList = imageRepository.CreateImageList( ) ;
            uiList.SmallImageList = _imageList ;

            var plugins = new List<IPlugin>();

            plugins.AddRange( extensibility.EditorPlugins );
            plugins.AddRange( extensibility.BehaviourPlugins );

            plugins.ForEach( p => imageRepository.Set( p.Icon ) );

            plugins.GroupBy( p => p.CategoryName ).Distinct( ).ForEach(
                grouping => _pluginsForCategories.Add( grouping.Key, new List<IPlugin>( ) ) ) ;

            plugins.ForEach( p=> _pluginsForCategories[p.CategoryName].Add( p ) );

            XElement xml = buildXml( ) ;

            populateTreeFromXml( xml ) ;
        }
    private void Initialize() {
      var ifFoodAhead = new IfFoodAhead();
      var prog2 = new Prog2();
      var prog3 = new Prog3();
      var move = new Move();
      var left = new Left();
      var right = new Right();
      var allSymbols = new List<Symbol>() { ifFoodAhead, prog2, prog3, move, left, right };
      var nonTerminalSymbols = new List<Symbol>() { ifFoodAhead, prog2, prog3 };

      allSymbols.ForEach(s => AddSymbol(s));
      SetSubtreeCount(ifFoodAhead, 2, 2);
      SetSubtreeCount(prog2, 2, 2);
      SetSubtreeCount(prog3, 3, 3);
      SetSubtreeCount(move, 0, 0);
      SetSubtreeCount(left, 0, 0);
      SetSubtreeCount(right, 0, 0);

      // each symbols is allowed as child of the start symbol
      allSymbols.ForEach(s => AddAllowedChildSymbol(StartSymbol, s));
      allSymbols.ForEach(s => AddAllowedChildSymbol(DefunSymbol, s));

      // each symbol is allowed as child of all other symbols (except for terminals that have MaxSubtreeCount == 0
      foreach (var parent in nonTerminalSymbols) {
        foreach (var child in allSymbols) {
          AddAllowedChildSymbol(parent, child);
        }
      }
    }
Beispiel #27
0
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>();
            List<Manager> managers = new List<Manager>();
            List<Programmer> programmers = new List<Programmer>();

            for (int i = 0; i < 3; i++)
            {
                customers.Add(new Customer("ACustomer", i.ToString(), new DateTime((1975 + i), 1, 1), "my a customer address"));
                customers.Add(new Customer("BCustomer", i.ToString(), new DateTime((2000 + i), 1, 1), "my b customer address"));
            }

            managers.Add(new Manager("Manager", "0", new DateTime((1990), 1, 1), 2000));

            for (int i = 0; i < 5; i++)
            {
                programmers.Add(new Programmer("Programmer", i.ToString(), new DateTime((1990), 1, 1), 1000));
            }

            programmers.ForEach(p => managers.First().AddProgrammer(p));

            Console.WriteLine("# Costummers:");
            customers.ForEach(c => Console.WriteLine(c.Print()));

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# Managers:");
            managers.ForEach(c => Console.WriteLine(c.Print()));

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# Programmers:");
            programmers.ForEach(c => Console.WriteLine(c.Print()));

            var costumersA = customers.Where(c => c.Fullname.StartsWith("A"));
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# Costummers, Name starts with 'A':");
            costumersA.OrderBy(c => c.Fullname).ToList().
                ForEach(c => Console.WriteLine(c.Print()));

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# How many Costummers, Name starts with 'A': " + costumersA.Count());

            var costumersA40 = costumersA.Where(c => c.Age > 40);
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# How many Costummers, Name starts with 'A' and age > 40: " + costumersA40.Count());

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("# All Persons:");
            Persons persons = new Persons();
            customers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p));
            managers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p));
            programmers.OrderBy(c => c.Fullname).ToList().ForEach(p => persons.AddPerson(p));
            persons.ToList().ForEach(p => Console.WriteLine(p.Print()));
        }
        public void _initializeDefaultFields(List<IField> pDefaultList)
        {
            pDefaultList.ForEach(item => item.DisplayName = MultiLanguageStrings.GetString(Ressource.CustomizableExport, item.Name + ".Text"));
            pDefaultList.ForEach(item => item.Header = item.DisplayName.ToString());
            if (!_file.IsExportFile)
                pDefaultList.OfType<Field>().Where(item => item.IsRequired).ToList().ForEach(item => item.DisplayName = "* " + item.DisplayName);

            fieldListUserControl1.DefaultList = pDefaultList;
        }
Beispiel #29
0
 public void AtualizaSeguidoresTarefas(List<string> seguidores, Tarefa tarefa)
 {
     using (TimeSContext db = new TimeSContext())
     {
         seguidores.ForEach(u => db.Entry(db.Users.Find(u)).State = EntityState.Modified);
         seguidores.ForEach(u => db.Users.Attach(db.Users.Find(u)));
         db.SaveChanges();
     }
 }
Beispiel #30
0
 public double ExpectedCardValue(IEnumerable<Card> cardsCollection)
 {
     List<Card> cards = new List<Card>(cardsCollection);
     double valueSum = 0;
     int numberOfCardsLeft = 0;
     cards.ForEach(card => valueSum += card.NumberLeft * card.Value.Value);
     cards.ForEach(card => numberOfCardsLeft += card.NumberLeft);
     return valueSum / numberOfCardsLeft;
 }
 /// <summary>
 /// 恢复动作模型对比结果
 /// </summary>
 public void ResetDefault()
 {
     Index      = 0;
     IsCompared = false;
     ActionFrames?.ForEach(o => o.IsCompared = false);
 }
Beispiel #32
0
 protected override void OnClear(List <View> views)
 {
     views?.ForEach(x => LayoutHandler?.Remove(x));
     InvalidateMeasurement();
 }
Beispiel #33
0
 public void NotifyObservers()
 {
     _observers?.ForEach(observer => observer.OnNext(this));
 }
Beispiel #34
0
 /// <summary>
 /// Foreach of the given list of facts, adds the "aFact -> owl:differentFrom -> bFact" relation to the data [OWL2]
 /// </summary>
 public RDFOntologyData AddAllDifferentRelation(List <RDFOntologyFact> ontologyFacts)
 {
     ontologyFacts?.ForEach(outerFact =>
                            ontologyFacts?.ForEach(innerFact => this.AddDifferentFromRelation(innerFact, outerFact)));
     return(this);
 }
Beispiel #35
0
        public IDownloader <DownloadResult, List <string> > AddUrls(List <string> urls)
        {
            urls?.ForEach(url => _urlsQueue.Enqueue(url));

            return(this);
        }
Beispiel #36
0
        private static Tuple <List <DayPeriodModel>, List <PostionWithWarningInfo> > GetMovablePositons(string localID, List <ResultDetailModel> item, ResultModel resultModel)
        {
            //可用课位,最后取反返回不可用课位
            var dayPeriods   = new List <DayPeriodModel>();
            var notReachable = new List <PostionWithWarningInfo>();

            ICommonDataManager commonDataManager = CacheManager.Instance.UnityContainer.Resolve <ICommonDataManager>();
            var cl   = commonDataManager.GetCLCase(localID);
            var rule = commonDataManager.GetMixedRule(localID);
            var algo = commonDataManager.GetMixedAlgoRule(localID);

            //获取方案可用时间
            dayPeriods = cl?.Positions?.Where(p => p.IsSelected &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.AB &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.Noon &&
                                              p.Position != XYKernel.OS.Common.Enums.Position.PB)
                         ?.Select(d => d.DayPeriod)?.ToList() ?? new List <DayPeriodModel>();

            //TODO: 是否基于现有模型更新结果模型中的教师信息?
            item?.ForEach(it =>
            {
                var classHourInfo = cl.ClassHours.FirstOrDefault(c => c.ID == it.ClassHourId);
                string classID    = classHourInfo?.ClassID ?? string.Empty;
                string courseID   = classHourInfo?.CourseID ?? string.Empty;

                List <string> teachers = new List <string>();
                teachers = it?.Teachers == null ? new List <string>() : it.Teachers.ToList();

                //2.0 检查批量规则 - 仅查权重为高级的规则
                rule?.TeacherTimes?.Where(t => t.Weight == 1 && teachers.Contains(t.TeacherID))?.ToList()?.ForEach(x =>
                {
                    if (x.ForbidTimes != null)
                    {
                        dayPeriods = TimeOperation.TimeSlotDiff(dayPeriods, x.ForbidTimes);

                        x.ForbidTimes.ForEach(fb =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = fb, WaringMessage = $"教师在课位({TimeOperation.GetDateInfo(fb)})有禁止规则!"
                            });
                        });
                    }

                    if (x.MustTimes != null)
                    {
                        //必须时间暂不必查
                    }
                });

                rule?.CourseTimes?.Where(c => c.Weight == 1 && c.ClassID == classID)?.ToList()?.ForEach(x =>
                {
                    if (x.ForbidTimes != null)
                    {
                        dayPeriods = TimeOperation.TimeSlotDiff(dayPeriods, x.ForbidTimes);

                        x.ForbidTimes.ForEach(fb =>
                        {
                            notReachable.Add(new PostionWithWarningInfo()
                            {
                                DayPeriod = fb, WaringMessage = $"课程在课位({TimeOperation.GetDateInfo(fb)})有禁止规则!"
                            });
                        });
                    }

                    if (x.MustTimes != null)
                    {
                        int classHourNumber = cl.ClassHours.Where(ch => ch.ClassID == classID && ch.CourseID == courseID).Count();

                        if (x.MustTimes.Count >= classHourNumber)
                        {
                            dayPeriods.ForEach(dp =>
                            {
                                if (!x.MustTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                {
                                    notReachable.Add(new PostionWithWarningInfo()
                                    {
                                        DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                    });
                                }
                            });

                            dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, x.MustTimes);
                        }
                        else
                        {
                            List <DayPeriodModel> classHourTimes = resultModel.ResultClasses.Where(c => c.ClassID == classID)
                                                                   ?.SelectMany(c => c.ResultDetails)
                                                                   ?.Select(c => c.DayPeriod).ToList() ?? new List <DayPeriodModel>()
                            {
                            };

                            List <DayPeriodModel> classHoursInMust = TimeOperation.TimeSlotInterSect(x.MustTimes, classHourTimes);
                            if (classHoursInMust.Count < x.MustTimes.Count)
                            {
                                dayPeriods.ForEach(dp =>
                                {
                                    if (!x.MustTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                    {
                                        notReachable.Add(new PostionWithWarningInfo()
                                        {
                                            DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                        });
                                    }
                                });

                                dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, x.MustTimes);
                            }
                            else
                            {
                                //如果课位在必须时间内,则只能和本班课时互换以保障课时优先在必须时间内
                                List <DayPeriodModel> mustTempTimes = TimeOperation.TimeSlotInterSect(x.MustTimes, new List <DayPeriodModel>()
                                {
                                    it.DayPeriod
                                });
                                if (mustTempTimes.Count == 1)
                                {
                                    dayPeriods.ForEach(dp =>
                                    {
                                        if (!classHourTimes.Exists(mt => mt.Day == dp.Day && mt.PeriodName == dp.PeriodName))
                                        {
                                            notReachable.Add(new PostionWithWarningInfo()
                                            {
                                                DayPeriod = dp, WaringMessage = "课程应先满足排到必须规则指定课位内!"
                                            });
                                        }
                                    });

                                    dayPeriods = TimeOperation.TimeSlotInterSect(dayPeriods, classHourTimes);
                                }
                            }
                        }
                    }
                });

                rule?.AmPmClassHours?.Where(a => a.Weight == 1 && a.ClassID == classID && a.CourseID == courseID)?.ToList()?.ForEach(x =>
                {
                    int pmNumber     = 0;
                    int amNumber     = 0;
                    var timePosition = cl.Positions.Where(p => p.DayPeriod.Day == it.DayPeriod.Day && p.DayPeriod.PeriodName == it.DayPeriod.PeriodName).FirstOrDefault();
                    var classHours   = resultModel.ResultClasses?.Where(c => c.ClassID == classID)
                                       ?.SelectMany(c => c.ResultDetails)?.ToList();

                    classHours?.ForEach(c =>
                    {
                        var tPosition = cl.Positions.Where(p => p.DayPeriod.Day == c.DayPeriod.Day && p.DayPeriod.PeriodName == c.DayPeriod.PeriodName).FirstOrDefault();
                        if (tPosition != null)
                        {
                            if (tPosition.Position == XYKernel.OS.Common.Enums.Position.AM)
                            {
                                amNumber = amNumber + 1;
                            }

                            if (tPosition.Position == XYKernel.OS.Common.Enums.Position.PM)
                            {
                                pmNumber = pmNumber + 1;
                            }
                        }
                    });

                    //If current time slot is AM, And PMMax is full, Disable PM
                    if (timePosition.Position == XYKernel.OS.Common.Enums.Position.AM)
                    {
                        if (x.PmMax > 0 && pmNumber >= x.PmMax)
                        {
                            //Disable PM
                            var pmTimes = cl.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.PM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, pmTimes);

                            pmTimes.ForEach(pt =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = pt, WaringMessage = "违反班级课程的下午最大课时规则!"
                                });
                            });
                        }

                        if (x.AmMax > 0 && amNumber > x.AmMax)
                        {
                            //Disable AM
                            var amTimes = cl.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.AM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, amTimes);

                            amTimes.ForEach(pt =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = pt, WaringMessage = "违反班级课程的上午最大课时规则!"
                                });
                            });
                        }
                    }

                    //If current time slot is PM, And AMMax is full, Disable AM
                    if (timePosition.Position == XYKernel.OS.Common.Enums.Position.PM)
                    {
                        if (x.AmMax > 0 && amNumber >= x.AmMax)
                        {
                            //Disable AM
                            var amTimes = cl.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.AM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, amTimes);

                            amTimes.ForEach(at =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = at, WaringMessage = "违反班级课程的上午最大课时规则!"
                                });
                            });
                        }

                        if (x.PmMax > 0 && pmNumber > x.PmMax)
                        {
                            //Disable PM
                            var pmTimes = cl.Positions.Where(p => p.IsSelected && p.Position == XYKernel.OS.Common.Enums.Position.PM).Select(p => p.DayPeriod).ToList();
                            dayPeriods  = TimeOperation.TimeSlotDiff(dayPeriods, pmTimes);

                            pmTimes.ForEach(at =>
                            {
                                notReachable.Add(new PostionWithWarningInfo()
                                {
                                    DayPeriod = at, WaringMessage = "违反班级课程的下午最大课时规则!"
                                });
                            });
                        }
                    }
                });
            });

            return(Tuple.Create(dayPeriods, notReachable));
        }
Beispiel #37
0
        /// <summary>
        /// 在数据库中搜索影片
        /// </summary>
        public async void Query()
        {
            if (Search == "")
            {
                return;
            }
            //对输入的内容进行格式化
            string FormatSearch = Search.Replace(" ", "").Replace("%", "").Replace("'", "");

            FormatSearch = FormatSearch.ToUpper();

            if (string.IsNullOrEmpty(FormatSearch))
            {
                return;
            }

            string fanhao = "";

            if (CurrentVedioType == VedioType.欧美)
            {
                fanhao = Identify.GetEuFanhao(FormatSearch);
            }
            else
            {
                fanhao = Identify.GetFanhao(FormatSearch);
            }

            string searchContent = "";

            if (fanhao == "")
            {
                searchContent = FormatSearch;
            }
            else
            {
                searchContent = fanhao;
            }



            TextType = searchContent;//当前显示内容
            cdb      = new DataBase();
            List <Movie> models = null;

            if (!cdb.IsTableExist("movie"))
            {
                cdb.CloseDB(); return;
            }

            try {
                if (Properties.Settings.Default.AllSearchType == "识别码")
                {
                    models = await cdb.SelectMoviesById(searchContent);
                }
                else if (Properties.Settings.Default.AllSearchType == "名称")
                {
                    models = cdb.SelectMoviesBySql($"SELECT * FROM movie where title like '%{searchContent}%'");
                }
                else if (Properties.Settings.Default.AllSearchType == "演员")
                {
                    models = cdb.SelectMoviesBySql($"SELECT * FROM movie where actor like '%{searchContent}%'");
                }
            }
            finally { cdb.CloseDB(); }


            MovieList = new ObservableCollection <Movie>();
            models?.ForEach(arg => { MovieList.Add(arg); });
            Sort();
        }
 /// <summary>
 /// Deletes the items by keys from the dictionary.
 /// </summary>
 /// <param name="keys">The keys of the items.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to cancel the work.</param>
 /// <returns></returns>
 public Task DeleteAsync(List <TKey> keys, CancellationToken cancellationToken)
 {
     Validate();
     return(Task.Run(() => keys?.ForEach(x => Items.Remove(x)), cancellationToken));
 }
 public void ShiftSubtitles(int shift)
 {
     Subtitles?.ForEach(s => s.Shift(shift));
 }
Beispiel #40
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     _plugins?.ForEach(plugin => plugin.Start());
     return(Task.CompletedTask);
 }
Beispiel #41
0
 public void ForeachType(Action <TypeDeclaration> @do)
 {
     nested?.ForEach(v => v.ForeachType(@do));
     @do(this);
 }
Beispiel #42
0
 public virtual Task ToolDeselected()
 {
     _subscriptions?.ForEach(x => x.Dispose());
     Invalidate();
     return(Task.CompletedTask);
 }
Beispiel #43
0
 internal static void GlobalCleanUp()
 {
     ms_finalizers?.ForEach(a => a());
     ms_finalizers?.Clear();
 }
        //获取where条件的sql语句
        private string GetConitionsql(List <ConditionModel> conditions)
        {
            //使用了And的条件
            var andlist = new List <string>();

            //使用了Or条件
            var orList = new List <string>();

            conditions?.ForEach(p =>
            {
                var pNames = "";
                //默认设置条件为=符号
                var where = $" {p.Key}=@{p.Key} ";
                switch (p.Oper)
                {
                case Operational.NotEqual:
                    where = $" {p.Key}<>@{p.Key} ";
                    break;

                case Operational.Greater:
                    where = $" {p.Key}>@{p.Key} ";
                    break;

                case Operational.Less:
                    where = $" {p.Key}<@{p.Key} ";
                    break;

                case Operational.In:
                    pNames = GetParams(p.Key, p.Value);
                    where  = $" {p.Key} In ({pNames}) ";
                    break;

                case Operational.NotIn:
                    pNames = GetParams(p.Key, p.Value);
                    where  = $" {p.Key} Not In ({pNames}) ";
                    break;

                case Operational.Like:
                    where = $" {p.Key} Like '%' || @{p.Key} || '%' ";
                    break;

                case Operational.LeftLike:
                    where = $" {p.Key} Like '%' || @{p.Key} ";
                    break;

                case Operational.RightLike:
                    where = $" {p.Key} Like  @{p.Key} || '%' ";
                    break;

                case Operational.Equal:
                default:
                    break;
                }

                if (p.Where == WhereType.And)
                {
                    andlist.Add(where);
                }
                else if (p.Where == WhereType.Or)
                {
                    orList.Add(where);
                }
            });

            var andWhereSql = andlist.ToWhereString(" AND ", "");
            var orWhereSql  = orList.ToWhereString(" OR ", "");

            if (andlist.Count > 0 && orList.Count > 0)
            {//如果包括了And条件与Or条件
                return($" {andWhereSql} OR {orWhereSql} ");
            }
            else if (andlist.Count > 0)
            {//只有And条件
                return(andWhereSql);
            }
            else
            {//只有Or条件
                return(orWhereSql);
            }
        }
Beispiel #45
0
 public void StartSendingEvents()
 {
     _eventSubscriptions?.ForEach(s => s.Dispose());
     _eventSubscriptions = new List <IDisposable>();
     _imageQueueEvents.ImageQueueChanges.Subscribe(e => SendEvent("QueueChanged", null));
 }
Beispiel #46
0
 public void SetOptions(NeuralTyresOptions options)
 {
     _options = options;
     _list?.ForEach(x => x.SetOptions(options));
 }
Beispiel #47
0
 private void Recalculate()
 {
     _recalculationActions?.ForEach(action => action());
 }
Beispiel #48
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="bodyText">邮件内容</param>
        /// <param name="bodyHtml">邮件内容(html格式)</param>
        /// <param name="name">发件人名称</param>
        /// <param name="host">发件人地址</param>
        /// <param name="username">发件人账号</param>
        /// <param name="password">发件人密码</param>
        /// <param name="smtp">发件人smtp服务</param>
        /// <param name="smtpport">发件人smtp服务端口</param>
        /// <param name="toemail">收件人地址</param>
        public static bool SendEmail(string subject, string bodyText, string bodyHtml, string name, string host, string username, string password, string smtp, int smtpport, string toemail, bool useSSL, List <MimePart> accessoryList = null)
        {
            try
            {
                var message = new MimeMessage();
                //发件人配置
                message.From.Add(new MailboxAddress(name, host));
                //收件人配置
                message.To.Add(new MailboxAddress(toemail));
                //邮件标题
                message.Subject = subject;
                //邮件内容
                //message.Body = new TextPart("plain") { Text = body };
                var alternative = new Multipart("alternative");
                if (!string.IsNullOrWhiteSpace(bodyText))
                {
                    alternative.Add(new TextPart("plain")
                    {
                        Text = bodyText
                    });
                }

                if (!string.IsNullOrWhiteSpace(bodyHtml))
                {
                    alternative.Add(new TextPart("html")
                    {
                        Text = bodyHtml
                    });
                }
                var multipart = new Multipart("mixed");
                multipart.Add(alternative);
                if (accessoryList != null)
                {
                    accessoryList?.ForEach(f =>
                    {
                        multipart.Add(f);
                    });
                }
                message.Body = multipart;
                //HTML邮件内容
                //var bodyBuilder = new BodyBuilder();
                //bodyBuilder.HtmlBody = @"<b>This is bold and this is <i>italic</i></b>";
                //message.Body = bodyBuilder.ToMessageBody();

                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect(smtp, smtpport, useSSL);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(username, password);

                    client.Send(message);
                    client.Disconnect(true);
                    Console.WriteLine($"给{toemail}发送邮件成功");
                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                return(false);
            }
        }
Beispiel #49
0
 private void CleanUp()
 {
     m_finalizers?.ForEach(a => a());
 }
Beispiel #50
0
        static void Main(string[] args)
        {
            object obj = new List <string>();

            {
                List <string> list = obj as List <string>;
                list?.ForEach((e) => Console.WriteLine(e));
            }

            {
                if (obj is List <string> list)
                // if (obj is List<string>)
                {
                    list.ForEach((e) => Console.WriteLine(e));
                }
            }

            object[] objList = new object[] { 100, null, DateTime.Now, new ArrayList() };

            foreach (object item in objList)
            {
                if (item is 100) // 상수 패턴
                {
                    Console.WriteLine(item);
                }
                else if (item is null) // 상수 패턴
                {
                    Console.WriteLine("null");
                }
                else if (item is DateTime dt) // 타입 패턴(값 형식 가능) - 필요없다면 dt 변수 생략 가능
                {
                    Console.WriteLine(dt);
                }
                else if (item is ArrayList arr) // 타입 패턴(참조 형식 가능 - 필요없다면 arr 변수 생략 가능
                {
                    Console.WriteLine(arr.Count);
                }
                else if (item is var elem) // 타입 패턴과는 달리 변수명 생략 불가
                {
                    Console.WriteLine(elem);
                }
                else if (item is var _) // 단지 변수가 필요없는 경우 밑줄로 대체 가능
                {
                }

                /*
                 * object elem = item;
                 * if (true)
                 * {
                 *  Console.WriteLine(elem);
                 * }
                 */
            }


            foreach (object item in objList)
            {
                switch (item)
                {
                case 100:       //상수 패턴
                    break;

                case null:      //상수 패턴
                    break;

                case DateTime dt:       //타입 패턴(값 형식) - 필요없다면 dt 변수명을 밑줄로 생략 가능
                    break;

                case ArrayList arr:     //타입 패턴(참조 형식) - 필요없다면 arr 변수명을 밑줄로 생략 가능
                    break;

                case var elem:      //var 패턴 (이렇게 생략하면 default와 동일)
                    break;
                }
            }

            int j = 100;

            if (j > 300)
            {
            }
            else
            {
            }

            switch (j)
            {
            case int i when i > 300:        //int 타입이고 그 값이 300보다 큰 경우
                break;

            default:
                break;
            }

            //기존에는 아래와 같은 조건은 if문을 통해서만 처리할 수 있었지만
            // 이제는 switch/case로도 가능
            string text = "......";

            switch (text)
            {
            case var item when(ContainsAt(item, "http://www.naver.com")):
                Console.WriteLine("In Naver");

                break;

            case var item when(ContainsAt(item, "http://www.daum.net")):
                Console.WriteLine("In Daum");

                break;

            default:
                Console.WriteLine("None");
                break;
            }
 public void Dispose()
 {
     _serviceProviders?.ForEach(sp => sp?.Dispose());
 }
 public void Stop()
 {
     AutoFetchHandler.Active = false;
     _detectors?.ForEach(w => w.Stop());
 }
Beispiel #53
0
 /// <summary>
 /// Performs post-processing tasks (if any) after all DrawableHitObjects are loaded into this Playfield.
 /// </summary>
 public virtual void PostProcess() => nestedPlayfields?.ForEach(p => p.PostProcess());
Beispiel #54
0
 void _MainForm_Load(object sender, EventArgs e)
 {
     _MainForm.Location    = _ActiveLayout.Location;
     _MainForm.WindowState = _ActiveLayout.WindowState;
     _FinishLayout?.ForEach(fa => fa());
 }
 public override void Execute()
 {
     DeleteUndelete(true);
     ContainedItemsCommand?.ForEach(cmd => cmd.Execute());
 }
Beispiel #56
0
 void SetPickupsPosition(Vector3 pos)
 {
     pickupList?.ForEach(item => item.transform.localPosition += pos);
 }
Beispiel #57
0
 /// <inheritdoc />
 public void Notify()
 {
     _observers?.ForEach(o => o.Update(this));
 }
Beispiel #58
0
        public ActionResult PayRecords(string act = "", int aId = 0, int pageIndex = 0, int pageSize = 10, int recordType = 0, string storePhone = "",
            string payUserPhone = "",
            string transaction_id = "",
            string out_trade_no = "",
            int parentAgentId = 0)
        {
            pageIndex -= 1;
            if (pageIndex < 0)
                pageIndex = 0;

            if (string.IsNullOrEmpty(act))
            {

                string fieldSql = $@" 

p.transaction_id,
p.out_trade_no,
p.time_end,
p.total_fee,

c.TuserId,
c.orderno,
c.ShowNote,
c.id as CityMordersId,

s.storename,
s.phone as StoreUserPhone,

go.ordertype,
go.goodsid as GoodsOrderGoodsId,

fu.id as payUserId,
fu.NickName as payusername,
fu.telephone as PayUserPhone,
su.NickName as storeUserName,
su.Id as storeUserId,
g.name as goodsname,
g.id as goodsid,
g.img as goodsimg
";
                if (parentAgentId > 0)
                {
                    fieldSql += ",aa.fuserid";
                }

                string fromSql = $@"
from payresult p LEFT  JOIN citymorders c on p.out_trade_no = c.orderno
LEFT JOIN c_userinfo fu on c.FuserId = fu.Id
LEFT JOIN pinstore s on c.TuserId = s.id
LEFT JOIN c_userinfo su on s.userid = su.id
LEFT JOIN pingoodsorder go on c.id=go.payno
LEFT JOIN pingoods g on go.goodsid=g.id

";
                if (parentAgentId > 0)
                {
                    fromSql += " LEFT JOIN pinagent aa on fu.id=aa.userid ";
                }
                List<MySqlParameter> parameters = new List<MySqlParameter>();
                string whereSql = $" c.ActionType ='{(int)ArticleTypeEnum.PinOrderPay}' and go.aid={aId} ";
                if (recordType == 1)
                    whereSql += " and go.ordertype=1 ";
                else if (recordType == 2)
                    whereSql += " and go.ordertype=0 ";
                if (!string.IsNullOrEmpty(payUserPhone))
                {
                    whereSql += $" and fu.telephone=@PayUserPhone";
                    parameters.Add(new MySqlParameter("@PayUserPhone", payUserPhone));
                }
                if (!string.IsNullOrEmpty(storePhone))
                {
                    whereSql += " and s.phone=@StoreUserPhone";
                    parameters.Add(new MySqlParameter("@StoreUserPhone", storePhone));
                }
                if (!string.IsNullOrEmpty(transaction_id))
                {
                    whereSql += " and p.transaction_id=@transaction_id";
                    parameters.Add(new MySqlParameter("@transaction_id", transaction_id));
                }
                if (!string.IsNullOrEmpty(out_trade_no))
                {
                    whereSql += " and p.out_trade_no=@out_trade_no";
                    parameters.Add(new MySqlParameter("@out_trade_no", out_trade_no));
                }
                if (parentAgentId > 0)
                {
                    whereSql += " and go.ordertype=1  and  aa.fuserid=" + parentAgentId;//and aa.state=1
                }

                string orderSql = " order by p.id desc ";
                string pagerSql = $" limit {pageSize * pageIndex},{pageSize} ";

                string querySql = $" select distinct {fieldSql} {fromSql} where {whereSql} {orderSql} {pagerSql}";
                string countSql = $" select distinct count(0) {fromSql} where {whereSql}";



                List<PayRecordModel> list = DataHelper.ConvertDataTableToList<PayRecordModel>(SqlMySql.ExecuteDataSet(Utility.dbEnum.MINIAPP.ToString(), System.Data.CommandType.Text, querySql, parameters.ToArray()).Tables[0]);

                string goodsIds = string.Join(",",list?.Select(s=>s.GoodsId).Distinct());
                List<PinGoods> pinGoodsList = PinGoodsBLL.SingleModel.GetListByIds(goodsIds);
                list?.ForEach(p =>
                {
                    p.OrderGoods = pinGoodsList?.FirstOrDefault(f=>f.id ==p.GoodsId);
                    if (p.OrderType == 1)
                    {
                        PinAgent agentInfo = PinAgentBLL.SingleModel.GetModelByUserId(p.PayUserId);
                        if (agentInfo != null && agentInfo.fuserId > 0)
                        {
                            p.ParentAgentUser = C_UserInfoBLL.SingleModel.GetModel(agentInfo.fuserId);
                            p.ParentAgentStore = PinStoreBLL.SingleModel.GetModelByAid_Id(agentInfo.aId, agentInfo.fuserId);
                        }

                    }

                });
                ViewModel<PayRecordModel> vm = new ViewModel<PayRecordModel>();
                vm.DataList = list;
                vm.aId = aId;
                vm.PageSize = pageSize;
                vm.PageIndex = pageIndex;
                vm.TotalCount = PayResultBLL.SingleModel.GetCountBySql(countSql, parameters.ToArray());
                return View(vm);
            }
            return View();
        }
Beispiel #59
0
 private void OnDisable()
 {
     textObjects?.ForEach(el => el.SetText(String.Empty));
 }
 /// <summary>
 /// Adds the items to the dictionary.
 /// </summary>
 /// <param name="items">The list of items to be added.</param>
 /// <param name="cancellationToken">A cancellation token that can be used to cancel the work.</param>
 /// <returns></returns>
 public Task AddAsync(List <TItem> items, CancellationToken cancellationToken)
 {
     Validate();
     return(Task.Run(() => items?.ForEach(x => Items.Add(KeySelector(x), x)), cancellationToken));
 }