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 : MyPageBase.cs
with Mozilla Public License 2.0
from agebullhu

protected void ConvertQueryString(string name, Action<string> action)
        {
            var val = Request[name];
            if (!string.IsNullOrEmpty(val))
            {
                action(val);
            }
        }

19 Source : ApiControlerEx.cs
with Mozilla Public License 2.0
from agebullhu

protected void ConvertQueryString(string name, Action<string> action)
        {
            var val = Arguments[name];
            if (!string.IsNullOrEmpty(val)) action(val);
        }

19 Source : PlanController.cs
with Mozilla Public License 2.0
from agebullhu

protected void ConvertQueryString(string name, Action<string> action)
        {
            var val = Request.Form[name];
            if (!string.IsNullOrEmpty(val))
            {
                action(val);
            }
        }

19 Source : RequestToken.cs
with MIT License
from AgoraIO

public static IEnumerator FetchToken(
        string url, string channel, int userId, Action<string> callback = null
    ) {
      UnityWebRequest request = UnityWebRequest.Get(string.Format(
        "{0}/rtc/{1}/publisher/uid/{2}/", url, channel, userId
      ));
      yield return request.SendWebRequest();

      if (request.isNetworkError || request.isHttpError) {
        Debug.LogWarning("FetchToken: url = " + url + " error:" + request.error);
        callback(null);
        yield break;
      }

      TokenObject tokenInfo = JsonUtility.FromJson<TokenObject>(
        request.downloadHandler.text
      );

      callback(tokenInfo.rtcToken);
    }

19 Source : BookListItemPresenter.cs
with MIT License
from AiursoftWeb

private void SaveCommand(object _)
        {
            _onPatch(Editreplacedle);
            OnPropertyChanged(nameof(Book));
            IsEditing = false;
        }

19 Source : BotHost.cs
with MIT License
from AiursoftWeb

public async Task Connect(Action<string> onGetWebsocket = null)
        {
            _botLogger.LogWarning("Establishing the connection to Kahla...");
            await ReleaseMonitorJob();
            var server = AskServerAddress();
            _settingsService["ServerAddress"] = server;
            try
            {
                await _kahlaLocation.UseKahlaServerAsync(server);
            }
            catch (Exception e)
            {
                _botLogger.LogDanger(e.Message);
                return;
            }
            if (!await SignedIn())
            {
                await OpenSignIn();
                var code = await AskCode();
                await SignIn(code);
            }
            else
            {
                _botLogger.LogSuccess("\nYou are already signed in! Welcome!");
            }
            await RefreshUserProfile();
            var websocketAddress = await GetWsAddress();
            // Trigger on request.
            var requests = (await _friendshipService.MyRequestsAsync())
                .Items
                .Where(t => !t.Completed);
            foreach (var request in requests)
            {
                await BuildBot.OnFriendRequest(new NewFriendRequestEvent
                {
                    Request = request
                });
            }
            // Trigger group connected.
            var friends = (await _friendshipService.MineAsync());
            foreach (var group in friends.Groups)
            {
                await BuildBot.OnGroupConnected(group);
            }
            onGetWebsocket?.Invoke(websocketAddress);
            await Task.WhenAll(_backgroundJobs.Select(t => t.StopAsync(CancellationToken.None)));
            await Task.WhenAll(_backgroundJobs.Select(t => t.StartAsync(CancellationToken.None)));
        }

19 Source : ConcatDeadlockTest.cs
with Apache License 2.0
from akarnokd

[Test]
        public void TestMethod1()
        {
            CountdownEvent printed = null;
            var nextInnerQuery = new Subject<Unit>();
            IEnumerable<object> e = null;
            Action<string> afterSelectManyButBeforeConcat = _ => { };

            (from _ in nextInnerQuery
             select (from __ in Observable.Return(Unit.Default)
                     from completeSynchronously in e
                     from x in SyncOrAsync(completeSynchronously as string, completeSynchronously as IObservable<string>)
                     select x)
                     .Do(x => afterSelectManyButBeforeConcat(x)))
            .ConcatMany()
            .Subscribe(x =>
            {
                Console.WriteLine(x);
                printed.Signal();
            });


            Console.WriteLine("No deadlock...");

            printed = new CountdownEvent(2);
            e = new[] { "Sync 1", "Sync 2" };
            nextInnerQuery.OnNext(Unit.Default);

            printed.Wait();


            Console.WriteLine("Also no deadlock...");

            printed = new CountdownEvent(2);
            var first = new Subject<string>();
            var second = new Subject<string>();
            e = new[] { first, second };
            nextInnerQuery.OnNext(Unit.Default);
            first.OnNext("Async 1");
            second.OnNext("Async 2");

            printed.Wait();


            Console.WriteLine("DEADLOCK");

            printed = new CountdownEvent(2);
            var waitForAsyncOnThreadB = new ManualResetEventSlim();
            var asyncValue = new Subject<string>();

            // Thread B
            afterSelectManyButBeforeConcat = _ => waitForAsyncOnThreadB.Set();

            e = AsyncThenSync(
              asyncValue,
              "Sync 2",
              () =>
              {
            // Thread A
            asyncValue.OnNext("Async 1");
            // Thread B: SelectMany.OnNext acquires a lock
            //           (waitForAsyncOnThreadB is set)
            //           Concat blocks awaiting the lock acquired initially by Thread A.
            //           Order of locks: SelectMany -> Concat (DEADLOCK)

            // Thread A
            waitForAsyncOnThreadB.Wait();
              });

            // Thread A
            nextInnerQuery.OnNext(Unit.Default);   // Thread A: Concat (technically, Merge(1)) acquires and holds a lock while iterating 'e'

            // This line is never reached, and nothing is ever printed.
            printed.Wait();
        }

19 Source : FileIOControl.cs
with MIT License
from akihiro0105

public static IEnumerator ReadTextFile(string name,Action<string> action)
        {
            string data = null;
            if (File.Exists(name))
            {
#if WINDOWS_UWP
            var task = Task.Run(() =>data = File.ReadAllText(name));
            yield return new WaitWhile(() => task.IsCompleted == false);
#else
                var thread = new Thread(() => data = File.ReadAllText(name));
                thread.Start();
                yield return new WaitWhile(() => thread.IsAlive == true);
#endif
            }
            action.Invoke(data);
        }

19 Source : RestAPIControl.cs
with MIT License
from akihiro0105

public static IEnumerator PostRestAPI(string uri, Dictionary<string, string> value, Action<string> complete, Action<long> error = null)
        {
            var form = new WWWForm();
            foreach (var item in value) form.AddField(item.Key, item.Value);
            using (var www = UnityWebRequest.Post(uri, form))
            {
                yield return www.SendWebRequest();
                if (www.responseCode != 200)
                {
                    if (error != null) error.Invoke(www.responseCode);
                }
                else
                {
                    if (complete != null) complete.Invoke(www.downloadHandler.text);
                }
            }
        }

19 Source : Notifications.cs
with MIT License
from AkiniKites

public void ShowAppStatus(string text)
        {
            _appStatusSetter(text);
        }

19 Source : BaseNode.cs
with MIT License
from alelievr

public bool UpdatePortsForFieldLocal(string fieldName, bool sendPortUpdatedEvent = true)
		{
			bool changed = false;

			if (!nodeFields.ContainsKey(fieldName))
				return false;

			var fieldInfo = nodeFields[fieldName];

			if (!HasCustomBehavior(fieldInfo))
				return false;

			List< string > finalPorts = new List< string >();

			var portCollection = fieldInfo.input ? (NodePortContainer)inputPorts : outputPorts;

			// Gather all fields for this port (before to modify them)
			var nodePorts = portCollection.Where(p => p.fieldName == fieldName);
			// Gather all edges connected to these fields:
			var edges = nodePorts.SelectMany(n => n.GetEdges()).ToList();

			if (fieldInfo.behavior != null)
			{
				foreach (var portData in fieldInfo.behavior(edges))
					AddPortData(portData);
			}
			else
			{
				var customPortTypeBehavior = customPortTypeBehaviorMap[fieldInfo.info.FieldType];

				foreach (var portData in customPortTypeBehavior(fieldName, fieldInfo.name, fieldInfo.info.GetValue(this)))
					AddPortData(portData);
			}

			void AddPortData(PortData portData)
			{
				var port = nodePorts.FirstOrDefault(n => n.portData.identifier == portData.identifier);
				// Guard using the port identifier so we don't duplicate identifiers
				if (port == null)
				{
					AddPort(fieldInfo.input, fieldName, portData);
					changed = true;
				}
				else
				{
					// in case the port type have changed for an incompatible type, we disconnect all the edges attached to this port
					if (!BaseGraph.TypesAreConnectable(port.portData.displayType, portData.displayType))
					{
						foreach (var edge in port.GetEdges().ToList())
							graph.Disconnect(edge.GUID);
					}

					// patch the port data
					if (port.portData != portData)
					{
						port.portData.CopyFrom(portData);
						changed = true;
					}
				}

				finalPorts.Add(portData.identifier);
			}

			// TODO
			// Remove only the ports that are no more in the list
			if (nodePorts != null)
			{
				var currentPortsCopy = nodePorts.ToList();
				foreach (var currentPort in currentPortsCopy)
				{
					// If the current port does not appear in the list of final ports, we remove it
					if (!finalPorts.Any(id => id == currentPort.portData.identifier))
					{
						RemovePort(fieldInfo.input, currentPort);
						changed = true;
					}
				}
			}

			// Make sure the port order is correct:
			portCollection.Sort((p1, p2) => {
				int p1Index = finalPorts.FindIndex(id => p1.portData.identifier == id);
				int p2Index = finalPorts.FindIndex(id => p2.portData.identifier == id);

				if (p1Index == -1 || p2Index == -1)
					return 0;

				return p1Index.CompareTo(p2Index);
			});

			if (sendPortUpdatedEvent)
				onPortsUpdated?.Invoke(fieldName);

			return changed;
		}

19 Source : BaseNode.cs
with MIT License
from alelievr

public void RemoveMessageContains(string subMessage)
		{
			string toRemove = messages.Find(m => m.Contains(subMessage));
			messages.Remove(toRemove);
			onMessageRemoved?.Invoke(toRemove);
		}

19 Source : BaseNode.cs
with MIT License
from alelievr

public void RemoveMessage(string message)
		{
			onMessageRemoved?.Invoke(message);
			messages.Remove(message);
		}

19 Source : BaseNode.cs
with MIT License
from alelievr

public void ClearMessages()
		{
			foreach (var message in messages)
				onMessageRemoved?.Invoke(message);
			messages.Clear();
		}

19 Source : ClientConfigView.cs
with MIT License
from alerdenisov

public void AddressChange(string address)
        {
            OnAddressChange(address);
        }

19 Source : PointElement.cs
with Apache License 2.0
from AlexWan

public void ShowDialog()
        {
            if (NeadToShowDialog != null)
            {
                NeadToShowDialog(UniqName.Split('&')[0]);
            }
        }

19 Source : BitMexClient.cs
with Apache License 2.0
from AlexWan

private void Converter()
        {
            string myTradesStr = "{\"table\"" + ":" + "\"execution\"";
            string ordersStr = "{\"table\"" + ":" + "\"order\"";
            string marginStr = "{\"table\"" + ":" + "\"margin\"";
            string positionsStr = "{\"table\"" + ":" + "\"position\"";
            string marketDepthStr = "{\"table\"" + ":" + "\"orderBookL2\"";
            string tradesStr = "{\"table\"" + ":" + "\"trade\"";

            while (true)
            {
                try
                {
                    if (_neadToStopAllThreads == true)
                    {
                        return;
                    }
                    if (!_newMessage.IsEmpty)
                    {
                        string mes;

                        if (_newMessage.TryDequeue(out mes))
                        {


                            if (mes.StartsWith(myTradesStr))
                            {
                                var myOrder = JsonConvert.DeserializeAnonymousType(mes, new BitMexMyOrders());

                                if (MyTradeEvent != null && 
                                    myOrder.data.Count != 0
                                    && 
                                    (myOrder.data[0].execType == "Trade"
                                    || myOrder.data[0].execType == "New"
                                    || myOrder.data[0].execType == "Filled"))
                                {
                                    MyTradeEvent(myOrder);
                                }
                                continue;
                            }

                            if (mes.StartsWith(ordersStr))
                            {
                                var order = JsonConvert.DeserializeAnonymousType(mes, new BitMexOrder());

                                if (MyOrderEvent != null)
                                {
                                    MyOrderEvent(order);
                                }
                                continue;
                            }

                            if (mes.StartsWith(marginStr))
                            {
                                var portf = JsonConvert.DeserializeAnonymousType(mes, new BitMexPortfolio());

                                if (UpdatePortfolio != null)
                                {
                                    UpdatePortfolio(portf);
                                }
                                continue;
                            }

                            if (mes.StartsWith(positionsStr))
                            {
                                var pos = JsonConvert.DeserializeAnonymousType(mes, new BitMexPosition());

                                if (UpdatePosition != null)
                                {
                                    UpdatePosition(pos);
                                }
                                continue;
                            }

                            if (mes.StartsWith(marketDepthStr))
                            {
                                var quotes = JsonConvert.DeserializeAnonymousType(mes, new BitMexQuotes());

                                if (UpdateMarketDepth != null && quotes.data.Count != 0 && quotes.data != null)
                                {
                                    UpdateMarketDepth(quotes);
                                }
                                continue;
                            }

                            if (mes.StartsWith(tradesStr))
                            {
                                var trade = JsonConvert.DeserializeAnonymousType(mes, new BitMexTrades());

                                if (NewTradesEvent != null)
                                {
                                    NewTradesEvent(trade);
                                }
                                continue;
                            }

                            if (mes.Contains("error"))
                            {
                                if (ErrorEvent != null)
                                {
                                    ErrorEvent(mes);
                                }
                            }
                        }

                    }
                    else
                    {
                        Thread.Sleep(1);
                    }
                }
                catch (Exception exception)
                {
                    if (BitMexLogMessageEvent != null)
                    {
                        BitMexLogMessageEvent(exception.ToString(), LogMessageType.Error);
                    }
                }
            }
        }

19 Source : BitMexClient.cs
with Apache License 2.0
from AlexWan

public string CreateQuery(string method, string function, Dictionary<string, string> param = null, bool auth = false)
        {
            lock (_queryHttpLocker)
            {
                //Wait for RateGate
                _rateGate.WaitToProceed();

                string paramData = BuildQueryData(param);
                string url = "/api/v1" + function + ((method == "GET" && paramData != "") ? "?" + paramData : "");
                string postData = (method != "GET") ? paramData : "";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_domain + url);
                webRequest.Method = method;

                if (auth)
                {
                    string nonce = GetNonce().ToString();
                    string message = method + url + nonce + postData;
                    byte[] signatureBytes = Hmacsha256(Encoding.UTF8.GetBytes(_secKey), Encoding.UTF8.GetBytes(message));
                    string signatureString = ByteArrayToString(signatureBytes);

                    webRequest.Headers.Add("api-nonce", nonce);
                    webRequest.Headers.Add("api-key", _id);
                    webRequest.Headers.Add("api-signature", signatureString);
                }

                try
                {
                    if (postData != "")
                    {
                        webRequest.ContentType = "application/x-www-form-urlencoded";
                        var data = Encoding.UTF8.GetBytes(postData);
                        using (var stream = webRequest.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }
                    }

                    using (WebResponse webResponse = webRequest.GetResponse())
                    using (Stream str = webResponse.GetResponseStream())
                    using (StreamReader sr = new StreamReader(str))
                    {
                        return sr.ReadToEnd();
                    }
                }
                catch (WebException wex)
                {
                    using (HttpWebResponse response = (HttpWebResponse)wex.Response)
                    {
                        if (response == null)
                            throw;

                        using (Stream str = response.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(str))
                            {
                                string error = sr.ReadToEnd();

                                if (ErrorEvent != null)
                                {
                                    ErrorEvent(error);
                                }
                                return sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }

19 Source : OsMinerServer.cs
with Apache License 2.0
from AlexWan

private void SendLogMessage(string message)
        {
            if (LogMessageEvent != null)
            {
                LogMessageEvent(message);
            }
        }

19 Source : TransaqClient.cs
with Apache License 2.0
from AlexWan

public void Converter()
        {
            while (true)
            {
                try
                {
                    if (_isDisposed)
                    {
                        return;
                    }

                    if (!_newMessage.IsEmpty)
                    {
                        string data;

                        if (_newMessage.TryDequeue(out data))
                        {
                            if (data.StartsWith("<pits>"))
                            {
                                continue;
                            }

                            if (data.StartsWith("<sec_info_upd>"))
                            {
                                if (!_loadSecInfoUpdate)
                                {
                                    continue;
                                }
                                _securityInfos.Add(data);
                                continue;
                            }
                            else if (data.StartsWith("<securities>"))
                            {
                                UpdatePairs?.Invoke(data);
                            }
                            else if (data.StartsWith("<quotes>"))
                            {
                                var quotes = _deserializer.Deserialize<List<Quote>>(new RestResponse() { Content = data });

                                UpdateMarketDepth?.Invoke(quotes);
                            }
                            else if (data.StartsWith("<trades>"))
                            {
                                var myTrades = _deserializer.Deserialize<List<Trade>>(new RestResponse() { Content = data });

                                MyTradeEvent?.Invoke(myTrades);
                            }
                            else if (data.StartsWith("<alltrades>"))
                            {
                                var allTrades = _deserializer.Deserialize<List<Trade>>(new RestResponse() { Content = data });

                                NewTradesEvent?.Invoke(allTrades);
                            }
                            else if (data.StartsWith("<mc_portfolio"))
                            {
                                UpdatePortfolio?.Invoke(data);
                            }
                            else if (data.StartsWith("<positions"))
                            {
                                var positions = Deserialize<TransaqPositions>(data);

                                UpdatePositions?.Invoke(positions);
                            }
                            else if (data.StartsWith("<clientlimits"))
                            {
                                var limits = Deserialize<ClientLimits>(data);

                                UpdateClientLimits?.Invoke(limits);
                            }
                            else if (data.StartsWith("<client"))
                            {
                                var clientInfo = _deserializer.Deserialize<Client>(new RestResponse() { Content = data });

                                ClientsInfo?.Invoke(clientInfo);
                            }
                            else if (data.StartsWith("<orders>"))
                            {
                                var orders = _deserializer.Deserialize<List<Order>>(new RestResponse() { Content = data });

                                MyOrderEvent?.Invoke(orders);
                            }
                            else if (data.StartsWith("<candles"))
                            {
                                Candles newCandles = Deserialize<Candles>(data);

                                NewCandles?.Invoke(newCandles);
                            }
                            else if (data.StartsWith("<messages>"))
                            {
                                if (data.Contains("Время действия Вашего пароля истекло"))
                                {
                                    NeedChangePreplacedword?.Invoke();
                                }
                            }
                            else if (data.StartsWith("<server_status"))
                            {
                                UpdateSecurity?.Invoke(_securityInfos);

                                ServerStatus status = Deserialize<ServerStatus>(data);

                                if (status.Connected == "true")
                                {
                                    IsConnected = true;
                                    Connected?.Invoke();
                                }
                                else if (status.Connected == "false")
                                {
                                    IsConnected = false;
                                    Disconnected?.Invoke();
                                }
                                else if (status.Connected == "error")
                                {
                                    SendLogMessage(status.Text, LogMessageType.Error);
                                }
                            }
                            else if (data.StartsWith("<error>"))
                            {
                                SendLogMessage(data, LogMessageType.Error);
                            }
                        }
                    }
                }

                catch (Exception exception)
                {
                    SendLogMessage(exception.ToString(), LogMessageType.Error);
                }
                Thread.Sleep(1);
            }
        }

19 Source : TcpServer.cs
with Apache License 2.0
from AlexWan

protected internal void HandleClientMessage(string message)
        {
            if (message.StartsWith("reboot_"))
            {
                var id = message.Replace("reboot_", "");
                ClientNeedRebootEvent?.Invoke(id);
            }
        }

19 Source : LicenseManager.cs
with Apache License 2.0
from Algoryx

public static bool GenerateEncryptedRuntime( int runtimeLicenseId,
                                                 string runtimeLicensePreplacedword,
                                                 string applicationRootDirectory,
                                                 string referenceApplicationFile,
                                                 Action<string> onSuccess = null )
    {
      if ( !Directory.Exists( applicationRootDirectory ) ) {
        Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
                        $"application root directory \"{applicationRootDirectory}\" doesn't exist." );
        return false;
      }

      if ( !Path.IsPathRooted( applicationRootDirectory ) ) {
        Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
                        $"application root directory \"{applicationRootDirectory}\" isn't rooted." );
        return false;
      }

      var absolutePathToReferenceFile = $"{applicationRootDirectory}/{referenceApplicationFile}".Replace( '\\', '/' );
      if ( !File.Exists( absolutePathToReferenceFile ) ) {
        Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
                        $"reference file \"{referenceApplicationFile}\" doesn't exist relative to \"{applicationRootDirectory}\"." );
        return false;
      }

      try {
        agxIO.Environment.instance().getFilePath( agxIO.Environment.Type.RESOURCE_PATH ).pushbackPath( applicationRootDirectory );
        var encrypted = agx.Runtime.instance().encryptRuntimeActivation( runtimeLicenseId,
                                                                         runtimeLicensePreplacedword,
                                                                         referenceApplicationFile );
        agxIO.Environment.instance().getFilePath( agxIO.Environment.Type.RESOURCE_PATH ).removeFilePath( applicationRootDirectory );

        if ( !string.IsNullOrEmpty( encrypted ) ) {
          // Fall-back directory is application root but we'll try to find
          // the AGX Dynamics binaries and place it there if applicationRootDirectory
          // is part of the resources of AGX Dynamics.
          var licenseTargetDirectory = Directory.GetFiles( applicationRootDirectory,
                                                           "agxPhysics.dll",
                                                           SearchOption.AllDirectories ).Select( file => new FileInfo( file ).Directory.FullName ).FirstOrDefault() ??
                                       applicationRootDirectory;

          var encryptedFilename = $"{licenseTargetDirectory}/agx{s_runtimeActivationExtension}".Replace( '\\', '/' );

          File.WriteAllText( encryptedFilename, encrypted );

          onSuccess?.Invoke( encryptedFilename );

          return true;
        }

        Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
                        $"encryption failed with status: {agx.Runtime.instance().getStatus()}" );
      }
      catch ( System.Exception e ) {
        Debug.LogError( "AGXUnity.LicenseManager: Exception occurred during generate of encrypted runtime " +
                        $"for application root \"{applicationRootDirectory}\"." );
        Debug.LogException( e );
      }

      return false;
    }

19 Source : Relay.cs
with MIT License
from AliFlux

public void notify(string json)
        {
            control.Invoke((MethodInvoker)delegate {
                callback(json);
            });
        }

19 Source : Relay.cs
with MIT License
from AliFlux

public void notify(string json)
        {
            dispatcher.BeginInvoke((Action)(() =>
            {
                callback(json);
            }));
        }

19 Source : FileLogger.cs
with GNU General Public License v3.0
from Alois-xx

internal void RollOver()
        {
            string fileName = myFile.Name;
            myLog.Close();
            string dir = Path.GetDirectoryName(fileName);
            string ext = Path.GetExtension(fileName);
            string basename = Path.GetFileNameWithoutExtension(fileName);
            string newFileName = Path.Combine(dir, $"{basename}_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}{ext}");
            File.Move(fileName, newFileName);
            string[] files = Directory.GetFiles(myLoggingDirectory, $"{Path.GetFileNameWithoutExtension(myFileBaseName)}*{Path.GetExtension(myFileBaseName)}");
            string [] sortedByAgeDescending = files.Select(f => new FileInfo(f)).OrderByDescending(x => x.LastWriteTime).Select(x => x.FullName).ToArray();
            
            for(int i=myMaxGenerationsToKeep;i<sortedByAgeDescending.Length;i++)
            {
                try
                {
                    Delete(sortedByAgeDescending[i]);
                }
                catch(Exception)
                {

                }
            }

            ReopenFileAndWriteHeader();
        }

19 Source : Files.cs
with Apache License 2.0
from aloneguid

internal static void Log(string message)
      {
         if(!HasLogger)
            return;

         _logMessage(message);
      }

19 Source : Files.cs
with Apache License 2.0
from aloneguid

public static void SetLogger(Action<string> logMessage)
      {
         _logMessage = logMessage;

         if(_logMessage != null)
         {
            _logMessage("logger set");
         }
      }

19 Source : DMPS3TwoWaySerialDriver.cs
with GNU General Public License v3.0
from alvaroyurrita

private void LocalStart()
        {
            if (!localstarted)
            {
                localstarted = true;

                PresetStrings = new List<ComPortPresetStrings>();
                _ComPort.PropertyChanged += new ComPortPropertyEvent(_ComPort_PropertyChanged);
                _ComPort.ExtendedInformationChanged += new ComPortExtendedInformationEvent(_ComPort_ExtendedInformationChanged);
                var ProcessData = new ProcessedReceivedData(PresetStrings, _delimiter);
                ProcessData.rx_Changed += rxData => { if (rx_Changed != null) rx_Changed(rxData); };
                ProcessData.PresetStringReceived += (PresetString, State) => { if (PresetStringReceived != null) PresetStringReceived(PresetString, State); };
                _ComPort.SerialDataReceived += new ComPortDataReceivedEvent(ProcessData._ComPort_SerialDataReceived);
            }
        }

19 Source : ProcessedReceivedData.cs
with GNU General Public License v3.0
from alvaroyurrita

public void _ComPort_SerialDataReceived(ComPort ReceivingComPort, ComPortSerialDataEventArgs args)
        {
            ReceiveDataBuffer.Append(args.SerialData);
            if (rx_Changed != null) rx_Changed(args.SerialData);
            CriticalProcessingReceivedData.Enter();
            try
            {
                string delimiter = _delimiter.ToString();
                string CompareBuffer = ReceiveDataBuffer.ToString();
                foreach (var cmd in PresetStrings)
                {
                    if (CompareBuffer.EndsWith(cmd.Command + delimiter))
                    {
                        if (!cmd.Active)
                        {
                            if (PresetStringReceived != null)
                            {
                                cmd.Active = true;
                                PresetStringReceived(cmd, cmd.Active);
                            }
                        }
                    }
                    else
                    {
                        if (cmd.Active)
                        {
                            if (PresetStringReceived != null)
                            {
                                cmd.Active = false;
                                PresetStringReceived(cmd, cmd.Active);
                            }
                        }
                    }
                }
                if (ReceiveDataBuffer.Length > 400) ReceiveDataBuffer.Remove(0, 256);
            }
            catch (Exception e)
            {
                ErrorLog.Error("Error Processsing Data Received - {0}", e.Message);
            }
            CriticalProcessingReceivedData.Leave();
        }

19 Source : RS232OnlyTwoWaySerialDriver.cs
with GNU General Public License v3.0
from alvaroyurrita

private void LocalStart()
        {
            if (!localstarted)
            {
                localstarted = true;

                PresetStrings = new List<ComPortPresetStrings>();
                var ProcessData = new ProcessedReceivedData(PresetStrings, _delimiter);
                ProcessData.rx_Changed += rxData => { if (rx_Changed != null) rx_Changed(rxData); };
                ProcessData.PresetStringReceived += (PresetString, State) => { if (PresetStringReceived != null) PresetStringReceived(PresetString, State); };
                _ComPort.SerialDataReceived += new ComPortDataReceivedEvent(ProcessData._ComPort_SerialDataReceived);
            }
        }

19 Source : ServerForm.cs
with MIT License
from AmazingDM

protected void CreateComboBox(string name, string remark, List<string> values, Action<string> save, string value, int width = InputBoxWidth)
        {
            _controlLines++;

            var comboBox = new ComboBox
            {
                Location = new Point(120, ControlLineHeight * _controlLines),
                Name = $"{name}ComboBox",
                Size = new Size(width, 23),
                DrawMode = DrawMode.OwnerDrawFixed,
                DropDownStyle = ComboBoxStyle.DropDownList,
                FormattingEnabled = true
            };
            comboBox.Items.AddRange(values.ToArray());
            comboBox.SelectedIndex = values.IndexOf(value);
            comboBox.DrawItem += Utils.Utils.DrawCenterComboBox;
            _saveActions.Add(comboBox, o => save.Invoke((string) o));
            ConfigurationGroupBox.Controls.AddRange(
                new Control[]
                {
                    comboBox,
                    new Label
                    {
                        AutoSize = true,
                        Location = new Point(10, ControlLineHeight * _controlLines),
                        Name = $"{name}Label",
                        Size = new Size(56, 17),
                        Text = remark
                    }
                }
            );
        }

19 Source : ModInputMenu.cs
with MIT License
from amazingalek

protected override void OnPopupConfirm()
		{
			base.OnPopupConfirm();
			OnConfirm?.Invoke(_inputMenu.GetInputText());
		}

19 Source : ServerForm.cs
with MIT License
from AmazingDM

protected void CreateTextBox(string name, string remark, Func<string, bool> check, Action<string> save, string value, int width = InputBoxWidth)
        {
            _controlLines++;

            var textBox = new TextBox
            {
                Location = new Point(120, ControlLineHeight * _controlLines),
                Name = $"{name}TextBox",
                Size = new Size(width, 23),
                TextAlign = HorizontalAlignment.Center,
                Text = value
            };
            _checkActions.Add(textBox, check);
            _saveActions.Add(textBox, o => save.Invoke((string) o));
            ConfigurationGroupBox.Controls.AddRange(
                new Control[]
                {
                    textBox,
                    new Label
                    {
                        AutoSize = true,
                        Location = new Point(10, ControlLineHeight * _controlLines),
                        Name = $"{name}Label",
                        Size = new Size(56, 17),
                        Text = remark
                    }
                }
            );
        }

19 Source : DeviceImageLoadContext.cs
with MIT License
from ancientproject

private void log(string s) => _trace($"[image-load-context] {s}");

19 Source : DeviceLoader.cs
with MIT License
from ancientproject

private static void trace(string str) => OnTrace?.Invoke(str);

19 Source : State.cs
with MIT License
from ancientproject

private void trace(string str)
        {
            if(tc) WriteLine(str);
            OnTrace?.Invoke(str);
        }

19 Source : State.cs
with MIT License
from ancientproject

private void Error(string str)
        {
            OnError?.Invoke(str);
            if (!ec) return;
            ForegroundColor = ConsoleColor.Red;
            WriteLine(str);
            ForegroundColor = ConsoleColor.White;
        }

19 Source : LocationService.cs
with GNU Lesser General Public License v3.0
from andisturber

public void PrintMessage(string msg)
        {
            PrintMessageEvent?.Invoke(msg);
        }

19 Source : UdpReceiver.cs
with MIT License
from AndreiMisiukevich

internal bool TryRun(out int port)
        {
            lock (_lockObject)
            {
                port = -1;
                Stop();
                foreach (var possiblePort in Enumerable.Range(15000, 2).Union(Enumerable.Range(17502, 200)))
                {
                    try
                    {
                        _udpClient = new UdpClient(possiblePort, AddressFamily.InterNetwork) { EnableBroadcast = true };
                        _udpTokenSource = new CancellationTokenSource();
                        var token = _udpTokenSource.Token;
                        Task.Run(() =>
                        {
                            while (!token.IsCancellationRequested)
                            {
                                try
                                {
                                    var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                                    var bytes = _udpClient.Receive(ref remoteEndPoint);

                                    if (!token.IsCancellationRequested && (bytes?.Any() ?? false))
                                    {
                                        var message = Encoding.ASCII.GetString(bytes);
                                        Received?.Invoke(message);
                                    }
                                }
                                catch
                                {
                                    if (token.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                }
                            }
                        });
                        port = possiblePort;
                        return true;
                    }
                    catch
                    {
                        continue;
                    }
                }
                return false;
            }
        }

19 Source : FileObserver.cs
with MIT License
from AndreiMisiukevich

internal async void StartAsync()
        {
            lock (_lockObject)
            {
                _udpClient = new UdpClient(_port);
                _udpTokenSource?.Cancel();
                _udpTokenSource = new CancellationTokenSource();
            }

            var token = _udpTokenSource.Token;
            while (!token.IsCancellationRequested)
            {
                var receivedResult = _udpClient != null
                    ? await _udpClient.ReceiveAsync().ConfigureAwait(false)
                    : default(UdpReceiveResult);

                var bytes = receivedResult.Buffer;

                if (!token.IsCancellationRequested &&
                    bytes != null &&
                    bytes.Any())
                {
                    var message = Encoding.ASCII.GetString(bytes);
                    Received?.Invoke(message);
                }
            }
        }

19 Source : BaseOpenTokService.cs
with MIT License
from AndreiMisiukevich

protected void RaiseError(string message) => Error?.Invoke(message);

19 Source : BaseOpenTokService.cs
with MIT License
from AndreiMisiukevich

protected void RaiseMessageReceived(string message) 
            => MessageReceived?.Invoke(message);

19 Source : ModelSaberAPI.cs
with MIT License
from andruzzzhka

public static IEnumerator DownloadAvatarCoroutine(string hash)
        {
            queuedAvatars.Add(hash);
            string downloadUrl = "";
            string avatarName = "";
            UnityWebRequest www = SongDownloader.GetRequestForUrl("https://modelsaber.com/api/v1/avatar/get.php?filter=hash:" + hash);

            www.timeout = 10;

            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
                Plugin.log.Error($"Unable to download avatar! {(www.isNetworkError ? $"Network error: " + www.error : (www.isHttpError ? $"HTTP error: " + www.error : "Unknown error"))}");
                queuedAvatars.Remove(hash);
                yield break;
            }
            else
            {
                Plugin.log.Debug("Received response from ModelSaber...");
                JSONNode node = JSON.Parse(www.downloadHandler.text);

                if (node.Count == 0)
                {
                    Plugin.log.Error($"Avatar with hash {hash} doesn't exist on ModelSaber!");
                    cachedAvatars.Add(hash, null);
                    queuedAvatars.Remove(hash);
                    yield break;
                }

                var tags = node[0]["tags"].AsArray;
                bool isNSFW = false;


                foreach(var child in tags.Values)
                {
                    if(child.Value == "NSFW")
                    {
                        isNSFW = true;
                    }
                }

                if (isNSFW && !Config.Instance.DownloadNSFWAvatars)
                {
                    Plugin.log.Error($"The avatar is NSFW!");
                    queuedAvatars.Remove(hash);
                    nsfwAvatars.Add(hash);
                    yield break;
                }

                downloadUrl = node[0]["download"].Value;
                avatarName = downloadUrl.Substring(downloadUrl.LastIndexOf("/") + 1);
            }

            if (string.IsNullOrEmpty(downloadUrl))
            {
                queuedAvatars.Remove(hash);
                yield break;
            }


            bool timeout = false;
            float time = 0f;
            UnityWebRequestAsyncOperation asyncRequest;

            try
            {
                www = SongDownloader.GetRequestForUrl(downloadUrl);
                www.timeout = 0;

                asyncRequest = www.SendWebRequest();
            }
            catch (Exception e)
            {
                Plugin.log.Error($"Unable to download avatar! Exception: {e}");
                queuedAvatars.Remove(hash);
                yield break;
            }

            while (!asyncRequest.isDone)
            {
                yield return null;

                time += Time.deltaTime;

                if ((time >= 5f && asyncRequest.progress <= float.Epsilon))
                {
                    www.Abort();
                    timeout = true;
                    Plugin.log.Error("Connection timed out!");
                }
            }


            if (www.isNetworkError || www.isHttpError || timeout)
            {
                queuedAvatars.Remove(hash);
                Plugin.log.Error("Unable to download avatar! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
            }
            else
            {
                Plugin.log.Debug("Received response from ModelSaber...");
                string docPath = "";
                string customAvatarPath = "";

                byte[] data = www.downloadHandler.data;

                try
                {
                    docPath = Application.dataPath;
                    docPath = docPath.Substring(0, docPath.Length - 5);
                    docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
                    customAvatarPath = docPath + "/CustomAvatars/" + avatarName;

                    Plugin.log.Debug($"Saving avatar to \"{customAvatarPath}\"...");

                    File.WriteAllBytes(customAvatarPath, data);

                    Plugin.log.Debug("Downloaded avatar!");
                    Plugin.log.Debug($"Loading avatar...");

                    SharedCoroutineStarter.instance.StartCoroutine(LoadedAvatar.FromFileCoroutine(avatarName,
                        (LoadedAvatar avatar) =>
                        {
                            queuedAvatars.Remove(hash);
                            cachedAvatars.Add(hash, avatar);
                            avatarDownloaded?.Invoke(hash);
                        }, (Exception ex) =>
                        {
                            Plugin.log.Error($"Unable to load avatar! Exception: {ex}");
                            queuedAvatars.Remove(hash);
                        }));


                }
                catch (Exception e)
                {
                    Plugin.log.Critical(e);
                    queuedAvatars.Remove(hash);
                    yield break;
                }
            }
        }

19 Source : Settings.cs
with MIT License
from andruzzzhka

public void UpdateMicrophoneList(bool deviceWasChanged)
        {
            micSelectOptions.Clear();
            micSelectOptions.Add("DEFAULT MIC");
            foreach (var mic in Microphone.devices)
            {
                micSelectOptions.Add(mic);
            }

            if (micSelectSetting)
            {
                micSelectSetting.tableView.ReloadData();
                micSelectSetting.ReceiveValue();
            }

            voiceChatMicrophoneChanged?.Invoke(Config.Instance.VoiceChatMicrophone);
        }

19 Source : SongSelectionViewController.cs
with MIT License
from andruzzzhka

[UIAction("search-pressed")]
        public void SearchStartPressed(string value)
        {
            SelectTopButtons(TopButtonsState.Select);
            _searchKeyboard.modalView.Hide(true);
            SearchPressed?.Invoke(value);
        }

19 Source : MorePlaylistsFlowCoordinator.cs
with MIT License
from andruzzzhka

public IEnumerator DownloadPlaylistFile(string url, Action<string> playlistDownloaded)
        {
            yield return null;

            UnityWebRequest www = UnityWebRequest.Get(url);
            www.timeout = 15;
            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
                Plugin.log.Error($"Unable to connect to BeastSaber playlist API! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
                playlistDownloaded?.Invoke(null);
            }
            else
            {
                try
                {
                    string docPath = Application.dataPath;
                    docPath = docPath.Substring(0, docPath.Length - 5);
                    docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
                    File.WriteAllText(docPath + "/Playlists/"+ Path.GetFileName(www.uri.LocalPath), www.downloadHandler.text);
                    playlistDownloaded?.Invoke(docPath + "/Playlists/" + Path.GetFileName(www.uri.LocalPath));
                }
                catch (Exception e)
                {
                    Plugin.log.Critical("Unable to parse response! Exception: " + e);
                    playlistDownloaded?.Invoke(null);
                }
            }
        }

19 Source : SearchKeyboardViewController.cs
with MIT License
from andruzzzhka

protected override void DidActivate(bool firstActivation, ActivationType type)
        {
            if (type == ActivationType.AddedToHierarchy && firstActivation)
            {
                _searchKeyboardGO = Instantiate(Resources.FindObjectsOfTypeAll<UIKeyboard>().First(x => x.name != "CustomUIKeyboard"), rectTransform, false).gameObject;

                Destroy(_searchKeyboardGO.GetComponent<UIKeyboard>());
                _searchKeyboard = _searchKeyboardGO.AddComponent<CustomUIKeyboard>();

                _searchKeyboard.textKeyWasPressedEvent += delegate (char input) { _inputString += input; UpdateInputText(); };
                _searchKeyboard.deleteButtonWasPressedEvent += delegate () { _inputString = _inputString.Substring(0, _inputString.Length - 1); UpdateInputText(); };
                _searchKeyboard.cancelButtonWasPressedEvent += () => { backButtonPressed?.Invoke(); };
                _searchKeyboard.okButtonWasPressedEvent += () => { searchButtonPressed?.Invoke(_inputString); };

                _inputText = BeatSaberUI.CreateText(rectTransform, "Search...", new Vector2(0f, 22f));
                _inputText.alignment = TextAlignmentOptions.Center;
                _inputText.fontSize = 6f;

            }
            else
            {
                _inputString = "";
                UpdateInputText();
            }

        }

19 Source : TextMeshProHyperlinkHandler.cs
with MIT License
from andruzzzhka

public void OnPointerClick(PointerEventData eventData)
        {
            TextMeshProUGUI textMesh = GetComponent<TextMeshProUGUI>();
            int linkIndex = TMP_TextUtilities.FindIntersectingLink(textMesh, eventData.pressPosition, Camera.main);
            if (linkIndex != -1)
            {
                TMP_LinkInfo linkInfo = textMesh.textInfo.linkInfo[linkIndex];
                linkClicked?.Invoke(linkInfo.GetLinkID());
            }
        }

19 Source : MorePlaylistsFlowCoordinator.cs
with MIT License
from andruzzzhka

public IEnumerator DownloadPlaylistFile(string url, Action<string> playlistDownloaded)
        {
            yield return null;

            UnityWebRequest www = UnityWebRequest.Get(url);
            www.timeout = 15;
            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
                Plugin.log.Error($"Unable to connect to BeastSaber playlist API! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
                playlistDownloaded?.Invoke(null);
            }
            else
            {
                try
                {
                    string docPath = Application.dataPath;
                    docPath = docPath.Substring(0, docPath.Length - 5);
                    docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
                    File.WriteAllText(docPath + "/Playlists/"+ Path.GetFileName(www.uri.LocalPath), www.downloadHandler.text);
                    playlistDownloaded?.Invoke(docPath + "/Playlists/" + Path.GetFileName(www.uri.LocalPath));
                }
                catch (Exception e)
                {
                    Plugin.log.Critical("Unable to parse response! Exception: " + e);
                    playlistDownloaded?.Invoke(null);
                }
            }
        }

19 Source : BaseEngine.cs
with MIT License
from angelsix

public void Dispose()
        {
            // Log the message
            if (mWatchers != null)
                Log($"{EngineName} Engine stopped");

            // Clean up all file watchers
            mWatchers?.ForEach(watcher =>
            {
                // Get extension
                var extension = watcher.Filter;

                // Dispose of watcher
                watcher.Dispose();

                // Inform listener
                StoppedWatching(extension);

                // Log the type
                LogTabbed("File Type", watcher.Filter, 1);
            });

            // Space between each engine log
            Log("");

            // Let listener know we stopped
            if (mWatchers != null)
                Stopped();

            // Clear watchers
            mWatchers = null;
        }

See More Examples