C# (CSharp) System. Action Code Examples

C# (CSharp) System.Action - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для System.Action, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
        public void SortingTest()
        {
            Action<int[]>[] actions = new Action<int[]>[]
            {
                BubbleSort.Sort,
                data => BucketSort.Sort(data, SortingTests.MaxValue),
                data => CountingSort.Sort(data, SortingTests.MaxValue),
                HeapSort.Sort,
                InsertionSort.Sort,
                MergeSort.Sort,
                QuickSort.Sort,
                data => RadixSort.Sort(data, SortingTests.MaxValue),
            };

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    int[] data = ArrayUtilities.CreateRandomArray(j, 0, SortingTests.MaxValue);
                    int[][] results = new int[actions.Length][];

                    for (int k = 0; k < actions.Length; k++)
                    {
                        results[k] = new int[data.Length];
                        Array.Copy(data, results[k], data.Length);

                        actions[k](results[k]);
                        Assert.IsTrue(ArrayUtilities.AreEqual(results[k], results[0]));
                    }
                }
            }
        }
Пример #2
0
        public void SortedMergeTest()
        {
            Action<int[], int[]>[] actions = new Action<int[], int[]>[]
            {
                SortedMerge.BruteForce,
                SortedMerge.SinglePass
            };

            for(int i = 0; i < 10; i++)
            {
                int[] A = ArrayUtilities.CreateRandomArray(40, 0, 20);
                int[] B = ArrayUtilities.CreateRandomArray(20, 0, 20);

                Array.Sort(A, 0, A.Length / 2);
                Array.Sort(B);

                int[][] results = new int[actions.Length][];

                for(int j = 0; j < actions.Length; j++)
                {
                    results[j] = new int[A.Length];
                    Array.Copy(A, results[j], A.Length);
                    int[] copyB = new int[B.Length];
                    Array.Copy(B, copyB, B.Length);

                    actions[j](results[j], copyB);
                    Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[j]));
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Creates a new menu form.
        /// </summary>
        /// <param name="title">Window title.</param>
        /// <param name="itemNames">Item names.</param>
        /// <param name="actions">Actions.</param>
        public MenuForm(string title, string[] itemNames, Action[] actions)
        {
            Title = title;
            SelectedIndex = -1;

            if (itemNames == null || actions == null)
                return;
            if (itemNames.Length != actions.Length)
                return;

            var stackLayout = new StackLayout {Orientation = Orientation.Vertical, HorizontalContentAlignment = HorizontalAlignment.Stretch };

            for (int i = 0; i < itemNames.Length; i++)
            {
                var idx = i;

                var button = new Button { Text = itemNames[idx], Size = new Size(240, 60) }; 
                button.Click += (s, e) =>
                {
                    actions[idx]();
                    SelectedIndex = idx;
                    this.Close();
                };

                stackLayout.Items.Add(new StackLayoutItem(button, true));
            }

            Content = stackLayout;
            Size = new Size(-1, -1);
        }
Пример #4
0
        public void IncrementIntegerTest()
        {
            Action<List<int>>[] actions = new Action<List<int>>[]
            {
                IncrementInteger.Convert,
                IncrementInteger.SinglePass
            };

            int digits = 0;
            for (int i = 0; i <= 1000; i++)
            {
                if (i % 10 == 0)
                    digits++;

                for(int j = 0; j < actions.Length; j++)
                {
                    List<int> list = new List<int>();
                    for (int k = 0; k < digits; k++)
                        list.Insert(0, 0);

                    IncrementInteger.ToList(i, list);
                    actions[j](list);
                    Assert.AreEqual(IncrementInteger.ToInt(list), i + 1);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Enumerates the segments in a path and calls a corresponding delegate verifier on each segment.
        /// Do not overuse this method: most test cases don't need to over-baseline what the expected segments are.
        /// </summary>
        public static void VerifyPath(ODataPath path, Action<ODataPathSegment>[] segmentVerifiers)
        {
            path.Count().Should().Be(segmentVerifiers.Count());

            var i = 0;
            foreach (var segment in path)
            {
                segmentVerifiers[i++](segment);
            }
        }
Пример #6
0
		public static void ProcessMovieImport(string fn, Action<string> conversionErrorCallback, Action<string> messageCallback)
		{
			var d = PathManager.MakeAbsolutePath(Global.Config.PathEntries.MoviesPathFragment, null);
			string errorMsg;
			string warningMsg;
			var m = ImportFile(fn, out errorMsg, out warningMsg);

			if (!string.IsNullOrWhiteSpace(errorMsg))
			{
				conversionErrorCallback(errorMsg);
			}

			if (!string.IsNullOrWhiteSpace(warningMsg))
			{
				messageCallback(warningMsg);

			}
			else
			{
				messageCallback(Path.GetFileName(fn) + " imported as " + m.Filename);
			}

			if (!Directory.Exists(d))
			{
				Directory.CreateDirectory(d);
			}
		}
Пример #7
0
        /// <summary>
        /// Sets the delegate to use when configuring the application's <see cref="GlobalConfiguration.Configuration"/>.
        /// </summary>
        /// <param name="configurationDelegate">The configuration delegate.</param>
        /// <returns>Current <see cref="WebApiManagerBuilder"/> instance.</returns>
        /// <remarks></remarks>
        public ApplicationConfigurationBuilder ConfigureForIIS(Action<HttpConfiguration> configurationDelegate)
        {
            _AspNetHttpConfigurationDelegate = configurationDelegate;
            Setup();

            return Builder;
        }
Пример #8
0
        public static void Invoke(this Control uiElement, Action updater, bool forceSynchronous = true)
        {
            if (uiElement == null)
            {
                throw new ArgumentNullException("uiElement");
            }

            if (uiElement.InvokeRequired)
            {
                if (forceSynchronous)
                {
                    try
                    {
                        uiElement.Invoke((Action)delegate { Invoke(uiElement, updater, forceSynchronous); });
                    }
                    catch (Exception e) { }
                }
                else
                {
                    uiElement.BeginInvoke((Action)delegate { Invoke(uiElement, updater, forceSynchronous); });
                }
            }
            else
            {
                if (!uiElement.IsDisposed)
                {
                    updater();
                }
            }
        }
Пример #9
0
        public UpdateHandler(DataTrade trade, DataFeed feed, Action<SymbolInfo[], AccountInfo, Quote> updateCallback, Processor processor)
        {
            if (trade == null)
                throw new ArgumentNullException(nameof(trade));

            if (feed == null)
                throw new ArgumentNullException(nameof(feed));

            if (updateCallback == null)
                throw new ArgumentNullException(nameof(updateCallback));

            if (processor == null)
                throw new ArgumentNullException(nameof(processor));

            this.updateCallback = updateCallback;
            this.processor = processor;

            this.SyncRoot = new object();

            feed.SymbolInfo += this.OnSymbolInfo;
            feed.Tick += this.OnTick;

            trade.AccountInfo += this.OnAccountInfo;
            trade.BalanceOperation += this.OnBalanceOperation;
            trade.ExecutionReport += this.OnExecutionReport;
            trade.PositionReport += this.OnPositionReport;
        }
        //public async Task<string> WebMethod2()
        public void WebMethod2(Action<string> yield)
        {
            // ThreadLocal SynchronizationContext aware ConnectionPool?
            var n = new PerformanceResourceTimingData2ApplicationPerformance();

            var rid = n.Insert(
                new PerformanceResourceTimingData2ApplicationPerformanceRow
            {
                connectStart = 5,
                connectEnd = 13,

                // conversion done in AddParameter
                // .stack rewriter needs to store struct. can we create new byref struct parameters?
                //EventTime = DateTime.Now.AddDays(-0),

                // conversion done in Insert?
                z = new XElement("goo", "foo")
            }
            );

            // { LastInsertRowId = 2 }
            Console.WriteLine("after insert " + new { rid });


            var c = new PerformanceResourceTimingData2ApplicationPerformance().Count();

            Console.WriteLine(new { c, rid });

            // I/System.Console( 7320): {{ c = 18, rid = 18 }}
            //return new { c, rid }.ToString();
            yield(
                "TestAndroidInsert " + new { c, rid }.ToString()
                );

        }
Пример #11
0
 public static void CreateTchatCommand(string name, string help, Action<string[], Bot> action)
 {
     string commandName = name.ToLowerInvariant();
     if (m_commands.Count(entry => entry.CommandName == commandName) == 1)
         throw new InvalidOperationException(String.Format("Command {0} already exists.", name));
     m_commands.Add(new TchatCommand(name, help, action));
 }
        /// <summary>
        /// Adds a saved search to your twitter account
        /// </summary>
        /// <param name="query">Search query to add</param>
        /// <param name="callback">Async Callback used in Silverlight queries</param>
        /// <returns>SavedSearch object</returns>
        public static SavedSearch CreateSavedSearch(this TwitterContext ctx, string query, Action<TwitterAsyncResponse<SavedSearch>> callback)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("query is required.", "query");
            }

            var savedSearchUrl = ctx.BaseUrl + "saved_searches/create.json";

            var reqProc = new SavedSearchRequestProcessor<SavedSearch>();

            ITwitterExecute exec = ctx.TwitterExecutor;
            exec.AsyncCallback = callback;
            var resultsJson =
                exec.PostToTwitter(
                    savedSearchUrl,
                    new Dictionary<string, string>
                    {
                        { "query", query }
                    },
                    response => reqProc.ProcessActionResult(response, SavedSearchAction.Create));

            SavedSearch result = reqProc.ProcessActionResult(resultsJson, SavedSearchAction.Create);
            return result;
        }
Пример #13
0
        public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            if (symbol.TypeKind != TypeKind.Enum)
            {
                return;
            }

            var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation);
            if (flagsAttribute == null)
            {
                return;
            }

            var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray();

            bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute);
            if (hasFlagsAttribute)
            {
                CheckFlags(symbol, zeroValuedFields, addDiagnostic);
            }
            else
            {
                CheckNonFlags(symbol, zeroValuedFields, addDiagnostic);
            }
        }
Пример #14
0
 public static SplitterBuilder VnrSplitter(this HtmlHelper helper, SplitterBuilderInfo builderInfo)
 {
     var pane = new Action<SplitterPaneFactory>(p =>
     {
         foreach (var item in builderInfo.Panes)
         {
             if (!string.IsNullOrWhiteSpace(item.Value.Content))
             {
                 p.Add()
                     .Content(item.Value.Content)
                     .Collapsible(item.Value.Collapsible)
                     .Scrollable(item.Value.Scrollable)
                     .Size(item.Value.Size)
                     .Resizable(item.Value.Resizable);
             }
             else if (!string.IsNullOrEmpty(item.Value.Controller) || !string.IsNullOrEmpty(item.Value.ActionName))
             {
                 p.Add()
                     .LoadContentFrom(item.Value.ActionName, item.Value.Controller)
                     .Collapsible(item.Value.Collapsible)
                     .Scrollable(item.Value.Scrollable)
                     .Size(item.Value.Size)
                     .Resizable(item.Value.Resizable);
             }
         }
     });
     var splitterBuilder = helper.Kendo().Splitter()
         .Orientation(builderInfo.Orientation)
         .Name(builderInfo.Name)
         .HtmlAttributes(new {style="height:"+builderInfo.Height+"px;"})
         .Panes(pane);
     return splitterBuilder;
 }
Пример #15
0
 public EventSignal<IResponse> PostAsync(string url, Action<IRequest> prepareRequest, Dictionary<string, string> postData)
 {
     var returnSignal = new EventSignal<IResponse>();
     var signal = HttpHelper.PostAsync(url, request => prepareRequest(new HttpWebRequestWrapper(request)), postData);
     signal.Finished += (sender, e) => returnSignal.OnFinish(new HttpWebResponseWrapper(e.Result.Result) { Exception = e.Result.Exception, IsFaulted = e.Result.IsFaulted });
     return returnSignal;
 }
 /// <summary>
 /// Repeats the specified <see cref="Action"/> the number of times.
 /// </summary>
 /// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
 /// <param name="action">The <see cref="Action"/> to repeat.</param>
 public static void Times(this int input, Action action)
 {
     while (input-- > 0)
     {
         action();
     }
 }
        private void Configure(AzureServiceBusOwinServiceConfiguration config, Action<IAppBuilder> startup)
        {
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            var options = new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new AzureServiceBusOwinServerFactory(config);
            var services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options)
            {
                ServerFactory = new ServerFactoryAdapter(testServerFactory),
                Startup = startup
            };
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }
Пример #18
0
        /// <summary>
        ///     Add a new timer and starts measuring time.
        /// </summary>
        /// <param name="duration">When the action must be started.</param>
        /// <param name="callbackAction">Action to invoke on time.</param>
        /// <param name="removeAfterCallback">Remove timer from list after execution of callback.</param>
        /// <returns>Timer instance.</returns>
        public Timer AddTimer(double duration, Action callbackAction, bool removeAfterCallback = false)
        {
            var timer = new Timer(duration, callbackAction, removeAfterCallback) {Running = true};
            timers.Add(timer);

            return timer;
        }
Пример #19
0
 /// <inheritdoc/>
 public override void Init(NLite.Mini.Activation.IActivator activator, IKernel kernel, IComponentInfo info, Action<IComponentInfo, object> onDestroying, Action<IComponentContext> onFetch)
 {
     Guard.NotNull(activator, "activator");
     Guard.NotNull(kernel, "kernel");
     Guard.NotNull(info, "info");
     Real.Init(new ProxyActivator(activator), kernel, info, onDestroying,OnFetch);
 }
Пример #20
0
        public MyCubeGridSystems(MyCubeGrid grid)
        {
            m_cubeGrid = grid;

            m_terminalSystem_GroupAdded = TerminalSystem_GroupAdded;
            m_terminalSystem_GroupRemoved = TerminalSystem_GroupRemoved;

            GyroSystem = new MyGridGyroSystem(m_cubeGrid);
            WeaponSystem = new MyGridWeaponSystem();
            ReflectorLightSystem = new MyGridReflectorLightSystem(m_cubeGrid);
            if (MyFakes.ENABLE_WHEEL_CONTROLS_IN_COCKPIT)
            {
                WheelSystem = new MyGridWheelSystem(m_cubeGrid);
            }
            ConveyorSystem = new MyGridConveyorSystem(m_cubeGrid);
            LandingSystem = new MyGridLandingSystem();
            ControlSystem = new MyGroupControlSystem();
            CameraSystem = new MyGridCameraSystem(m_cubeGrid);

            if (MySession.Static.Settings.EnableOxygen)
            {
                GasSystem = new MyGridGasSystem(m_cubeGrid);
            }
            if (MyPerGameSettings.EnableJumpDrive)
            {
                JumpSystem = new MyGridJumpDriveSystem(m_cubeGrid);
            }
            if (MyPerGameSettings.EnableShipSoundSystem && (MyFakes.ENABLE_NEW_SMALL_SHIP_SOUNDS || MyFakes.ENABLE_NEW_LARGE_SHIP_SOUNDS) && MySandboxGame.IsDedicated == false)
            {
                ShipSoundComponent = new MyShipSoundComponent();
            }

            m_blocksRegistered = true;
        }
Пример #21
0
 /// <summary>
 /// Creates a new command.
 /// </summary>
 /// <param name="execute">The execution logic.</param>
 /// <param name="canExecute">The execution status logic.</param>
 public RelayCommand(Action<object> execute, Func<bool> canExecute)
 {
     if (execute == null)
         throw new ArgumentNullException("execute");
     _execute = execute;
     _canExecute = canExecute;
 }
Пример #22
0
 public static String CaptureOutput(Action Action, bool Capture = true)
 {
     if (Capture)
     {
         var OldOut = Console.Out;
         var StringWriter = new StringWriter();
         try
         {
             Console.SetOut(StringWriter);
             Action();
         }
         finally
         {
             Console.SetOut(OldOut);
         }
         try
         {
             return StringWriter.ToString();
         }
         catch
         {
             return "";
         }
     }
     else
     {
         Action();
         return "";
     }
 }
        public void GetData(Action<DataItem, Exception> callback)
        {
            // Use this to create design time data

            var item = new DataItem("Welcome to MVVM Light [design]");
            callback(item, null);
        }
Пример #24
0
        public void BackupDataBase(string destinationPath, Action<int> percentCompleteCallback, Action completeCallback)
        {
            var server = GetDbServer();

            var backup = new Backup();
            backup.Action = BackupActionType.Database;
            backup.Database = this.DatabaseName;
            backup.Devices.Add(new BackupDeviceItem(GetFileName(destinationPath, this.DatabaseName, ".bak"), DeviceType.File));
            backup.Initialize = true;
            backup.Checksum = true;
            backup.ContinueAfterError = true;
            backup.Incremental = false;
            backup.PercentCompleteNotification = 1;
            backup.LogTruncation = BackupTruncateLogType.Truncate;

            backup.Complete += (s, e) =>
            {
                if (completeCallback != null)
                {
                    completeCallback();
                }
            };

            backup.PercentComplete += (s, e) =>
            {
                if (percentCompleteCallback != null)
                {
                    percentCompleteCallback(e.Percent);
                }
            };

            backup.SqlBackupAsync(server);
        }
Пример #25
0
	public SmugglerApi(SmugglerOptions smugglerOptions, IAsyncDatabaseCommands commands, Action<string> output)
		: base(smugglerOptions)
	{
		this.commands = commands;
		this.output = output;
		batch = new List<RavenJObject>();
	}
Пример #26
0
        public override void Connect(string host, int port, Action callback)
        {
            if (state != Socket.SocketState.Invalid)
                throw new InvalidOperationException ("Socket already in use");

            int error;
            var fd = manos_socket_connect (host, port, out error);

            if (fd < 0)
                throw new Exception (String.Format ("An error occurred while trying to connect to {0}:{1} errno: {2}", host, port, error));

            stream = new PlainSocketStream (this, new IntPtr (fd));

            var connectWatcher = new IOWatcher (new IntPtr (fd), EventTypes.Write, Context.Loop, (watcher, revents) => {
                watcher.Stop ();
                watcher.Dispose ();

                this.address = host;
                this.port = port;

                this.state = Socket.SocketState.Open;

                callback ();
            });
            connectWatcher.Start ();
        }
        public AppUpdateControl(IEnumerable<IAppVersion> appVersions, Action<IAppVersion> updateAction)
        {
            this.NewestVersion = appVersions.First();
            InitializeComponent();

            this.AppIconImage.ImageFailed += (sender, e) => { this.AppIconImage.Source = new BitmapImage(new Uri("/Assets/windows_phone.png", UriKind.RelativeOrAbsolute)); };
            this.AppIconImage.Source = new BitmapImage(new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".png"));

            this.ReleaseNotesBrowser.Opacity = 0;
            this.ReleaseNotesBrowser.Navigated += (sender, e) => { (this.ReleaseNotesBrowser.Resources["fadeIn"] as Storyboard).Begin(); };
            this.ReleaseNotesBrowser.NavigateToString(WebBrowserHelper.WrapContent(NewestVersion.Notes));
            this.ReleaseNotesBrowser.Navigating += (sender, e) =>
            {
                e.Cancel = true;
                WebBrowserTask browserTask = new WebBrowserTask();
                browserTask.Uri = e.Uri;
                browserTask.Show();
            };
            this.InstallAETX.Click += (sender, e) =>
            {
                WebBrowserTask webBrowserTask = new WebBrowserTask();
                webBrowserTask.Uri = new Uri(HockeyClient.Current.AsInternal().ApiBaseVersion2 + "apps/" + NewestVersion.PublicIdentifier + ".aetx", UriKind.Absolute);
                webBrowserTask.Show();
            };
            this.InstallOverApi.Click += (sender, e) => {
                this.Overlay.Visibility = Visibility.Visible;
                updateAction.Invoke(NewestVersion); 
            };
            
        }
 //This method improves upon the naive method (stringBuffer) as ENCODING.GetString
 //allocates a new character array with every invocation, and this method bypasses
 //this by reusing the same char array.  Surprisingly in tests, this method held
 //no improvement.
 static void filestream2(string filePath, Action<string> callback)
 {
     byte[] buffer = new byte[BUFFER_SIZE];
     byte[] charBuffer = new byte[MAX_TOKEN_SIZE];
     char[] encoderBuffer = new char[ENCODING.GetMaxCharCount(MAX_TOKEN_SIZE)];
     int charIndex = 0;
     int bufferSize, encodedChars;
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         do
         {
             bufferSize = stream.Read(buffer, 0, BUFFER_SIZE);
             for (int i = 0; i < bufferSize; i++)
             {
                 if (scannerNoMatch(buffer[i]))
                 {
                     charBuffer[charIndex++] = buffer[i];
                 }
                 else
                 {
                     encodedChars = ENCODING.GetChars(charBuffer, 0, charIndex, encoderBuffer, 0);
                     callback(new string(encoderBuffer, 0, encodedChars));
                     charIndex = 0;
                 }
             }
         } while (bufferSize != 0);
     }
 }
 //Base method - most simple implementation
 static void filestream(string filePath, Action<string> callback)
 {
     byte[] buffer = new byte[BUFFER_SIZE];
     byte[] charBuffer = new byte[MAX_TOKEN_SIZE];
     int charIndex = 0;
     int bufferSize;
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         do
         {
             bufferSize = stream.Read(buffer, 0, BUFFER_SIZE);
             for (int i = 0; i < bufferSize; i++)
             {
                 if (scannerNoMatch(buffer[i]))
                 {
                     charBuffer[charIndex++] = buffer[i];
                 }
                 else
                 {
                     callback(ENCODING.GetString(charBuffer, 0, charIndex));
                     charIndex = 0;
                 }
             }
         } while (bufferSize != 0);
     }
 }
Пример #30
-1
 public static PushStreamContent Create(string fileName, ITracer tracer, Action<ZipArchive> onZip)
 {
     var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
     {
         using (tracer.Step("ZipStreamContent.OnZip"))
         {
             try
             {
                 using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
                 {
                     onZip(zip);
                 }
             }
             catch (Exception ex)
             {
                 tracer.TraceError(ex);
                 throw;
             }
         }
     });
     content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     content.Headers.ContentDisposition.FileName = fileName;
     return content;
 }