System.Action.Invoke(string)

Here are the examples of the csharp api System.Action.Invoke(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2521 Examples 7

19 Source : BaseEngine.cs
with MIT License
from angelsix

public void Start()
        {
            Log($"{EngineName} Engine Starting...", type: LogType.Information);
            Log("=======================================", type: LogType.Information);

            // TODO: Add async lock here to prevent multiple calls

            // Dispose of any previous engine setup
            Dispose();

            // Make sure we have extensions
            if (EngineExtensions?.Count == 0)
                throw new InvalidOperationException("No engine extensions specified");

            // Let listener know we started
            Started();

            // Log the message
            Log($"Listening to '{ResolvedMonitorPath}'...", type: LogType.Information);
            LogTabbed($"Delay", $"{ProcessDelay}ms", 1);

            // Create a new list of watchers
            mWatchers = new List<FolderWatcher>
            {

                // We need to listen out for file changes per extension
                //EngineExtensions.ForEach(extension => mWatchers.Add(new FolderWatcher
                //{
                //    Filter = "*" + extension,
                //    Path = ResolvedMonitorPath,
                //    UpdateDelay = ProcessDelay
                //}));

                // Add watcher to watch for everything
                new FolderWatcher
                {
                    Filter = "*",
                    Path = ResolvedMonitorPath,
                    UpdateDelay = ProcessDelay
                }
            };

            // Listen on all watchers
            mWatchers.ForEach(watcher =>
            {
                // Listen for file changes
                watcher.FileChanged += Watcher_FileChanged;

                // Listen for deletions
                watcher.FileDeleted += Watcher_FileDeletedAsync;
                watcher.FolderDeleted += Watcher_FolderDeletedAsync;

                // Listen for renames / moves
                watcher.FileRenamed += Watcher_FileRenamedAsync;
                watcher.FolderRenamed += Watcher_FolderRenamedAsync;

                // Inform listener
                StartedWatching(watcher.Filter);

                // Log the message
                LogTabbed($"File Type", watcher.Filter, 1);

                // Start watcher
                watcher.Start();
            });

            // Closing comment tag
            Log("", type: LogType.Information);
        }

19 Source : FolderWatcher.cs
with MIT License
from angelsix

private void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            // If it is a file...
            if (File.Exists(e.FullPath))
                // Fire file deleted event
                FileDeleted(e.FullPath);
            else
                // Fire folder deleted event
                FolderDeleted(e.FullPath);
        }

19 Source : FolderWatcher.cs
with MIT License
from angelsix

private void OnFileChanged(string fullPath)
        {
            // Store file change path
            var path = fullPath;

            // Set the last update Id to this one
            if (!mLastUpdateIds.ContainsKey(path))
                mLastUpdateIds.Add(path, Guid.NewGuid());

            // Create new change Id for this path
            var updateId = Guid.NewGuid();
            mLastUpdateIds[path] = updateId;

            // Wait the delay period
            Task.Delay(Math.Max(1, UpdateDelay)).ContinueWith((t) =>
            {
                // Check if the last update Id still matches, meaning no updates since that time
                if (updateId != mLastUpdateIds[path])
                    return;

                // Settle time reached, so fire off the change event
                FileChanged(path);
            });
        }

19 Source : Log.cs
with MIT License
from AnotherEnd15

public static void Error(string msg)
        {
            StackTrace st = new StackTrace(1, true);
            ErrorCallback?.Invoke($"{msg}\n{st}");
            ILog.Error($"{msg}\n{st}");
        }

19 Source : Log.cs
with MIT License
from AnotherEnd15

public static void Error(Exception e)
        {
            string str = e.ToString();
            ErrorCallback?.Invoke(str);
            ILog.Error(str);
        }

19 Source : Log.cs
with MIT License
from AnotherEnd15

public static void Error(string message, params object[] args)
        {
            StackTrace st = new StackTrace(1, true);
            string s = string.Format(message, args) + '\n' + st;
            ErrorCallback?.Invoke(s);
            ILog.Error(s);
        }

19 Source : SpellConfigViewModel.Visual.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private ICommand CreateChangeColorCommand(
            Func<string> getCurrentColor,
            Action<string> changeColorAction)
            => new DelegateCommand(() =>
            {
                var result = ColorDialogWrapper.ShowDialog(getCurrentColor().FromHTML(), true);
                if (result.Result)
                {
                    changeColorAction.Invoke(result.LegacyColor.ToHTML());
                }
            });

19 Source : TimelineExpressionsModel.Table.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public bool Execute(
            TimelineExpressionsTableJsonModel queryModel,
            Action<string> raiseLog = null)
        {
            if (queryModel == null)
            {
                return false;
            }

            var result = false;
            var parent = this.Parent?.Parent;

            try
            {
                var table = TimelineExpressionsModel.GetTable(queryModel.Table);

                var key = queryModel.Cols
                    .FirstOrDefault(x => x.IsKey)?
                    .Val ?? null;

                if (queryModel.Method == TalbeJsonMethods.Delete)
                {
                    table.Remove(key);
                    raiseLog?.Invoke($"Delete row from TABLE['{queryModel.Table}'] by key='{key}'");
                }
                else if (queryModel.Method == TalbeJsonMethods.Truncate)
                {
                    table.Truncate();
                    raiseLog?.Invoke($"Truncate rows from TABLE['{queryModel.Table}']");
                }
                else
                {
                    var row = new TimelineRow();

                    var logs = new List<string>();
                    var keyLog = string.Empty;

                    foreach (var col in queryModel.Cols)
                    {
                        row.AddCol(new TimelineColumn(
                            col.Name,
                            col.Val,
                            col.IsKey));

                        logs.Add($"{col.Name}:'{col.Val}'");

                        if (col.IsKey)
                        {
                            keyLog = $"key='{col.Name}'";
                        }
                    }

                    table.Add(row);

                    var colLog = string.Join(", ", logs.ToArray());
                    raiseLog?.Invoke($"Merge row into TABLE['{queryModel.Table}'] cols ({colLog}) {keyLog}");
                }

                if (TimelineExpressionsModel.ReferedTriggerRecompileDelegates.ContainsKey(table.Name))
                {
                    lock (table)
                    {
                        TimelineExpressionsModel.ReferedTriggerRecompileDelegates[table.Name]?.Invoke();
                    }
                }

                result = true;
            }
            catch (Exception ex)
            {
                var parentName = string.IsNullOrEmpty(parent.Name) ?
                    (parent as dynamic).Text :
                    parent.Name;

                this.AppLogger.Error(
                    ex,
                    $"{TimelineConstants.LogSymbol} Error on execute table JSON. parent={parentName}.\n{this.JsonText}");

                result = false;
            }

            return result;
        }

19 Source : TimelineScriptGlobalModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void RaiseLogLine(
            string logLine)
            => this.RaiseLogLineDelegate?.Invoke(logLine);

19 Source : TimelineScriptGlobalModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void Trace(
            string message)
            => this.TraseDelegate?.Invoke(message);

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal void ReadParamenterSurfaceInfo(XElement element, string sid, Action<string> callback)
        {
            foreach (var item in element.Descendants("newparam"))
            {
                if (item.GetAttribute("sid") == sid)
                {
                    var surfaceElement = item.GetElementByTag("surface");
                    if (surfaceElement != null)
                    {
                        var initFrom = surfaceElement.GetElementByTag("init_from");
                        if (initFrom != null)
                        {
                            callback(initFrom.Value);
                            return;
                        }
                    }
                }
            }
        }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

internal void ReadTextureInfo(XElement element, string tag, Action<string> callback)
        {
            var e = element.GetDescendantByTag(tag);
            if (e != null)
            {              
                var textureRefElement = e.GetDescendantByTag("texture");
                if (textureRefElement != null)
                {
                    var textureElement = _libraryImages.GetElementById(textureRefElement.GetAttribute("texture"));
                    var textureUrl = textureElement.GetDescendantByTag("init_from").Value;
                    callback(textureUrl);
                }               
            }
        }

19 Source : ChatOverlayViewModel.cs
with MIT License
from anoyetta

private void LogBuffer_ChatLogAdded(
            object sender,
            ChatLogAddedEventArgs e)
        {
            if (sender == null)
            {
                return;
            }

            lock (this)
            {
                this.lastLogAddedTimestamp = DateTime.Now;

                if (!this.IsForceMinimized)
                {
                    this.ShowCallback?.Invoke();
                }
            }

            if (this.ChatOverlaySettings.IsAutoActivatePage)
            {
                this.ChangeActivePageCallback?.Invoke(e.ParentPage.Name);
            }

            this.ScrollToEndCallback?.Invoke();
        }

19 Source : Causal.cs
with Apache License 2.0
from AnthonyLloyd

public void Output(Action<string> output) => output(ToString());

19 Source : Dbg.cs
with Apache License 2.0
from AnthonyLloyd

public static void Output(Action<string> output)
    {
        foreach (var s in info)
            output(string.Concat("[Dbg] ", s));
        int maxLength = 0, total = 0;
        foreach (var kv in counts)
        {
            total += kv.Value;
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
        }
        foreach (var kc in counts.OrderByDescending(i => i.Value))
        {
            var percent = ((float)kc.Value / total).ToString("0.0%").PadLeft(7);
            output(string.Concat("Count: ", kc.Key.PadRight(maxLength), percent, " ", kc.Value));
        }
        maxLength = 0;
        int maxPercent = 0, maxTime = 0, maxCount = 0;
        foreach (var kv in times)
        {
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
            if ((kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length > maxTime)
                maxTime = (kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length;
            if (((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length > maxPercent)
                maxPercent = ((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length;
            if (kv.Value.Item2.ToString().Length > maxCount)
                maxCount = kv.Value.Item2.ToString().Length;
        }
        foreach (var kc in times)
        {
            var time = (kc.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").PadLeft(maxTime + 1);
            var percent = ((float)kc.Value.Item1 / times.Value(0).Item1).ToString("0.0%").PadLeft(maxPercent + 1);
            var count = kc.Value.Item2.ToString().PadLeft(maxCount + 1);
            output(string.Concat("Time: ", kc.Key.PadRight(maxLength), time, "ms", percent, count));
        }
        Clear();
    }

19 Source : SolveRootTests.cs
with Apache License 2.0
from AnthonyLloyd

[Fact]
        public void Root_TestProblems_Compare()
        {
            var rootCounts = TestSolver(1e-11, Root).Item2;
            var brentCounts = TestSolver(1e-11, Brent).Item2;
            var check =
                rootCounts.Zip(brentCounts)
                .Select((t, i) => (t.First, t.Second, i))
                .Where(t => t.First > t.Second)
                .OrderBy(t => t.Second - t.First)
                .ThenBy(t => ((double)(t.Second - t.First)) / t.Second)
                .Select(t => t.i + ": " + t.First + " - " + t.Second);
            foreach (var s in check) writeLine(s);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

public static void RunCommand(
			string program,
			string arguments,
			string workDir,
			Action<string> onOutput,
			Action<string> onError,
			bool isWait = true)
		{
			if (program == null)
			{
				program = "cmd";
				arguments = "/c " + arguments;
			}

			if (IsPrintCommand)
			{
				string cmd = string.Format("> {0} {1}", program, arguments);
				Console.WriteLine(cmd);
			}

			var si = new ProcessStartInfo
			{
				WorkingDirectory = workDir,
				FileName = program,
				Arguments = arguments,
				CreateNoWindow = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				UseShellExecute = false
			};
			// 此环境变量会破坏 clang 定位到正确的头文件目录
			si.EnvironmentVariables.Remove("VCInstallDir");

			Process pSpawn = new Process
			{
				StartInfo = si
			};

			if (onOutput != null)
			{
				pSpawn.OutputDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onOutput(args.Data);
				};
			}
			if (onError != null)
			{
				pSpawn.ErrorDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onError(args.Data);
				};
			}

			pSpawn.Start();

			if (onOutput != null)
				pSpawn.BeginOutputReadLine();

			if (onError != null)
				pSpawn.BeginErrorReadLine();

			if (isWait)
				pSpawn.WaitForExit();
		}

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

protected override bool DoAction()
		{
			bool isError = false;
			Helper.RunCommand(
				null,
				Command,
				WorkDir,
				OnOutput,
				strErr =>
				{
					if (!isError && strErr.IndexOf("error") != -1)
						isError = true;

					if (isError)
						OnError(strErr);
					else
						OnOutput(strErr);
				});

			return !isError;
		}

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

protected virtual bool DoAction()
		{
			bool isError = false;
			Helper.RunCommand(
				null,
				Command,
				WorkDir,
				OnOutput,
				strErr =>
				{
					isError = true;
					OnError(strErr);
				});

			return !isError;
		}

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

private static void RunCommand(
			string program,
			string arguments,
			string workDir,
			Action<string> onOutput,
			Action<string> onError,
			bool isWait = true)
		{
			if (program == null)
			{
				program = "cmd";
				arguments = "/c " + arguments;
			}

			var si = new ProcessStartInfo
			{
				WorkingDirectory = workDir,
				FileName = program,
				Arguments = arguments,
				CreateNoWindow = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				UseShellExecute = false
			};
			// 此环境变量会破坏 clang 定位到正确的头文件目录
			si.EnvironmentVariables.Remove("VCInstallDir");

			Process pSpawn = new Process
			{
				StartInfo = si
			};

			if (onOutput != null)
			{
				pSpawn.OutputDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onOutput(args.Data);
				};
			}
			if (onError != null)
			{
				pSpawn.ErrorDataReceived += (sender, args) =>
				{
					if (args.Data != null)
						onError(args.Data);
				};
			}

			pSpawn.Start();

			if (onOutput != null)
				pSpawn.BeginOutputReadLine();

			if (onError != null)
				pSpawn.BeginErrorReadLine();

			if (isWait)
				pSpawn.WaitForExit();
		}

19 Source : Options.cs
with MIT License
from aolszowka

public OptionSet Add (string prototype, string description, Action<string> action)
		{
			if (action == null)
				throw new ArgumentNullException ("action");
			Option p = new ActionOption (prototype, description, 1, 
					delegate (OptionValueCollection v) { action (v [0]); });
			base.Add (p);
			return this;
		}

19 Source : TestAmqpPeer.cs
with Apache License 2.0
from apache

public void ExpectReceiverAttach(
            Action<string> linkNameMatcher,
            Action<Source> sourceMatcher,
            Action<Target> targetMatcher,
            bool settled = false,
            bool refuseLink = false,
            Symbol errorType = null,
            string errorMessage = null,
            Source responseSourceOverride = null,
            Action<Symbol[]> desiredCapabilitiesMatcher = null)
        {
            var attachMatcher = new FrameMatcher<Attach>()
                .Withreplacedertion(attach => linkNameMatcher(attach.LinkName))
                .Withreplacedertion(attach => replacedert.AreEqual(Role.RECEIVER, attach.Role))
                .Withreplacedertion(attach => replacedert.AreEqual(settled ? SenderSettleMode.Settled : SenderSettleMode.Unsettled, attach.SndSettleMode))
                .Withreplacedertion(attach => replacedert.AreEqual(ReceiverSettleMode.First, attach.RcvSettleMode))
                .Withreplacedertion(attach => sourceMatcher(attach.Source as Source))
                .Withreplacedertion(attach => targetMatcher(attach.Target as Target))
                .WithOnComplete(context =>
                {
                    var attach = new Attach()
                    {
                        Role = Role.SENDER,
                        SndSettleMode = SenderSettleMode.Unsettled,
                        RcvSettleMode = ReceiverSettleMode.First,
                        InitialDeliveryCount = 0,
                        Handle = context.Command.Handle,
                        LinkName = context.Command.LinkName,
                        Target = context.Command.Target,
                        OfferedCapabilities = new []{ SymbolUtil.OPEN_CAPABILITY_SHARED_SUBS }
                    };

                    if (refuseLink)
                        attach.Source = null;
                    else if (responseSourceOverride != null)
                        attach.Source = responseSourceOverride;
                    else
                        attach.Source = context.Command.Source;

                    this.lastInitiatedLinkHandle = context.Command.Handle;

                    context.SendCommand(attach);
                });

            if (desiredCapabilitiesMatcher != null)
            {
                attachMatcher.Withreplacedertion(attach => desiredCapabilitiesMatcher(attach.DesiredCapabilities));
            }

            if (refuseLink)
            {
                attachMatcher.WithOnComplete(context =>
                {
                    var detach = new Detach { Closed = true, Handle = context.Command.Handle };
                    context.SendCommand(detach);
                });
            }

            AddMatcher(attachMatcher);
        }

19 Source : PhoneFormatter.cs
with Apache License 2.0
from AppRopio

public bool ShouldChangePhoneNumber(UITextField textField, NSRange range, string replacementString)
        {
            var changedString = (range.Location > 0 ? textField.Text.Substring(0, (int)range.Location) : "")
                + replacementString
                + (textField.Text.Substring(
                    (int)(range.Location + range.Length),
                    (int)(textField.Text.Length - range.Location - range.Length)));

            if (range.Length == 1 && replacementString.Length == 0 &&
                !char.IsDigit(textField.Text[(int)range.Location]))
            {
                // Something was deleted.  Delete past the previous number
                int location = changedString.Length - 1;
                if (location > 0)
                {
                    for (; location > 0; location--)
                    {
                        if (char.IsDigit(changedString[location]))
                            break;
                    }
                    changedString = changedString.Substring(0, location);
                }
            }

            textField.Text = FilteredPhoneString(changedString);

            FireValueChanged?.Invoke(textField.Text);

            return false;
        }

19 Source : CatalogSearchHeaderVm.cs
with Apache License 2.0
from AppRopio

protected override void OnSearchTextChanged(string searchText)
        {
            SearchTextChanged?.Invoke(searchText);
        }

19 Source : CloudPayments3DSService.cs
with Apache License 2.0
from AppRopio

public override void OnReceivedError(WebView view, [GeneratedEnum] ClientError errorCode, string description, string failingUrl)
            {
                if (failingUrl != _redirectUri)
                    OnLoadingError?.Invoke(description);
            }

19 Source : CloudPayments3DSService.cs
with Apache License 2.0
from AppRopio

public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
            {
                if (request.Url.ToString() != _redirectUri)
                    OnLoadingError?.Invoke(error.Description);
            }

19 Source : CloudPayments3DSService.cs
with Apache License 2.0
from AppRopio

[JavascriptInterface, Java.Interop.Export("processHTML")]
            public void processHTML(string paramString)
            {
                CompleteAuthorization?.Invoke(paramString);
            }

19 Source : BizService.cs
with MIT License
from appsonsf

public async Task GetPendingList(string accessToken, string componentId)
        {
            this._httpClient.SetBearerToken(accessToken);
            var response = await this._httpClient.GetAsync(BizUrlConfig.PUll_TODO_GET + "?appid=" + componentId);
            if (!response.IsSuccessStatusCode)
            {
                this.OnErrorOrExceptionEvent?.Invoke(response);
                return;
            }

            var content = await response.Content.ReadreplacedtringAsync();
            this.OnSuccessEvent?.Invoke(content);
        }

19 Source : BizService.cs
with MIT License
from appsonsf

public async Task GetDoneList(string accessToken, string componentId)
        {
            this._httpClient.SetBearerToken(accessToken);
            var response = await this._httpClient.GetAsync(BizUrlConfig.PUll_DONE_GET + "?appid=" + componentId);
            if (!response.IsSuccessStatusCode)
            {
                this.OnErrorOrExceptionEvent?.Invoke(response);
                return;
            }

            var content = await response.Content.ReadreplacedtringAsync();
            this.OnSuccessEvent?.Invoke(content);
        }

19 Source : SelectPathViewModel.cs
with MIT License
from arasplm

private void OnSelectDirectoryItem(DirectoryItemViewModel selectDirectoryItem)
		{
			this.selectDirectoryItem = selectDirectoryItem;
			var selectionChanged = SelectionChanged;
			if (selectionChanged != null)
			{
				selectionChanged(selectDirectoryItem.FullPath);
			}
		}

19 Source : PhotonEditorUtils.cs
with MIT License
from ArcturusZhang

public static System.Collections.IEnumerator HttpGet(string url, Action<string> successCallback, Action<string> errorCallback)
        {
            using (UnityEngine.Networking.UnityWebRequest w = UnityEngine.Networking.UnityWebRequest.Get(url))
            {
                #if UNITY_2017_2_OR_NEWER
                yield return w.SendWebRequest();
                #else
                yield return w.Send();
                #endif
 
                while (w.isDone == false)
                    yield return null;

                #if UNITY_2017_1_OR_NEWER
                if (w.isNetworkError || w.isHttpError)
                #else
                if (w.isError)
                #endif
                {
                    if (errorCallback != null)
                    {
                        errorCallback(w.error);
                    }
                }
                else
                {
                    if (successCallback != null)
                    {
                        successCallback(w.downloadHandler.text);
                    }
                }
            }
        }

19 Source : ConsoleLogger.cs
with MIT License
from Arefu

public void LogException(Exception exception)
        {
            var message = Localization.Exception(exception.Message, exception.InnerException?.Message);
            AppendExceptionToConsole?.Invoke(message);
        }

19 Source : ArtworkEditor.cs
with MIT License
from Arefu

private void Btn_browse_carddb_Click(object sender, EventArgs e)
        {
            if (browse_carddb.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var filePath = browse_carddb.FileName;
                SavePathSettingAction?.Invoke(filePath, Constants.Setting.LastUsedCardDbPath);
                CardDbPathChanged?.Invoke(filePath);
                txt_browse_carddb.Text = filePath;
            }
        }

19 Source : ConsoleLogger.cs
with MIT License
from Arefu

public void LogInformation(string message)
        {
            var formattedMessage = Localization.MessageFormattedForConsole(message);
            AppendTextToConsole?.Invoke(formattedMessage);
        }

19 Source : ArtworkEditor.cs
with MIT License
from Arefu

private void Btn_run_Click(object sender, EventArgs e)
        {
            var replacementImagesLocation = txt_browse_replacement_images.Text;
            MatchAllAction?.Invoke(replacementImagesLocation);
        }

19 Source : ArtworkEditor.cs
with MIT License
from Arefu

private void Btn_load_match_Click(object sender, EventArgs e)
        {
            LoadAction?.Invoke(txt_card_match_path.Text);
        }

19 Source : ArtworkPicker.cs
with MIT License
from Arefu

private void Btn_search_Click(object sender, EventArgs e)
        {
            SearchCards?.Invoke(txtbox_search.Text);
        }

19 Source : CompilerLog.cs
with GNU General Public License v3.0
from armandoalonso

public void Insert(string message, string type = "Info")
        {
            var log = new LogMessage {Date = DateTime.Now, Message = message, Type = type};
            Logs.Add(log);

            foreach (var callback in _insertCallbacks)
            {
                callback?.Invoke(log.ToString());
            }
        }

19 Source : LogManager.cs
with GNU General Public License v3.0
from armandoalonso

public static void AddLogMessage(string message, string source = "Info")
        {
            var log = new LogMessage{Date = DateTime.Now, Message = message, Type = source};
            Logs.Add(log);

            foreach (var logCallback in _logCallbacks)
            {
                logCallback?.Invoke(log.ToString());
            }
        }

19 Source : LogManager.cs
with GNU General Public License v3.0
from armandoalonso

public static void AddErrorLog(Exception ex)
        {
            Exceptions.Add(ex);
            var log = new LogMessage {Date = DateTime.Now, Message = $"{ex.Source} => \n{ex.Message}\n{ex.StackTrace}", Type = "Error"};
            Logs.Add(log);

            foreach (var errorCallback in _errorCallbacks)
            {
                errorCallback?.Invoke(log.ToString());
            }
        }

19 Source : NotificationManager.cs
with GNU General Public License v3.0
from armandoalonso

public static void PublishNotification(string notification)
        {
            _notificationCallback?.Invoke(notification);
        }

19 Source : NotificationManager.cs
with GNU General Public License v3.0
from armandoalonso

public static void PublishErrorNotification(string notification)
        {
            _errorCallback?.Invoke(notification);
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public bool CheckEmailVerified(Action<string> updateStatus, ref bool shouldRetry)
        {
            Logger.Trace("Creating account: checking mail is verified");

            SetConfig(Defaults.Web.STEAM_AJAX_CHECK_VERIFIED_URI, Method.POST);
            _request.AddParameter("creationid", _sessionId);

            var response = _client.Execute(_request);
            switch (response.Content)
            {
                case "1":
                    Logger.Debug("Creating account: Email confirmed, done!");
                    updateStatus?.Invoke("Email confirmed, done!");
                    return true;
                case "42":
                case "29":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.REGISTRATION}");
                    updateStatus?.Invoke(Error.REGISTRATION);
                    break;
                case "27":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.TIMEOUT}");
                    updateStatus?.Invoke(Error.TIMEOUT);
                    break;
                case "36":
                case "10":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.MAIL_UNVERIFIED}");
                    updateStatus?.Invoke(Error.MAIL_UNVERIFIED);
                    break;
                default:
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.UNKNOWN}");
                    updateStatus?.Invoke(Error.UNKNOWN);
                    shouldRetry = FormMain.ProxyManager.GetNew();
                    break;
            }
            return false;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public bool CheckEmailVerified(Action<string> updateStatus, ref bool shouldRetry)
        {
            Logger.Trace("Creating account: checking mail is verified");

            SetConfig(Defaults.Web.STEAM_AJAX_CHECK_VERIFIED_URI, Method.POST);
            _request.AddParameter("creationid", _sessionId);

            var response = _client.Execute(_request);
            switch (response.Content)
            {
                case "1":
                    Logger.Debug("Creating account: Email confirmed, done!");
                    updateStatus?.Invoke("Email confirmed, done!");
                    return true;
                case "42":
                case "29":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.REGISTRATION}");
                    updateStatus?.Invoke(Error.REGISTRATION);
                    break;
                case "27":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.TIMEOUT}");
                    updateStatus?.Invoke(Error.TIMEOUT);
                    break;
                case "36":
                case "10":
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.MAIL_UNVERIFIED}");
                    updateStatus?.Invoke(Error.MAIL_UNVERIFIED);
                    break;
                default:
                    Logger.Warn($"Creating account error: #{response.Content} / {Error.UNKNOWN}");
                    updateStatus?.Invoke(Error.UNKNOWN);
                    shouldRetry = FormMain.ProxyManager.GetNew();
                    break;
            }
            return false;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public bool CompleteSignup(string alias, string preplacedword,
            Action<string> updateStatus,
            ref long steamId, ref int gamesNotAdded,
            IEnumerable<Models.GameInfo> addThisGames,
            Models.ProfileConfig profileConfig)
        {
            Logger.Trace("Creating account: compliting signup...");

            if (!CheckAlias(alias, updateStatus))
                return false;
            if (!CheckPreplacedword(preplacedword, alias, updateStatus))
                return false;

            SetConfig(Defaults.Web.STEAM_CREATE_ACCOUNT_URI, Method.POST);
            _request.AddParameter("accountname", alias);
            _request.AddParameter("preplacedword", preplacedword);
            _request.AddParameter("creation_sessionid", _sessionId);
            _request.AddParameter("count", "1");
            _request.AddParameter("lt", "0");

            var response = _client.Execute(_request);

            dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);
            if (jsonResponse.bSuccess == "true")
            {
                Logger.Debug("Creating account: Account created");
                updateStatus?.Invoke("Account created");
                //disable guard
                Logger.Debug("Creating account: Disabling guard");
                _client.FollowRedirects = false;
                SetConfig("https://store.steampowered.com/twofactor/manage", Method.POST);
                _request.AddParameter("action", "none");
                _request.AddParameter("sessionid", _sessionId);
                _request.AddParameter("none_authenticator_check", "on");
                var response1 = _client.Execute(_request);
                var sessionId = "";

                var cookies = _cookieJar.GetCookies(new Uri("https://store.steampowered.com/"));
                foreach (Cookie cookie in cookies)
                {
                    _cookieJar.Add(new Uri("https://steamcommunity.com"), cookie);

                    if (cookie.Name.ToLower() == "sessionid")
                    {
                        sessionId = cookie?.Value ?? "";
                    }
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    Logger.Warn($"SessionID cookie not found for: {alias}");
                    updateStatus?.Invoke("Account seems created but SessionID cookie not found. Cannot disable guard, add game(s), set profile.");
                    return true;
                }

                SetConfig("https://store.steampowered.com/twofactor/manage_action", Method.POST);
                _request.AddParameter("action", "actuallynone");
                _request.AddParameter("sessionid", sessionId);
                var response11 = _client.Execute(_request);
                _client.FollowRedirects = true;

                var _steamIdRegex = SteamProfileRegex.Match(response1?.Content ?? "");
                if (!_steamIdRegex.Success)
                    _steamIdRegex = SteamProfileRegex.Match(response11?.Content ?? "");

                if (_steamIdRegex.Success)
                {
                    Logger.Trace($"Creating account: SteamID64 found ({_steamIdRegex.Groups[1].Value}).");
                    steamId = long.Parse(_steamIdRegex.Groups[1].Value);
                }

                gamesNotAdded = 0;
                foreach (var game in addThisGames)
                {
                    if (game == null)
                        continue;

                    var addSuccess = false;

                    try
                    {
                        Logger.Debug($"Creating account: Adding game({game.SubId}:{game.Name})");
                        updateStatus($"Adding game: {game.Name}");

                        SetConfig("https://store.steampowered.com/checkout/addfreelicense", Method.POST);
                        _request.AddParameter("action", "add_to_cart");
                        _request.AddParameter("subid", game.SubId);
                        _request.AddParameter("sessionid", sessionId);
                        var responce111 = _client.Execute(_request);
                        _client.FollowRedirects = true;

                        addSuccess = Regex.IsMatch(responce111?.Content ?? "", $"steam://subscriptioninstall/{game.SubId}", RegexOptions.IgnoreCase);
                    }
                    catch { }

                    if (!addSuccess)
                    {
                        gamesNotAdded++;
                        Logger.Warn($"Creating account: Adding game({game.SubId}:{game.Name}) failed!");
                    }

                    if (game != addThisGames.Last())
                        Thread.Sleep(500);
                }

                if ((profileConfig?.Enabled ?? false) && steamId > 0)
                {
                    Logger.Debug("Updating profile info...");
                    updateStatus("Updating profile info...");

                    var profCli = new RestClient("https://steamcommunity.com")
                    {
                        CookieContainer = _cookieJar
                    };
                    var profReq = new RestRequest($"/profiles/{steamId}/edit", Method.POST);
                    profReq.AddHeader("Referer", $"https://steamcommunity.com/profiles/{steamId}/edit?welcomed=1");
                    profReq.AddParameter("sessionID", sessionId);
                    profReq.AddParameter("type", "profileSave");
                    profReq.AddParameter("personaName", profileConfig.Name);
                    profReq.AddParameter("real_name", profileConfig.RealName);
                    profReq.AddParameter("country", profileConfig.Country);
                    profReq.AddParameter("state", profileConfig.State);
                    profReq.AddParameter("city", profileConfig.City);
                    if (profileConfig.Url)
                        profReq.AddParameter("customURL", alias);
                    profReq.AddParameter("summary", profileConfig.Bio);

                    var profRes = profCli.Execute(profReq);

                    if (System.IO.File.Exists(profileConfig?.Image ?? ""))
                    {
                        var imageInfo = new FileInfo(profileConfig.Image);
                        if (imageInfo.Length <= MainForm.PHOTO_MAX_SIZE)
                        {
                            Logger.Debug("Uploading image...");
                            updateStatus("Uploading image...");

                            var photoReq = new RestRequest("/actions/FileUploader", Method.POST, DataFormat.Json)
                            {
                                JsonSerializer = new RestSharp.Serializers.Newtonsoft.Json.NewtonsoftJsonSerializer()
                            };

                            photoReq.AddParameter("MAX_FILE_SIZE", $"{MainForm.PHOTO_MAX_SIZE}");
                            photoReq.AddParameter("type", "player_avatar_image");
                            photoReq.AddParameter("sId", $"{steamId}");
                            photoReq.AddParameter("sessionid", $"{sessionId}");
                            photoReq.AddParameter("doSub", "1");
                            photoReq.AddParameter("json", "1");
                            photoReq.AddFile("avatar", imageInfo.FullName);

                            var resp = profCli.Execute<Models.Steam.UploadProfileImage>(photoReq);
                            var imgUploadOk = resp?.Data?.Success ?? false;
                            if (imgUploadOk)
                                Logger.Debug("Uploading image done!");
                            else
                                Logger.Debug("Something went wrong with uloading image");
                        }
                    }

                    Logger.Debug("Updating profile info done!");
                }

                Logger.Debug("Creating account: done!");
                return true;
            }
            Logger.Debug($"Creating account: {jsonResponse.details}");
            updateStatus?.Invoke((jsonResponse.details as object)?.ToString() ?? "Accounts seems to be created but something broken...");
            return false;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public bool CreateAccount(string email, Captcha.CaptchaSolution captcha, Action<string> updateStatus, ref bool stop)
        {
            if (CreateFailedCount >= 3)
            {
                Logger.Warn("FAILED! Current IP seems to be banned. Endless captcha detected.");
                updateStatus?.Invoke("FAILED! Current IP seems to be banned. Endless captcha detected.");
                stop = true;
                return false;
            }

            if (!(captcha?.Solved ?? false))
            {
                Logger.Warn("Captcha not solved. Cannot create account.");
                return false;
            }

            Logger.Debug("Creating account...");

            //Send request again
            SetConfig(Defaults.Web.STEAM_AJAX_VERIFY_EMAIL_URI, Method.POST);
            _request.AddParameter("captchagid", _captchaGid);
            _request.AddParameter("captcha_text", captcha.Solution);
            _request.AddParameter("email", email);

            var response = _client.Execute(_request);
            if (!response.IsSuccessful)
            {
                Logger.Warn($"HTTP Error: {response.StatusCode}");
                updateStatus($"HTTP Error: {response.StatusCode}");
                return false;
            }

            _request.Parameters.Clear();
            try
            {
                dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);

                var succesCode = 0;
                try
                {
                    succesCode = (jsonResponse?.success as Newtonsoft.Json.Linq.JValue)?.ToObject<int?>() ?? 0;
                }
                catch (Exception ex)
                {
                    Logger.Error("Cannot get success code.", ex);
                }

                if (jsonResponse.success != 1)
                {
                    switch (succesCode)
                    {
                        case 62:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.SIMILIAR_MAIL}");
                            updateStatus(Error.SIMILIAR_MAIL);
                            stop = true;
                            return false;
                        case 13:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.INVALID_MAIL}");
                            updateStatus(Error.INVALID_MAIL);
                            stop = true;
                            return false;
                        case 17:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.TRASH_MAIL}");
                            updateStatus(Error.TRASH_MAIL);
                            stop = true;
                            return false;
                        case 101: // Please verify your humanity by re-entering the characters below.
                            Logger.Warn("Creating account error: Wrong captcha");
                            updateStatus(Error.WRONG_CAPTCHA);

                            if (captcha.Config != null)
                            {
                                if (captcha.Config.Service == Enums.CaptchaService.RuCaptcha &&
                                    captcha.Config.RuCaptcha.ReportBad)
                                {
                                    TwoCaptchaReport(captcha, false);
                                }
                            }
                            stop = !FormMain.ProxyManager.GetNew();
                            CreateFailedCount++;
                            return false;
                        case 84:
                            {
                                Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.PROBABLY_IP_BAN}");
                                updateStatus(Error.PROBABLY_IP_BAN);
                                stop = !FormMain.ProxyManager.GetNew();
                                CreateFailedCount++;
                            }
                            return false;
                        default:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.UNKNOWN}");
                            updateStatus(Error.UNKNOWN);
                            stop = !FormMain.ProxyManager.GetNew();
                            CreateFailedCount++;
                            break;
                    }
                    return false;
                }

                Logger.Trace($"Creating account, SessionID: {_sessionId}");
                _sessionId = jsonResponse.sessionid;

                Logger.Debug("Creating account: Waiting for email to be verified");
                updateStatus("Waiting for email to be verified");
            }
            catch { }

            return true;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

private bool CheckAlias(string alias, Action<string> statusUpdate)
        {
            Logger.Debug("Checking alias (login)...");

            var tempClient = new RestClient(Defaults.Web.STEAM_CHECK_AVAILABLE_URI);
            var tempRequest = new RestRequest(Method.POST);
            tempRequest.AddParameter("accountname", alias);
            tempRequest.AddParameter("count", "1");

            var response = tempClient.Execute(tempRequest);
            dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);

            if (jsonResponse.bAvailable == "true")
            {
                Logger.Debug("Checking alias (login): OK");
                return true;
            }

            Logger.Warn($"Checking alias (login): {Error.ALIAS_UNAVAILABLE}");
            statusUpdate?.Invoke(Error.ALIAS_UNAVAILABLE);
            return false;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

private bool CheckPreplacedword(string preplacedword, string alias, Action<string> updateStatus)
        {
            Logger.Debug("Checking preplacedword...");

            var tempClient = new RestClient(Defaults.Web.STEAM_CHECK_AVAILABLE_PreplacedWORD_URI)
            {
                CookieContainer = _cookieJar,
                Proxy = FormMain?.ProxyManager?.WebProxy
            };
            var tempRequest = new RestRequest(Method.POST);
            tempRequest.AddParameter("preplacedword", preplacedword);
            tempRequest.AddParameter("accountname", alias);
            tempRequest.AddParameter("count", "1");

            var response = tempClient.Execute(tempRequest);
            dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);

            if (jsonResponse.bAvailable == "true")
            {
                Logger.Debug("Checking preplacedword: OK");
                return true;
            }

            Logger.Debug($"Checking preplacedword: {Error.PreplacedWORD_UNSAFE}");
            updateStatus?.Invoke(Error.PreplacedWORD_UNSAFE);
            return false;
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public Captcha.CaptchaSolution SolveCaptcha(Action<string> updateStatus, Models.Configuration config)
        {
            Logger.Debug("Getting captcha...");
            updateStatus?.Invoke("Getting captcha...");

            var captchaConfig = config.Captcha;

            if (!GetRecaptcha(3, out string _siteKey, out _captchaGid, out bool? isRecaptcha))
                return new Captcha.CaptchaSolution(true, "Get captcha info error!", captchaConfig);

            if (string.IsNullOrEmpty(_captchaGid))
                return new Captcha.CaptchaSolution(true, "Getting captcha GID error!", captchaConfig);

            var captchaPayload = string.Empty;
            if (isRecaptcha.HasValue && !isRecaptcha.Value)
            {
                //download and return captcha image
                SetConfig($"{Defaults.Web.STEAM_RENDER_CAPTCHA_ADDRESS}?gid={_captchaGid}", Method.GET);
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        Logger.Debug($"Downloading captcha: Try {i + 1}/3");
                        updateStatus($"Downloading captcha: Try {i + 1}/3");

                        var _captchaResp = _client.DownloadData(_request);
                        captchaPayload = GetBase64FromImage(_captchaResp);

                        break;
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Downloading captcha error.", ex);
                        captchaPayload = string.Empty;
                    }
                }
            }

            // recognize captcha
            Logger.Debug("Recognizing captcha...");
            updateStatus("Recognizing captcha...");
            switch (captchaConfig.Service)
            {
                case Enums.CaptchaService.Captchasolutions:
                    {
                        if (!captchaConfig.Enabled)
                            goto default;

                        var _params = new Dictionary<string, object>()
                        {
                            { "key", captchaConfig.CaptchaSolutions.ApiKey },
                            { "secret", captchaConfig.CaptchaSolutions.ApiSecret },
                            { "out", "txt" },
                        };

                        if (isRecaptcha.HasValue && isRecaptcha.Value)
                        {
                            _params.Add("p", "nocaptcha");
                            _params.Add("googlekey", _siteKey);
                            _params.Add("pageurl", Defaults.Web.STEAM_JOIN_ADDRESS);
                        }
                        else
                        {
                            _params.Add("p", "base64");
                            _params.Add("captcha", $"data:image/jpg;base64,{captchaPayload}");
                        }

                        Logger.Debug("Recognizing captcha via Captchasolutions...");
                        var _resp = Captchasolutions("solve",
                            new Dictionary<string, object>()
                            {
                                { "p", "base64" },
                                { "captcha", $"data:image/jpg;base64,{captchaPayload}" },
                                { "key", captchaConfig.CaptchaSolutions.ApiKey },
                                { "secret", captchaConfig.CaptchaSolutions.ApiSecret },
                                { "out", "txt" },
                            });

                        if (Regex.IsMatch(_resp, @"Error:\s(.+)", RegexOptions.IgnoreCase))
                        {
                            Logger.Warn($"Captchasolutions error:\n{_resp}\n====== END ======");
                            return new Captcha.CaptchaSolution(true, _resp, captchaConfig);
                        }

                        var solution = Regex.Replace(_resp, @"\t|\n|\r", "");
                        Logger.Debug($"Captchasolutions: {solution}");
                        return new Captcha.CaptchaSolution(solution, null, captchaConfig);
                    }
                case Enums.CaptchaService.RuCaptcha:
                    {
                        if (!captchaConfig.Enabled)
                            goto default;

                        Logger.Debug("Recognizing captcha via TwoCaptcha/RuCaptcha");

                        var _params = new Dictionary<string, object>()
                        {
                            { "key", captchaConfig.RuCaptcha.ApiKey },
                            { "soft_id", "2370" },
                            { "json", "0" }
                        };

                        if (isRecaptcha.HasValue && isRecaptcha.Value)
                        {
                            _params.Add("googlekey", _siteKey);
                            _params.Add("method", "userrecaptcha");
                            _params.Add("pageurl", Defaults.Web.STEAM_JOIN_ADDRESS);
                        }
                        else
                        {
                            _params.Add("body", $"data:image/jpg;base64,{captchaPayload}");
                            _params.Add("method", "base64");
                        }

                        var _captchaIdResponse = TwoCaptcha("in.php", _params);

                        var _captchaStatus = _captchaIdResponse?.FirstOrDefault()?.ToUpper() ?? "UNKNOWN";
                        Logger.Debug($"TwoCaptcha/RuCaptcha image upload response: {_captchaStatus}");
                        switch (_captchaStatus)
                        {
                            case "OK":
                                break;
                            case "ERROR_NO_SLOT_AVAILABLE":
                                Thread.Sleep(6000);
                                return new Captcha.CaptchaSolution(true, _captchaStatus, captchaConfig);
                            default:
                                return new Captcha.CaptchaSolution(false, _captchaStatus, captchaConfig);
                        }

                        var _captchaId = _captchaIdResponse.ElementAt(1);
                        Logger.Debug($"TwoCaptcha/RuCaptcha ID: {_captchaId}");

                        Thread.Sleep(TimeSpan.FromSeconds(20));

                        var solution = string.Empty;
                        var retryCount = (isRecaptcha.HasValue && isRecaptcha.Value)
                            ? 10
                            : 3;
                        for (int i = 0; (Program.EndlessTwoCaptcha) ? true : i < retryCount; i++)
                        {
                            Logger.Debug($"TwoCaptcha/RuCaptcha requesting solution... Try {i + 1}{(Program.EndlessTwoCaptcha ? "" : $" of {retryCount}")}");
                            var _captchaResponse = TwoCaptcha("res.php",
                                new Dictionary<string, object>()
                                {
                                    { "key", captchaConfig.RuCaptcha.ApiKey },
                                    { "action", "get" },
                                    { "id", _captchaId },
                                    { "json", "0" },
                                });

                            var _status = _captchaResponse?.FirstOrDefault()?.ToUpper() ?? "UNKNOWN";
                            Logger.Debug($"TwoCaptcha/RuCaptcha solving status: {_status}");
                            switch (_status)
                            {
                                case "OK":
                                    {
                                        var _solution = new Captcha.CaptchaSolution(_captchaResponse.ElementAt(1), _captchaId, captchaConfig);
                                        Logger.Debug($"TwoCaptcha/RuCaptcha solution: {_solution.Solution}");
                                        return _solution;
                                    }
                                case "CAPCHA_NOT_READY":
                                case "ERROR_NO_SLOT_AVAILABLE":
                                    Thread.Sleep(6000);
                                    continue;
                                default:
                                    return new Captcha.CaptchaSolution(true, _status, captchaConfig);
                            }
                        }
                    }
                    Logger.Debug("TwoCaptcha/RuCaptcha somethig went wrong.");
                    return new Captcha.CaptchaSolution(true, "Something went wrong", captchaConfig);
                case Enums.CaptchaService.Module:
                    {
                        try
                        {
                            if (isRecaptcha.HasValue && !isRecaptcha.Value)
                            {
                                var imageCaptchas = FormMain.ModuleManager.Modules.GetCaptchaSolvers();
                                if (imageCaptchas.Count() < 1)
                                    goto default;

                                var anyRetryAvailable = false;
                                for (int i = 0; i < imageCaptchas.Count(); i++)
                                {
                                    var ic = imageCaptchas.ElementAt(i);
                                    var icResponse = ic.Solve(new SACModuleBase.Models.Capcha.CaptchaRequest(captchaPayload, FormMain.ProxyManager.WebProxy));
                                    var icStatus = icResponse?.Status ?? SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve;
                                    if (icStatus == SACModuleBase.Enums.Captcha.CaptchaStatus.Success)
                                        return new Captcha.CaptchaSolution(icResponse.Solution, icResponse?.ToString(), captchaConfig);

                                    switch (icStatus)
                                    {
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.RetryAvailable:
                                            anyRetryAvailable = true;
                                            continue;
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.Failed:
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve:
                                            continue;
                                    }
                                }
                                return new Captcha.CaptchaSolution(anyRetryAvailable, "Something went wrong...", captchaConfig);
                            }
                            else
                            {
                                var reCaptchas = FormMain.ModuleManager.Modules.GetReCaptchaSolvers();
                                if (reCaptchas.Count() < 1)
                                    goto default;

                                var anyRetryAvailable = false;
                                for (int i = 0; i < reCaptchas.Count(); i++)
                                {
                                    var rc = reCaptchas.ElementAt(i);
                                    var rcResponse = rc.Solve(new SACModuleBase.Models.Capcha.ReCaptchaRequest(_siteKey, Defaults.Web.STEAM_JOIN_ADDRESS));
                                    var rcStatus = rcResponse?.Status ?? SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve;
                                    if (rcStatus == SACModuleBase.Enums.Captcha.CaptchaStatus.Success)
                                        return new Captcha.CaptchaSolution(rcResponse.Solution, rcResponse?.ToString(), captchaConfig);

                                    switch (rcStatus)
                                    {
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.RetryAvailable:
                                            anyRetryAvailable = true;
                                            continue;
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.Failed:
                                        case SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve:
                                            continue;
                                    }
                                }
                                return new Captcha.CaptchaSolution(anyRetryAvailable, "Something went wrong...", captchaConfig);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error($"Module solving error.", ex);
                        }
                    }
                    return new Captcha.CaptchaSolution(true, "Something went wrong.", captchaConfig);
                default:
                    {
                        try
                        {
                            var recap = isRecaptcha.HasValue && isRecaptcha.Value;
                            using (var dialog = (recap)
                                ? FormMain.ExecuteInvoke(() => new ReCaptchaDialog(config, FormMain.ProxyManager.Current) as ICaptchaDialog)
                                : new CaptchaDialog(this, updateStatus, config))
                            {
                                var solution = default(Captcha.CaptchaSolution);
                                var dialogResult = DialogResult.None;
                                if (recap)
                                    dialogResult = FormMain.ExecuteInvokeLock(() => dialog.ShowDialog(out solution));
                                else // for image captcha we don't wait other windowses
                                    dialogResult = dialog.ShowDialog(out solution);

                                if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Cancel)
                                {
                                    solution = solution ?? new Captcha.CaptchaSolution(true, "Something went wrong...", config.Captcha);
                                    if (recap)
                                        _captchaGid = (string.IsNullOrEmpty(solution?.Id)) ? _captchaGid : solution?.Id ?? "";

                                    return solution;
                                }
                                else
                                    return new Captcha.CaptchaSolution(false, "Captcha not recognized!", config.Captcha);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("Manual captcha error.", ex);
                        }
                    }
                    return new Captcha.CaptchaSolution(true, "Something went wrong.", captchaConfig);
            }
        }

19 Source : HttpHandler.cs
with MIT License
from Ashesh3

public bool CreateAccount(string email, Captcha.CaptchaSolution captcha, Action<string> updateStatus, ref bool stop)
        {
            if (CreateFailedCount >= 3)
            {
                Logger.Warn("FAILED! Current IP seems to be banned. Endless captcha detected.");
                updateStatus?.Invoke("FAILED! Current IP seems to be banned. Endless captcha detected.");
                stop = true;
                return false;
            }

            if (!(captcha?.Solved ?? false))
            {
                Logger.Warn("Captcha not solved. Cannot create account.");
                return false;
            }

            Logger.Debug("Creating account...");

            //Send request again
            SetConfig(Defaults.Web.STEAM_AJAX_VERIFY_EMAIL_URI, Method.POST);
            _request.AddParameter("captchagid", _captchaGid);
            _request.AddParameter("captcha_text", captcha.Solution);
            _request.AddParameter("email", email);

            var response = _client.Execute(_request);
            if (!response.IsSuccessful)
            {
                Logger.Warn($"HTTP Error: {response.StatusCode}");
                updateStatus($"HTTP Error: {response.StatusCode}");
                return false;
            }

            _request.Parameters.Clear();
            try
            {
                dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);

                var succesCode = 0;
                try
                {
                    succesCode = (jsonResponse?.success as Newtonsoft.Json.Linq.JValue)?.ToObject<int?>() ?? 0;
                }
                catch (Exception ex)
                {
                    Logger.Error("Cannot get success code.", ex);
                }

                if (jsonResponse.success != 1)
                {
                    switch (succesCode)
                    {
                        case 62:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.SIMILIAR_MAIL}");
                            updateStatus(Error.SIMILIAR_MAIL);
                            stop = true;
                            return false;
                        case 13:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.INVALID_MAIL}");
                            updateStatus(Error.INVALID_MAIL);
                            stop = true;
                            return false;
                        case 17:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.TRASH_MAIL}");
                            updateStatus(Error.TRASH_MAIL);
                            stop = true;
                            return false;
                        case 101: // Please verify your humanity by re-entering the characters below.
                            Logger.Warn("Creating account error: Wrong captcha");
                            updateStatus(Error.WRONG_CAPTCHA);

                            if (captcha.Config != null)
                            {
                                if (captcha.Config.Service == Enums.CaptchaService.RuCaptcha &&
                                    captcha.Config.RuCaptcha.ReportBad)
                                {
                                    TwoCaptchaReport(captcha, false);
                                }
                            }
                            stop = !FormMain.ProxyManager.GetNew();
                            CreateFailedCount++;
                            return false;
                        case 84:
                            {
                                Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.PROBABLY_IP_BAN}");
                                updateStatus(Error.PROBABLY_IP_BAN);
                                stop = !FormMain.ProxyManager.GetNew();
                                CreateFailedCount++;
                            }
                            return false;
                        default:
                            Logger.Warn($"Creating account error: #{jsonResponse.success} / {Error.UNKNOWN}");
                            updateStatus(Error.UNKNOWN);
                            stop = !FormMain.ProxyManager.GetNew();
                            CreateFailedCount++;
                            break;
                    }
                    return false;
                }

                Logger.Trace($"Creating account, SessionID: {_sessionId}");
                _sessionId = jsonResponse.sessionid;

                Logger.Debug("Creating account: Waiting for email to be verified");
                updateStatus("Waiting for email to be verified");
            }
            catch { }

            return true;
        }

See More Examples