Serilog.Log.Warning(string)

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

58 Examples 7

19 Source : GridConverter.cs
with Microsoft Public License
from achimismaili

internal static List<FeatureParent> SelectedRowsToFeatureParent(DataGridViewSelectedRowCollection selectedRows)
        {
            if (selectedRows == null || selectedRows.Count == 1)
            {
                Log.Warning("No feature parents selected!");
                return null;
            }

            var convertedRows = new List<FeatureParent>();

            foreach (DataGridViewRow row in selectedRows)
            {
                FeatureParent fd = row.DataBoundItem as FeatureParent;
                convertedRows.Add(fd);
            }

            return convertedRows;
        }

19 Source : GridConverter.cs
with Microsoft Public License
from achimismaili

internal static List<ActivatedFeature> SelectedRowsToActivatedFeature(DataGridViewSelectedRowCollection selectedRows)
        {
            if (selectedRows == null || selectedRows.Count == 1)
            {
                Log.Warning("No activated features selected!");
                return null;
            }

            var convertedRows = new List<ActivatedFeature>();

            foreach (DataGridViewRow row in selectedRows)
            {
                ActivatedFeature fd = row.DataBoundItem as ActivatedFeature;
                convertedRows.Add(fd);
            }

            return convertedRows;
        }

19 Source : GridConverter.cs
with Microsoft Public License
from achimismaili

internal static List<ActivatedFeature> SelectedRowsToActivatedFeature(CheckedItemCollection selectedRows)
        {
            if (selectedRows == null || selectedRows.Count == 1)
            {
                Log.Warning("No activated features selected!");
                return null;
            }

            var convertedRows = new List<ActivatedFeature>();

            foreach (DataGridViewRow row in selectedRows)
            {
                ActivatedFeature fd = row.DataBoundItem as ActivatedFeature;
                convertedRows.Add(fd);
            }

            return convertedRows;
        }

19 Source : GridConverter.cs
with Microsoft Public License
from achimismaili

public static List<FeatureDefinition> SelectedRowsToFeatureDefinition(DataGridViewSelectedRowCollection selectedRows)
        {
            if (selectedRows == null || selectedRows.Count == 1)
            {
                Log.Warning("No feature definitions selected!");
                return null;
            }

            var convertedRows = new List<FeatureDefinition>();

            foreach (DataGridViewRow row in selectedRows)
            {
                FeatureDefinition fd = row.DataBoundItem as FeatureDefinition;
                convertedRows.Add(fd);
            }

            return convertedRows;
        }

19 Source : FeaturesListViewModel.cs
with Microsoft Public License
from achimismaili

private void backgroundWorker_RunWorkerCompletedFeatures(object sender,
            RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
              Log.Error( e.Error.Message);
            }
            else if (e.Cancelled)
            {
              Log.Warning( "Loading feature definitions cancelled");
            }
            else
            {

                var rawFeatures = e.Result as List<IFeatureDefinition>;

                PopulateObservableCollection(rawFeatures);

                // hard code 5% as progress, when feature definitions of a farm are loaded
                _eventAggregator.GetEvent<SetProgressBarEvent>()
               .Publish(5);

                var msg = string.Format("Loaded {0} Feature Definitions", Features.Count);

                _eventAggregator.GetEvent<SetStatusBarEvent>()
                .Publish(msg);

                Log.Information(msg);
                
            }
        }

19 Source : LocationsListViewModel.cs
with Microsoft Public License
from achimismaili

private void backgroundWorker_RunWorkerCompletedLocations(object sender,
            RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Log.Error(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                Log.Warning("Loading locations cancelled");
            }
            else
            {
                var loadedLocations = e.Result as List<LocationViewModel>;

                if (loadedLocations != null && loadedLocations.Any())
                {
                    foreach (LocationViewModel l in loadedLocations)
                    {
                        Locations.Add(l);
                    }
                }
            }
        }

19 Source : InMemoryDataBase.cs
with Microsoft Public License
from achimismaili

public void AddActivatedFeature(SPFeature feature)
        {
            if (feature == null)
            {
                return;
            }

            try
            {
                var activatedFeature = ActivatedFeature.GetActivatedFeature(feature);

                // update activated features
                this.ActivatedFeatures.Add(activatedFeature);


                // update featureDefinition (and its activated instances)
                var featureDef = this.FeatureDefinitions.FirstOrDefault(fd => fd.Id == activatedFeature.Id);

                if (featureDef != null)
                {
                    // add activated feature to feature definition
                    featureDef.ActivatedFeatures.Add(activatedFeature);
                }
                else
                {
                    // fyi - if we get here, we have most likely a group of faulty features ...

                    // create feature definition and add features
                    var newFeatureDef = FeatureDefinition.GetFeatureDefinition(activatedFeature);
                    this.FeatureDefinitions.Add(newFeatureDef);
                    Log.Warning("Unexpected - Feature Definition of activated Feature was not available - please Reload");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to add new feature to InMemorySharePointDb", ex);
            }

        }

19 Source : InMemoryDataBase.cs
with Microsoft Public License
from achimismaili

public void RemoveDeactivatedFeature(Guid featureId, Guid parentId)
        {
            try
            {
                // update activated features
                var deactivatedFeature = this.ActivatedFeatures.FirstOrDefault(f => f.Id == featureId && f.Parent.Id == parentId);

                if (deactivatedFeature != null)
                {
                    this.ActivatedFeatures.Remove(deactivatedFeature);
                }
                else
                {
                    Log.Warning("Unexpected - Deactivated Feature was not found in existing cached list of activated features - please Reload");
                }

                // update featureDefinition (and its activated instances)
                var featureDef = this.FeatureDefinitions.FirstOrDefault(fd => fd.Id == featureId);

                if (featureDef != null)
                {
                    // add activated feature to feature definition
                    featureDef.ActivatedFeatures.Remove(deactivatedFeature);
                }
                else
                {
                    Log.Warning("Unexpected - Deactivated Feature was not found in the activated instances of existing cached feature definition list - please Reload");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to remove deactivated feature from InMemorySharePointDb", ex);
            }

        }

19 Source : InMemoryDataBase.cs
with Microsoft Public License
from achimismaili

public void RemoveUninstalledFeatureDefinition(Guid featureId)
        {
            try
            {
                // update featureDefinition list
                var featureDef = this.FeatureDefinitions.FirstOrDefault(fd => fd.Id == featureId);

                if (featureDef != null)
                {
                    // add activated feature to feature definition
                    this.FeatureDefinitions.Remove(featureDef);
                }
                else
                {
                    Log.Warning("Unexpected - Feature Definition was not found in the cached feature definition list - please Reload");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to remove deactivated feature from InMemorySharePointDb", ex);
            }

        }

19 Source : NukiBridge2MqttLogic.cs
with Apache License 2.0
from bluewalk

private void Initialize(string mqttHost, int? mqttPort, string mqttRootTopic, string callbackAddress,
            int? callbackPort, string bridgeUrl, string token, bool hashToken, int? infoInterval)
        {
            _mqttRootTopic = !string.IsNullOrEmpty(mqttRootTopic) ? mqttRootTopic : "nukibridge";
            _mqttHost = !string.IsNullOrEmpty(mqttHost) ? mqttHost : "localhost";
            _mqttPort = mqttPort ?? 1883;

            _bridgeUrl = !string.IsNullOrEmpty(bridgeUrl) ? bridgeUrl : NukiBridgeClient.DiscoverBridge();
            _bridgeToken = token;

            if (string.IsNullOrEmpty(_bridgeUrl) ||
                string.IsNullOrEmpty(_bridgeToken))
                throw new Exception("No Bridge_URL and/or Bridge_Token defined");

            _hashToken = hashToken;

            // Setup MQTT
            _mqttClient = new MqttFactory().CreateManagedMqttClient();
            _mqttClient.UseApplicationMessageReceivedHandler(e => MqttClientOnApplicationMessageReceived(e));
            _mqttClient.UseConnectedHandler(e =>
            {
                Log.Information("MQTT: Connected");

                SubscribeTopic("discover");
                SubscribeTopic("reset");
                SubscribeTopic("reboot");
                SubscribeTopic("fw-upgrade");
            });
            _mqttClient.UseDisconnectedHandler(e =>
            {
                if (e.ClientWasConnected)
                    Log.Warning($"MQTT: Disconnected ({e.Exception?.Message ?? "clean"})");
                else
                    Log.Error($"MQTT: Unable to connect ({e.Exception?.Message ?? "clean"})");
            });

            _nukiBridgeClient = new NukiBridgeClient(_bridgeUrl, _bridgeToken, _hashToken);

            // Setup callback
            _callbackAddress = callbackAddress ?? LocalIpAddress().ToString();
            _callbackPort = callbackPort ?? 8080;
            
            _httpListener = new HttpListener
            {
                Prefixes = { $"http://+:{_callbackPort}/" }
            };

            _devices = new List<Device>();

            // Prevent info interval being set to 0
            if ((infoInterval ?? 0) == 0)
                infoInterval = 300;
                
            // Setup info interval
            _infoTimer = new Timer((infoInterval ?? 300) * 1000);
            _infoTimer.Elapsed += async (sender, args) =>
            {
                _infoTimer.Stop();
                await PublishBridgeInfo();
                _infoTimer.Start();
            };
        }

19 Source : NukiBridge2MqttLogic.cs
with Apache License 2.0
from bluewalk

private void MqttClientOnApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            var topic = e.ApplicationMessage.Topic.ToUpper().Split('/');
            var message = e.ApplicationMessage.ConvertPayloadToString();

            Log.Debug($"Received MQTT message for topic {e.ApplicationMessage.Topic}, Data: {message}");
#if DEBUG
            // Remove first part "dev"
            topic = topic.Skip(1).ToArray();
#endif
            /**
             * Topic[0] = _rootTopic
             * Topic[1] = {NukiId} | Discover
             * Topic[2] = Device-Action, Reset, Reboot, Fw-Upgrade, Callbacks
             */
            try
            {
                switch (topic[1])
                {
                    case "DISCOVER": 
                        DiscoverLocks();
                        break;
                    case "RESET":
                        _nukiBridgeClient.FactoryReset();
                        break;
                    case "REBOOT":
                        _nukiBridgeClient.Reboot();
                        break;
                    case "FW-UPGRADE":
                        _nukiBridgeClient.FwUpdate();
                        break;
                    case "CALLBACKS":
                        InitializeCallback();
                        break;

                    default:
                        var device = _devices.FirstOrDefault(l =>
                            l.NukiId.ToString().Equals(topic[1]) || l.NameMqtt.Equals(topic[1],
                                StringComparison.InvariantCultureIgnoreCase));
                        if (device == null) return;

                        switch (topic[2])
                        {
                            case "DEVICE-ACTION":
                                Enum.TryParse(message, true, out LockActionEnum action);
                                if (action == LockActionEnum.Unspecified) return;

                                _nukiBridgeClient.LockAction(device.NukiId, device.DeviceType, action);
                                break;

                            default:
                                Log.Warning($"MQTT: {topic[2]} is not a valid device topic");
                                break;
                        }

                        break;
                }
            }
            catch (Exception ex)
            {
                Log.Error($"An error occurred processing the MQTT message (Topic {e.ApplicationMessage.Topic}, Message: {message}", ex);
            }
        }

19 Source : EventLogListener.cs
with MIT License
from c0shea

private void SendRetroactiveEntries()
        {
            try
            {
                using (var eventLog = OpenEventLog())
                {
                    Serilog.Log.Information("Processing {EntryCount} retroactive entries in {LogName}", eventLog.Entries.Count, LogName);

                    foreach (EventLogEntry entry in eventLog.Entries)
                    {
                        if (_cancel.IsCancellationRequested)
                        {
                            Serilog.Log.Warning("Canceling retroactive event loading");
                            return;
                        }

                        HandleEventLogEntry(entry, eventLog.Log).GetAwaiter().GetResult();
                    }
                }
            }
            catch (Exception ex)
            {
                Serilog.Log.Error(ex, "Failed to send retroactive entries in {LogName} on {MachineName}", LogName, MachineName ?? ".");
            }
        }

19 Source : LogWriter.cs
with GNU General Public License v3.0
from dd-bim

public static void WriteLogFile(List<LogPair> messages, bool solid, double all, double success, double? error, double? errorLod1, double? fatalError)
        {
            //string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "City2BIM");
            //string name = "Log_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

            //string path = Path.Combine(folder, name);

            //if (!Directory.Exists(folder))
            //    Directory.CreateDirectory(folder);

            //Serilog.Core.Logger result = new LoggerConfiguration().WriteTo.File(path).CreateLogger();

            //  !!!!!!!!!!!!!!!!!!!!!!!!!!!
            //  The function requires a serilog logger set up at a different place!
            //  !!!!!!!!!!!!!!!!!!!!!!!!!!!

            Log.Information("Log-Protocol for CityGML-Import to BIM");
            Log.Information("--------------------------------------------------");

            if (solid)
            {
                Log.Information("Kind of transfered geometry: Solids");
                Log.Information("Calculation parameters");
                Log.Information("----------------------");

                Log.Information("Equal Point distance = " + Math.Sqrt(City2BIM_prop.EqualPtSq) + " m.");
                Log.Information("Equal Planes normal distance (normal length 1m) = " + Math.Sqrt(City2BIM_prop.EqualPlSq) + " m.");
                Log.Information("Maximum deviation between calculated point and original point (if applicable) = " + Math.Sqrt(City2BIM_prop.MaxDevPlaneCutSq) + " m.");

                Log.Information("----------------------");
                Log.Information("----------------------");
            }
            else
                Log.Information("Kind of transfered geometry: Surfaces");

            Log.Information("Statistic");
            Log.Information("----------------------");

            double statSucc = success / all * 100;

            Log.Information("Amount of Solids or Surfaces: " + all);
            Log.Information("Success rate = " + statSucc + " percent = " + success + " objects");

            if (error.HasValue)
            {
                double statErr = (double)error / all * 100;
                Log.Warning("Failure rate (LOD1, correct contour) = " + statErr + " percent = " + error + " objects");
            }

            if (errorLod1.HasValue)
            {
                double statErr = (double)errorLod1 / all * 100;
                Log.Warning("Failure rate (LOD1 Fallback, convex hull contour) = " + statErr + " percent = " + errorLod1 + " objects");
            }

            if (fatalError.HasValue)
            {
                double fatStatErr = (double)fatalError / all * 100;
                Log.Error("Fatal error: no geometry at = " + fatStatErr + " percent = " + fatalError + " objects");
            }
            Log.Information("----------------------");
            Log.Information("----------------------");

            Log.Information("Protocol for each Building(Part)");
            Log.Information("-------------------------------------");


            foreach (var log in messages)
            {
                switch (log.Type)
                {
                    case (LogType.error):
                        {
                            Log.Error(log.Message);
                            break;
                        }
                    case (LogType.warning):
                        {
                            Log.Warning(log.Message);
                            break;
                        }
                    case (LogType.info):
                        {
                            Log.Information(log.Message);
                            break;
                        }
                }
            }
        }

19 Source : Cmd_properties.cs
with GNU General Public License v3.0
from dd-bim

public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDoreplacedent uiDoc = commandData.Application.ActiveUIDoreplacedent;
            Doreplacedent doc = uiDoc.Doreplacedent;

            Prop_GeoRefSettings.SetInitialSettings(doc);

            try
            {
                Selection sel = uiDoc.Selection;
                ICollection<ElementId> selectedIds = sel.GetElementIds();

                if (selectedIds.Count != 1)
                {
                    Log.Warning("ManageProperties: to much or to less elements were selected. nr of selected elements: " + selectedIds.Count);
                    TaskDialog.Show("Hint", "Please only select one element for which custom attribtes should be shown!");
                }
                else
                {
                    var firstElemId = selectedIds.First();
                    Element pickedElement = doc.GetElement(firstElemId);

                    var schemaGUIDS = pickedElement.GetEnreplacedySchemaGuids();

                    Dictionary<string, Dictionary<string, string>> schemaAndAttrDict = new Dictionary<string, Dictionary<string, string>>();

                    foreach (var schemaGUID in schemaGUIDS)
                    {
                        var currentSchema = Schema.Lookup(schemaGUID);
                        if (currentSchema.SchemaName == "ExternalDataCatalogSchema")
                        {
                            continue;
                        }

                        Enreplacedy ent = pickedElement.GetEnreplacedy(currentSchema);

                        Dictionary<string, string> schemaAttributes = new Dictionary<string, string>();
                        foreach (var currentField in currentSchema.ListFields())
                        {
                            schemaAttributes.Add(currentField.FieldName, ent.Get<string>(currentField));
                        }
                        schemaAndAttrDict.Add(currentSchema.SchemaName, schemaAttributes);
                    }

                    var propUI = new PropertyWindow(schemaAndAttrDict);

                    propUI.ShowDialog();

                    if (propUI.saveChanges)
                    {
                        using (Transaction trans = new Transaction(doc, "Update Schema Information"))
                        {
                            trans.Start();
                            var modified = propUI.data;
                            foreach (var schemaGUID in schemaGUIDS)
                            {
                                var currentSchema = Schema.Lookup(schemaGUID);
                                Enreplacedy ent = pickedElement.GetEnreplacedy(currentSchema);

                                ObservableCollection<AttributeContainer> currentCollection = modified[currentSchema.SchemaName];
                                var fieldList = currentSchema.ListFields();

                                foreach (AttributeContainer attrCont in currentCollection)
                                {
                                    var currentField = from field in fieldList
                                                       where field.FieldName.Equals(attrCont.attrName)
                                                       select field;

                                    ent.Set<string>(currentField.FirstOrDefault(), attrCont.attrValue);
                                }

                                pickedElement.SetEnreplacedy(ent);
                            }
                            trans.Commit();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                TaskDialog.Show("Exception", e.ToString());
                return Result.Failed;
            }

            return Result.Succeeded;

        }

19 Source : Cmd_ReadTerrain.cs
with GNU General Public License v3.0
from dd-bim

public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            //get revit doreplacedent
            Doreplacedent doc = revit.Application.ActiveUIDoreplacedent.Doreplacedent;

            //get georef settings based on revit doreplacedent
            Prop_GeoRefSettings.SetInitialSettings(doc);

            //init user controler (otherwise will not be able to init the window)
            uC.Dxf.Read ucDxf = new uC.Dxf.Read();
            uC.Grid.Read ucGrid = new uC.Grid.Read();
            uC.Reb.Read ucReb = new uC.Reb.Read();
            uC.Grafbat.Read ucGrafbat = new uC.Grafbat.Read();
            uC.XML.Read ucXml = new uC.XML.Read();
            uC.PostGIS.Read ucPostGIS = new uC.PostGIS.Read();
            uC.GeoJSON.Read ucGeoJson = new uC.GeoJSON.Read();

            //init main window
            DTM2BIM.Terrain_ImportUI terrainUI = new DTM2BIM.Terrain_ImportUI();

            #region version handler
            //get current revit version
            utils.rvtVersion rvtVersion = utils.GetVersionInfo(doc.Application);

            BIMGISInteropLibs.IfcTerrain.Config config = new BIMGISInteropLibs.IfcTerrain.Config();

            string thisreplacedemblyPath = replacedembly.GetExecutingreplacedembly().Location;
            string logPath = Path.GetDirectoryName(thisreplacedemblyPath);

            //set logfile path
            config.logFilePath = logPath;

            if (rvtVersion.Equals(utils.rvtVersion.NotSupported))
            {
                //error mreplacedage
                TaskDialog.Show("Supported version", "The used Revit version is not supported!" + Environment.NewLine + "Processing failed!");
                
                return Result.Failed;
            }
            else
            {
                //
                Log.Debug(" Opening the settings for processing DTMs");

                //
                terrainUI.DataContext = config as BIMGISInteropLibs.IfcTerrain.Config;

                //show main window to user (start dialog for settings)
                terrainUI.ShowDialog();

                //get config from window
                config = terrainUI.DataContext as BIMGISInteropLibs.IfcTerrain.Config;

                if (!string.IsNullOrEmpty(config.logFilePath))
                {
                    LogWriter.initLogger(config);
                }
                else
                {
                    Log.Warning("Log file path has been empty! Set to: " + logPath);
                    config.logFilePath = logPath;
                    
                    LogWriter.initLogger(config);
                }
                Log.Information("RvtTerrain log file is stored under: " + Environment.NewLine + "'" + config.logFilePath + "'");
            }
            #endregion

            if(terrainUI.startTerrainImport)
            {
                Log.Debug("Start terrain processing...");

                //start mapping process
                var res = BIMGISInteropLibs.RvtTerrain.ConnectionInterface.mapProcess(config);

                //init surface builder
                var rev = new Builder.RevitTopoSurfaceBuilder(doc);

                if (res != null && config.rvtReadPoints.GetValueOrDefault())
                {
                    //create dtm (via points)
                    rev.createDTMviaPoints(res);
                }
                else if(res != null && !config.rvtReadPoints.GetValueOrDefault())
                {
                    //create dtm via points & faces
                    rev.createDTM(res);
                }
                else
                {
                    #region define task dialog
                    TaskDialog dialog = new TaskDialog("DTM processing");
                    dialog.MainIcon = TaskDialogIcon.TaskDialogIconError;
                    dialog.replacedle = "DTM processing failed!";
                    dialog.AllowCancellation = true;
                    dialog.MainInstruction = "Check log file!";
                    dialog.MainContent = "DTM processing failed - for more information check log file or try other settings. Want to open storage of log file?";
                    dialog.FooterText = "Error caused by RvtTerrain.";

                    //define "shown buttons"
                    dialog.CommonButtons =
                        TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;

                    //define pre selected button
                    dialog.DefaultButton = TaskDialogResult.Yes;
                    #endregion define task dialog

                    //open dialog
                    TaskDialogResult dialogResult = dialog.Show();

                    //react on dialog
                    if (dialogResult.Equals(TaskDialogResult.Yes))
                    {
                        if (Directory.Exists(Path.GetDirectoryName(config.logFilePath)))
                        {
                            System.Diagnostics.Process.Start("explorer.exe", config.logFilePath);
                        }
                    }
                    return Result.Failed;
                }

                //error handlings
                if (rev.terrainImportSuccesful)
                {
                    dynamic resLog;
                    
                    if (config.rvtReadPoints.GetValueOrDefault())
                    {
                        resLog = "Points: " + numPoints;
                    }
                    else
                    {
                        resLog = "Points: " + numPoints + " Faces: " + numFacets;
                    }
                    //show info dialog (may update to better solution)
                    TaskDialog.Show("DTM import", "DTM import finished! Result:" + Environment.NewLine + resLog);

                    //process successfuly
                    return Result.Succeeded;
                }
                else
                {
                    //TODO improve error message
                    TaskDialog.Show("DTM import failed!", "The DTM import failed.");

                    return Result.Failed;
                }
            }
            else
            {
                //user canceld / closed window
                return Result.Cancelled;
            }
        }

19 Source : MainMenuBar.cs
with MIT License
from Figglewatts

private void renderFileMenu()
        {
            if (ImGui.MenuItem("Open"))
            {
                _openFileOpenDialog = true;
            }

            if (ImGui.BeginMenu("Open Recent"))
            {
                if (_configController.Config.RecentFiles.Count > 0)
                {
                    string fileToOpen = null;
                    foreach (var recentFile in _configController.Config.RecentFiles)
                    {
                        try
                        {
                            var relPath = PathUtil.MakeRelative(recentFile,
                                _configController.Config.GameDataPath);
                            if (ImGui.MenuItem(relPath))
                            {
                                fileToOpen = recentFile;
                                break;
                            }
                        }
                        catch (UriFormatException e)
                        {
                            Log.Warning($"Invalid recent file: '{recentFile}', invalid URI: {e}");
                        }
                    }

                    if (fileToOpen != null) _fileOpenController.OpenFile(fileToOpen);
                }
                else
                {
                    ImGui.MenuItem("No recent files!");
                }

                ImGui.EndMenu();
            }

            ImGui.Separator();

            if (ImGui.MenuItem("Set game data path..."))
            {
                OpenSetGameDataPath();
            }
        }

19 Source : UpdateCheckerController.cs
with MIT License
from Figglewatts

public bool IsUpdateAvailable()
        {
            // if we're developing locally, always return false
            if (Version.String.Equals("#{VERSION}#")) return false;

            using (WebClient wc = new WebClient())
            {
                wc.Headers.Add("User-Agent", "LSDView");
                try
                {
                    var json = wc.DownloadString(UPDATE_API_URL);
                    dynamic releaseInfo = JObject.Parse(json);
                    string releaseName = releaseInfo.name;
                    return !Version.String.Equals(releaseName);
                }
                catch (WebException exception)
                {
                    Log.Warning($"Unable to check for update: {exception}");
                    return false;
                }
            }
        }

19 Source : ReaderMtgaOutputLogGreMatchToClient.cs
with MIT License
from ibiza240

public IEnumerable<IMtgaOutputLogPartResult> ParsePart(string part)
        {
            var match = regexMatchTo.Match(part);
            if (!match.Success)
            {
                Log.Warning($"Match to did not match expected pattern: {part}");
                return new[] { new UnknownResult() };
            }

            var playerId = match.Groups[1].Value;
            var messageType = match.Groups[2].Value;

            if (messageType == "AuthenticateResponse")
                return authenticateResponseConverter.ParsePart(part);

            var json = part.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1];
            return ParseJsonMulti(json);
        }

19 Source : GameCardInZone.cs
with MIT License
from ibiza240

public GameCardInZone MovedTo(int newInstId, OwnedZone destZone, int? grpId = null)
        {
            if (grpId != null && grpId != GrpId)
            {
                Log.Warning($"changing grpId from {GrpId} to {grpId} (instId {newInstId} (was {InstId}))");
            }
            return new GameCardInZone(newInstId, OwnerSeatId, destZone, grpId ?? GrpId, GameObjectType, Visibility, Card);
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

private static void CurrentDomainOnProcessExit(object sender, EventArgs eventArgs)
        {
            Log.Warning("Exiting process");
            ExitEvent.Set();
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

private static void DefaultOnUnloading(replacedemblyLoadContext replacedemblyLoadContext)
        {
            Log.Warning("Unloading process");
            ExitEvent.Set();
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

private static void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            Log.Warning("Canceling process");
            e.Cancel = true;
            ExitEvent.Set();
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

static void Main(string[] args)
        {
            InitLogging();

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            Console.WriteLine("|=======================|");
            Console.WriteLine("|     BITMEX CLIENT     |");
            Console.WriteLine("|=======================|");
            Console.WriteLine();

            Log.Debug("====================================");
            Log.Debug("   STARTING (full .NET Framework)   ");
            Log.Debug("====================================");


            var url = BitmexValues.ApiWebsocketUrl;
            using (var communicator = new BitmexWebsocketCommunicator(url))
            {
                using (var client = new BitmexWebsocketClient(communicator))
                {

                    client.Streams.InfoStream.Subscribe(info =>
                    {
                        Log.Information($"Reconnection happened, Message: {info.Info}, Version: {info.Version:D}");
                           
                        client.Send(new PingRequest()).Wait();
                        client.Send(new TradesSubscribeRequest("XBTUSD")).Wait();

                        if (!string.IsNullOrWhiteSpace(API_SECRET))
                            client.Send(new AuthenticationRequest(API_KEY, API_SECRET)).Wait();
                    });   

                    client.Streams.ErrorStream.Subscribe(x =>
                        Log.Warning($"Error received, message: {x.Error}, status: {x.Status}"));

                    client.Streams.AuthenticationStream.Subscribe(x =>
                    {
                        Log.Information($"Authentication happened, success: {x.Success}");
                        client.Send(new WalletSubscribeRequest()).Wait();
                        client.Send(new OrderSubscribeRequest()).Wait();
                        client.Send(new PositionSubscribeRequest()).Wait();
                    });

                    client.Streams.PongStream.Subscribe(x =>
                        Log.Information($"Pong received ({x.Message})"));


                    client.Streams.TradesStream.Subscribe(y =>
                       y.Data.ToList().ForEach(x => 
                           Log.Information($"Trade {x.Symbol} executed. Time: {x.Timestamp:mm:ss.fff}, Amount: {x.Size}, " +
                                           $"Price: {x.Price}, Direction: {x.TickDirection}"))
                        );

                    communicator.Start();
                    
                    ExitEvent.WaitOne();
                }
            }

            Log.Debug("====================================");
            Log.Debug("              STOPPING              ");
            Log.Debug("====================================");
            Log.CloseAndFlush();
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

static void Main(string[] args)
        {
            InitLogging();

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            Console.WriteLine("|=======================|");
            Console.WriteLine("|     BITMEX CLIENT     |");
            Console.WriteLine("|=======================|");
            Console.WriteLine();

            Log.Debug("====================================");
            Log.Debug("   STARTING (full .NET Framework)   ");
            Log.Debug("====================================");


            var url = BitmexValues.ApiWebsocketUrl;
            using (var communicator = new BitmexWebsocketCommunicator(url))
            {
                using (var client = new BitmexWebsocketClient(communicator))
                {

                    client.Streams.InfoStream.Subscribe(info =>
                    {
                        Log.Information($"Reconnection happened, Message: {info.Info}, Version: {info.Version:D}");
                           
                        client.Send(new PingRequest());
                        client.Send(new TradesSubscribeRequest("XBTUSD"));
                        //client.Send(new BookSubscribeRequest("XBTUSD"));

                        if (!string.IsNullOrWhiteSpace(API_SECRET))
                            client.Send(new AuthenticationRequest(API_KEY, API_SECRET));
                    });   

                    client.Streams.ErrorStream.Subscribe(x =>
                        Log.Warning($"Error received, message: {x.Error}, status: {x.Status}"));

                    client.Streams.AuthenticationStream.Subscribe(x =>
                    {
                        Log.Information($"Authentication happened, success: {x.Success}");
                        client.Send(new WalletSubscribeRequest());
                        client.Send(new OrderSubscribeRequest());
                        client.Send(new PositionSubscribeRequest());
                    });

                    client.Streams.PongStream.Subscribe(x =>
                        Log.Information($"Pong received ({x.Message})"));


                    client.Streams.TradesStream.Subscribe(y =>
                       y.Data.ToList().ForEach(x => 
                           Log.Information($"Trade {x.Symbol} executed. Time: {x.Timestamp:mm:ss.fff}, Amount: {x.Size}, " +
                                           $"Price: {x.Price}, Direction: {x.TickDirection}"))
                        );

                    client.Streams.BookStream.Subscribe(book =>
                        book.Data.Take(100).ToList().ForEach(x => Log.Information(
                            $"Book | {book.Action} pair: {x.Symbol}, price: {x.Price}, amount {x.Size}, side: {x.Side}"))
                    );

                    communicator.Start();
                    
                    ExitEvent.WaitOne();
                }
            }

            Log.Debug("====================================");
            Log.Debug("              STOPPING              ");
            Log.Debug("====================================");
            Log.CloseAndFlush();
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

private static void SubscribeToStreams(BitmexWebsocketClient client)
        {
            client.Streams.ErrorStream.Subscribe(x =>
                Log.Warning($"Error received, message: {x.Error}, status: {x.Status}"));

            client.Streams.AuthenticationStream.Subscribe(x =>
            {
                Log.Information($"Authentication happened, success: {x.Success}");
                client.Send(new WalletSubscribeRequest());
                client.Send(new OrderSubscribeRequest());
                client.Send(new PositionSubscribeRequest());
            });


            client.Streams.SubscribeStream.Subscribe(x =>
            {
                Log.Information(x.IsSubscription
                    ? $"Subscribed ({x.Success}) to {x.Subscribe}"
                    : $"Unsubscribed ({x.Success}) from {x.Unsubscribe}");
            });

            client.Streams.PongStream.Subscribe(x =>
                Log.Information($"Pong received ({x.Message})"));


            client.Streams.WalletStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information($"Wallet {x.Account}, {x.Currency} amount: {x.BalanceBtc}"))
            );

            client.Streams.OrderStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information(
                        $"Order {x.Symbol} {x.OrderId} updated. Time: {x.Timestamp:HH:mm:ss.fff}, Amount: {x.OrderQty}, " +
                        $"Price: {x.Price}, Direction: {x.Side}, Working: {x.WorkingIndicator}, Status: {x.OrdStatus}"))
            );

            client.Streams.PositionStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information(
                        $"Position {x.Symbol}, {x.Currency} updated. Time: {x.Timestamp:HH:mm:ss.fff}, Amount: {x.CurrentQty}, " +
                        $"Entry: {x.AvgEntryPrice}, Price: {x.LastPrice}, Liq: {x.LiquidationPrice}, " +
                        $"PNL: {x.UnrealisedPnl}"))
            );

            client.Streams.TradesStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information($"Trade {x.Symbol} executed. Time: {x.Timestamp:HH:mm:ss.fff}, [{x.Side}] Amount: {x.Size}, " +
                                    $"Price: {x.Price}, Match: {x.TrdMatchId}"))
            );

            client.Streams.BookStream.Subscribe(book =>
                book.Data.Take(100).ToList().ForEach(x => Log.Information(
                    $"Book | {book.Action} pair: {x.Symbol}, price: {x.Price}, amount {x.Size}, side: {x.Side}"))
            );

            client.Streams.Book25Stream.Subscribe(book =>
                book.Data.Take(100).ToList().ForEach(x => Log.Information(
                    $"Book | {book.Action} pair: {x.Symbol}, price: {x.Price}, amount {x.Size}, side: {x.Side}"))
            );

            client.Streams.QuoteStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information($"Quote {x.Symbol}. Bid: {x.BidPrice} - {x.BidSize} Ask: {x.AskPrice} - {x.AskSize}"))
            );

            client.Streams.LiquidationStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                    Log.Information(
                        $"Liquidation Action: {y.Action}, OrderID: {x.OrderID}, Symbol: {x.Symbol}, Side: {x.Side}, Price: {x.Price}, LeavesQty: {x.leavesQty}"))
            );

            client.Streams.TradeBinStream.Subscribe(y =>
                y.Data.ToList().ForEach(x =>
                Log.Information($"TradeBin table:{y.Table} {x.Symbol} executed. Time: {x.Timestamp:mm:ss.fff}, Open: {x.Open}, " +
                        $"Close: {x.Close}, Volume: {x.Volume}, Trades: {x.Trades}"))
            );

            client.Streams.InstrumentStream.Subscribe(x =>
            {
                x.Data.ToList().ForEach(y =>
                {
                    Log.Information($"Instrument, {y.Symbol}, " +
                                    $"price: {y.MarkPrice}, last: {y.LastPrice}, " +
                                    $"mark: {y.MarkMethod}, fair: {y.FairMethod}, direction: {y.LastTickDirection}, " +
                                    $"funding: {y.FundingRate} i: {y.IndicativeFundingRate} s: {y.FundingQuoteSymbol}");
                });
            });

            client.Streams.FundingStream.Subscribe(x =>
            {
                x.Data.ToList().ForEach(f =>
                {
                    Log.Information($"Funding {f.Symbol}, Timestamp: {f.Timestamp}, Interval: {f.FundingInterval}, " +
                                    $"Rate: {f.FundingRate}, RateDaily: {f.FundingRateDaily}");
                });
            });


            // example of unsubscribe requests
            //Task.Run(async () =>
            //{
            //    await Task.Delay(5000);
            //    client.Send(new BookSubscribeRequest("XBTUSD") { IsUnsubscribe = true });
            //    await Task.Delay(5000);
            //    client.Send(new TradesSubscribeRequest() { IsUnsubscribe = true });
            //});
        }

19 Source : Program.cs
with Apache License 2.0
from Marfusios

private static void SubscribeToStreams(CoinbaseWebsocketClient client)
        {
            client.Streams.ErrorStream.Subscribe(x =>
                Log.Warning($"Error received, message: {x.Message}"));


            client.Streams.SubscribeStream.Subscribe(x =>
            {
                Log.Information($"Subscribed, " +
                                $"channels: {JsonConvert.SerializeObject(x.Channels, CoinbaseJsonSerializer.Settings)}");
            });

            client.Streams.HeartbeatStream.Subscribe(x =>
                Log.Information($"Heartbeat received, product: {x.ProductId}, seq: {x.Sequence}, time: {x.Time}"));


            client.Streams.TickerStream.Subscribe(x =>
                    Log.Information($"Ticker {x.ProductId}. Bid: {x.BestBid} Ask: {x.BestAsk} Last size: {x.LastSize}, Price: {x.Price}")
                );

            client.Streams.TradesStream.Subscribe(x =>
            {
                Log.Information($"Trade executed [{x.ProductId}] {x.TradeSide} price: {x.Price} size: {x.Size}");
            });

            client.Streams.OrderBookSnapshotStream.Subscribe(x =>
            {
                Log.Information($"OB snapshot [{x.ProductId}] bids: {x.Bids.Length}, asks: {x.Asks.Length}");
            });

            client.Streams.OrderBookUpdateStream.Subscribe(x =>
            {
                Log.Information($"OB updates [{x.ProductId}] changes: {x.Changes.Length}");
            });
            
            // example of unsubscribe requests
            //Task.Run(async () =>
            //{
            //    await Task.Delay(5000);
            //    await client.Send(new BookSubscribeRequest("XBTUSD") {IsUnsubscribe = true});
            //    await Task.Delay(5000);
            //    await client.Send(new TradesSubscribeRequest() {IsUnsubscribe = true});
            //});
        }

19 Source : Program.cs
with MIT License
from Marfusios

static void Main(string[] args)
        {
            InitLogging();

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            replacedemblyLoadContext.Default.Unloading += DefaultOnUnloading;
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            Console.WriteLine("|=======================|");
            Console.WriteLine("|    WEBSOCKET CLIENT   |");
            Console.WriteLine("|=======================|");
            Console.WriteLine();

            Log.Debug("====================================");
            Log.Debug("              STARTING              ");
            Log.Debug("====================================");

            var factory = new Func<ClientWebSocket>(() =>
            {
                var client = new ClientWebSocket
                {
                    Options =
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(5),
                        // Proxy = ...
                        // ClientCertificates = ...
                    }
                };
                //client.Options.SetRequestHeader("Origin", "xxx");
                return client;
            });

            var url = new Uri("wss://www.bitmex.com/realtime");

            using (IWebsocketClient client = new WebsocketClient(url, factory))
            {
                client.Name = "Bitmex";
                client.ReconnectTimeout = TimeSpan.FromSeconds(30);
                client.ErrorReconnectTimeout = TimeSpan.FromSeconds(30);
                client.ReconnectionHappened.Subscribe(type =>
                {
                    Log.Information($"Reconnection happened, type: {type}, url: {client.Url}");
                });
                client.DisconnectionHappened.Subscribe(info =>
                    Log.Warning($"Disconnection happened, type: {info.Type}"));

                client.MessageReceived.Subscribe(msg =>
                {
                    Log.Information($"Message received: {msg}");
                });

                Log.Information("Starting...");
                client.Start().Wait();
                Log.Information("Started.");

                Task.Run(() => StartSendingPing(client));
                Task.Run(() => SwitchUrl(client));

                ExitEvent.WaitOne();
            }

            Log.Debug("====================================");
            Log.Debug("              STOPPING              ");
            Log.Debug("====================================");
            Log.CloseAndFlush();
        }

19 Source : Program.cs
with MIT License
from Marfusios

static void Main(string[] args)
        {
            InitLogging();

            AppDomain.CurrentDomain.ProcessExit += CurrentDomainOnProcessExit;
            Console.CancelKeyPress += ConsoleOnCancelKeyPress;

            Console.WriteLine("|=======================|");
            Console.WriteLine("|    WEBSOCKET CLIENT   |");
            Console.WriteLine("|=======================|");
            Console.WriteLine();

            Log.Debug("====================================");
            Log.Debug("              STARTING              ");
            Log.Debug("====================================");
           


            var url = new Uri("wss://www.bitmex.com/realtime");
            using (var client = new WebsocketClient(url))
            {
                client.Name = "Bitmex";
                client.ReconnectTimeoutMs = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
                client.ReconnectionHappened.Subscribe(type =>
                    Log.Information($"Reconnection happened, type: {type}"));
                client.DisconnectionHappened.Subscribe(type => 
                    Log.Warning($"Disconnection happened, type: {type}"));

                client.MessageReceived.Subscribe(msg => Log.Information($"Message received: {msg}"));

                client.Start();

                Task.Run(() => StartSendingPing(client));

                ExitEvent.WaitOne();
            }

            Log.Debug("====================================");
            Log.Debug("              STOPPING              ");
            Log.Debug("====================================");
            Log.CloseAndFlush();
        }

19 Source : IServiceProvider.cs
with MIT License
from msdn129

public object GetService(Type serviceType)
        {
            try
            {
                return _root.Resolve(serviceType);
            }
            catch {
                Log.Warning(serviceType.FullName);
                return null;
            }
        }

19 Source : IServiceProvider.cs
with MIT License
from msdn129

private object GetServiceByName(string Name, Type serviceType)
        {
            try
            {
                return _root.ResolveNamed(Name, serviceType);
            } 
            catch
            {
                Log.Warning(serviceType.FullName);
                return null;
            }
        }

19 Source : BuySellCommandHandler.cs
with GNU General Public License v3.0
from Winster332

public async Task Consume(ConsumeContext<BuyCurrency> context)
    {
      var amountInCurrency = await _exchange.RiskManager.GetActualBuyAmount();
      var rate = await _exchange.GetActualBuyPrice();
      var converter = new TradeCalcService();
      var amount = decimal.Round(converter.GetBuyAmount(amountInCurrency, rate), 8);
      var balanceMinLimit = _exchange.RiskManager.GetBalanceMinLimit();
      
      Log.Information($"GET[BUY] => USD amount [{amount} / {amountInCurrency}] rate [{rate}]");

      if (amountInCurrency <= balanceMinLimit)
      {
        Log.Warning($"Balance equal {amountInCurrency}. Risk manager stopping FarmMachine.ExchangeBroker");
        
        return;
      }

      try
      {
        await _protocolService.WriteAsync(new Dictionary<string, object>
        {
          {"_id", context.Message.Id},
          {"amount", amount},
          {"bid", context.Message.Bid},
          {"rate", rate},
          {"timestamp", context.Message.Created},
          {"type", "buy"}
        }, "BuyCurrency");
      }
      catch (Exception ex)
      {
        Log.Warning($"Invalid write to db: {ex}");
      }

//      await _exchange.PlaceOrderOnBuy(amount, rate);
    }

19 Source : BuySellCommandHandler.cs
with GNU General Public License v3.0
from Winster332

public async Task Consume(ConsumeContext<SellCurrency> context)
    {
      var amountInCurrency = await _exchange.RiskManager.GetActualSellAmount();
      var rate = await _exchange.GetActualSellPrice();
      var converter = new TradeCalcService();
      var amount = decimal.Round(converter.GetSellAmount(amountInCurrency, rate), 8);
      var balanceMinLimit = _exchange.RiskManager.GetBalanceMinLimit();
      
      Log.Information($"GET[SELL] => USD amount [{amount} / {amountInCurrency}] rate [{rate}]");

      if (amount <= balanceMinLimit)
      {
        Log.Warning($"Balance equal {amountInCurrency}. Risk manager stopping FarmMachine.ExchangeBroker");

        return;
      }
      
      try
      {
        await _protocolService.WriteAsync(new Dictionary<string, object>
        {
          {"_id", context.Message.Id},
          {"amount", context.Message.Amount},
          {"ask", context.Message.Ask},
          {"rate", rate},
          {"timestamp", context.Message.Created},
          {"type", "sell"}
        }, "SellCurrency");
      }
      catch (Exception ex)
      {
        Log.Warning($"Invalid write to db: {ex}");
      }

//      await _exchange.PlaceOrderOnSell(amountInCurrency, rate);
    }

19 Source : FarmMachineExchangeBrokerService.cs
with GNU General Public License v3.0
from Winster332

private void OnRefreshOnSell(object sender, MetaOrder e)
    {
      Log.Warning($"Begin cancel order: {e}");
      
      _container.Resolve<IBittrexExchange>().CancelOrder(e.OrderId).GetAwaiter().GetResult();
      
      Log.Warning($"Canceled. Push on sell");
      
      _container.Resolve<IBusControl>().Publish<SellCurrency>(new
      {
        Id = Guid.NewGuid(),
        Created = DateTime.Now,
        Amount = e.Amount,
        Ask = e.Rate
      }).GetAwaiter().GetResult();
    }

19 Source : FarmMachineExchangeBrokerService.cs
with GNU General Public License v3.0
from Winster332

private void OnRefreshOnBuy(object sender, MetaOrder e)
    {
      Log.Warning($"Begin cancel order: {e}");
      
      _container.Resolve<IBittrexExchange>().CancelOrder(e.OrderId).GetAwaiter().GetResult();
      
      Log.Warning($"Canceled. Push on sell");
      
      _container.Resolve<IBusControl>().Publish<BuyCurrency>(new
      {
        Id = Guid.NewGuid(),
        Created = DateTime.Now,
        Amount = e.Amount,
        Bid = e.Rate
      }).GetAwaiter().GetResult();
    }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from Winster332

private void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e)
    {
      if (e.IsMainFrame)
      {
        Browser.GetSourceAsync().ContinueWith(taskHtml =>
        {
          _libLoader.Execute(Browser);
          
          var html = taskHtml.Result;
          
          Browser.ExecuteScriptAsync("openLastBacktestOrderList();");
          
          Thread.Sleep(500);
          
          Browser.ExecuteScriptAsync("getButtonBacktestListOrders(2).click();");
          
          Thread.Sleep(500);
          
          Browser.ExecuteScriptAsync("backtestListOrderScrollToBottom();");
          
          Thread.Sleep(1000);
          
          Log.Information("Begin extract orders from backtest");
          var orders = ExtractOrders();
          Log.Information($"Orders extracted from backtest: {orders.Count}");
          
          Log.Information("Begin order validation");
          var validationResult = _orderCache.Push(orders);
          Log.Information($"End order validation: {validationResult}");

          if (validationResult.Status == ValidationStatus.Reload)
          {
            Thread.Sleep(1000);
            
            Log.Warning("Begin reload browser after failed validation");
            
            Browser.Reload();
          }
        });
      }
    }

19 Source : AllDebridCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args, CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var allDebrid = _appConfig.AllDebridConfig;
            var isEnabled = allDebrid.IsEnabled;

            if (!isEnabled)
            {
                Log.Warning("AllDebrid feature is disabled on AppSettings");
                return;
            }

            var txtParts = _telegramService.MessageTextParts;
            var urlParam = txtParts.ValueOfIndex(1);

            if (!_telegramService.IsFromSudo && _telegramService.IsChatRestricted)
            {
                Log.Information("AllDebrid is restricted only to some Chat ID");
                var limitFeature = "Convert link via AllDebrid hanya boleh di grup <b>WinTen Mirror</b>.";
                var groupBtn = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("⬇Ke WinTen Mirror", "https://t.me/WinTenMirror")
                    }
                });

                await _telegramService.SendTextAsync(limitFeature, groupBtn);
                return;
            }

            if (urlParam == null)
            {
                await _telegramService.SendTextAsync("Sertakan url yang akan di Debrid");
                return;
            }

            Log.Information("Converting url: {0}", urlParam);
            await _telegramService.SendTextAsync("Sedang mengkonversi URL via Alldebrid.");

            // var result = await _telegramService.ConvertUrl(urlParam);
            var result = await _allDebridService.ConvertUrl(urlParam, s =>
            {
                Log.Debug("Progress: {S}", s);
            });

            if (result.Status != "success")
            {
                var errorMessage = result.DebridError.Message;
                var fail = "Sepertinya Debrid gagal." +
                           $"\nNote: {errorMessage}";

                await _telegramService.EditAsync(fail);
                return;
            }

            var urlResult = result.DebridData.Link.AbsoluteUri;
            var fileName = result.DebridData.Filename;
            var fileSize = result.DebridData.Filesize;

            var text = "✅ Debrid berhasil" +
                       $"\n📁 Nama: <code>{fileName}</code>" +
                       $"\n📦 Ukuran: <code>{fileSize.SizeFormat()}</code>";

            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                new[]
                {
                    InlineKeyboardButton.WithUrl("⬇️ Download", urlResult)
                }
            });

            await _telegramService.EditAsync(text, inlineKeyboard);
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from Winster332

private void TimeSchedulerOnWork(object sender, EventArgs e)
    {
      Log.Warning("Browser start reloading from TimeScheduler...");
      Browser.Reload();
      Log.Warning("Browser stop reloaded from TimeScheduler");
    }

19 Source : DeleteBanCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var msg = _telegramService.Message;
            var chatId = msg.Chat.Id;
            var fromId = msg.From.Id;
            var partedText = msg.Text.Split(" ");
            var param1 = partedText.ValueOfIndex(1); // User ID

            if (!_telegramService.IsFromSudo)
            {
                Log.Warning("Not sudo can't execute this command..");
                return;
            }

            if (param1.IsNullOrEmpty())
            {
                await _telegramService.SendTextAsync("Spesifikasikan ID Pengguna yang mau di hapus dari Global Ban");
                return;
            }

            var repMsg = msg.ReplyToMessage;
            var userId = param1.ToInt();

            Log.Information("Execute Global DelBan");
            await _telegramService.SendTextAsync("Mempersiapkan..");

            var isBan = await _globalBanService.IsExist(userId);
            Log.Information("IsBan: {IsBan}", isBan);
            if (!isBan)
            {
                await _telegramService.EditAsync("Pengguna tidak di ban");
                return;
            }

            await _telegramService.EditAsync("Memperbarui informasi..");
            var save = await _globalBanService.DeleteBanAsync(userId);
            Log.Information("SaveBan: {Save}", save);

            await _telegramService.EditAsync("Memperbarui Cache..");
            await SyncUtil.SyncGBanToLocalAsync();

            await _telegramService.EditAsync("Pengguna berhasil di tambahkan");
        }

19 Source : AdminCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            if (_telegramService.IsPrivateChat)
            {
                Log.Warning("Get admin list only for group");
                return;
            }

            await _telegramService.SendTextAsync("🍽 Loading..");

            var admins = await _telegramService.GetChatAdmin();

            var creatorStr = string.Empty;
            var sbAdmin = new StringBuilder();

            int number = 1;
            foreach (var admin in admins)
            {
                var user = admin.User;
                var nameLink = user.Id.GetNameLink((user.FirstName + " " + user.LastName).Trim());
                if (admin.Status == ChatMemberStatus.Creator)
                {
                    creatorStr = nameLink;
                }
                else
                {
                    sbAdmin.AppendLine($"{number++}. {nameLink}");
                }
            }

            var sendText = $"👤 <b>Creator</b>" +
                           $"\n└ {creatorStr}" +
                           $"\n" +
                           $"\n👥️ <b>Administrators</b>" +
                           $"\n{sbAdmin.ToTrimmedString()}";

            await _telegramService.EditAsync(sendText);

            // await _telegramService.UpdateCacheAdminAsync();
        }

19 Source : DelRssCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);
            var chatId = _telegramService.ChatId;

            var isAdminOrPrivateChat = _telegramService.IsAdminOrPrivateChat();
            if (!isAdminOrPrivateChat)
            {
                Log.Warning("Delete RSS only for admin or private chat!");
                await _telegramService.DeleteAsync();
                return;
            }

            var urlFeed = _telegramService.Message.Text.GetTextWithoutCmd();

            await _telegramService.SendTextAsync($"Sedang menghapus {urlFeed}");

            var delete = await _rssService.DeleteRssAsync(chatId, urlFeed);

            var success = delete.ToBool()
                ? "berhasil."
                : "gagal. Mungkin RSS tersebut sudah di hapus atau belum di tambahkan";

            await _telegramService.EditAsync($"Hapus {urlFeed} {success}");
        }

19 Source : RssCtlCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var chatId = _telegramService.ChatId;

            var msg = context.Update.Message;

            var isSudoer = _telegramService.IsFromSudo;
            if (!isSudoer)
            {
                Log.Warning("This command only for sudo!");
                return;
            }

            var partedMsg = msg.Text.Split(" ");
            var param1 = partedMsg.ValueOfIndex(1);
            Log.Debug("RssCtl Param1: {Param1}", param1);

            await _telegramService.AppendTextAsync("Access Granted");
            switch (param1)
            {
                case "start":
                    await _telegramService.AppendTextAsync("Starting RSS Service");
                    // RssScheduler.InitScheduler();

                    var rssSettings = await _rssService.GetAllRssSettingsAsync();
                    var filteredSettings = rssSettings.Where(setting => setting.ChatId == chatId.ToString());

                    foreach (var rssSetting in rssSettings)
                    {
                        var rssChatId = rssSetting.ChatId.ToInt64();
                        var urlFeed = rssSetting.UrlFeed;

                        var reducedChatId = rssChatId.ReduceChatId();
                        var unique = StringUtil.GenerateUniqueId(5);

                        var baseId = "rss";
                        var cronInMinute = 1;
                        var recurringId = $"{baseId}-{reducedChatId}-{unique}";

                        HangfireUtil.RegisterJob<RssFeedService>(recurringId, service => service.ExecuteUrlAsync(rssChatId, urlFeed), Cron.Minutely, queue: "rss-feed");

                        // RegisterFeed(chatId, urlFeed);
                        // RegisterScheduler(chatId);
                    }

                    await _telegramService.AppendTextAsync("Start successfully.");
                    break;

                case "stop":
                    await _telegramService.AppendTextAsync("Stopping RSS Service");
                    HangfireUtil.DeleteAllJobs();
                    await _telegramService.AppendTextAsync("Stop successfully.");
                    break;

                default:
                    await _telegramService.AppendTextAsync("Lalu mau ngapain?");
                    break;
            }
        }

19 Source : ResetSettingsCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var msg = _telegramService.Message;
            var chat = _telegramService.Message.Chat;
            var chatId = _telegramService.ChatId;

            var adminOrPrivate = _telegramService.IsAdminOrPrivateChat();
            if (!adminOrPrivate)
            {
                Log.Warning("Settings command only for Admin group or Private chat");
                return;
            }

            Log.Information("Initializing reset Settings.");
            await _telegramService.DeleteAsync(msg.MessageId);
            await _telegramService.SendTextAsync("Sedang mengembalikan ke Pengaturan awal");

            var data = new Dictionary<string, object>()
            {
                ["chat_id"] = chat.Id,
                ["chat_replacedle"] = chat.replacedle,
                ["enable_afk_stats"] = 1,
                ["enable_anti_malfiles"] = 1,
                ["enable_fed_cas_ban"] = 1,
                ["enable_fed_es2_ban"] = 1,
                ["enable_fed_spamwatch"] = 1,
                ["enable_url_filtering"] = 1,
                ["enable_human_verification"] = 1,
                ["enable_reply_notification"] = 1,
                ["enable_warn_username"] = 1,
                ["enable_word_filter_group"] = 1,
                ["enable_word_filter_global"] = 1,
                ["enable_welcome_message"] = 1,
            };

            var update = await _settingsService.SaveSettingsAsync(data);
            await _settingsService.UpdateCacheAsync(chatId);
            Log.Information("Result: {Update}", update);

            await _telegramService.EditAsync("Pengaturan awal berhasil di kembalikan");
            await _telegramService.DeleteAsync(_telegramService.EditedMessageId, 2000);

            Log.Information("Settings has been reset.");
        }

19 Source : SettingsCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var message = _telegramService.Message;
            var chatId = _telegramService.ChatId;

            await _telegramService.DeleteAsync(message.MessageId);

            var adminOrPrivate = _telegramService.IsAdminOrPrivateChat();
            if (!adminOrPrivate)
            {
                Log.Warning("Settings command only for Admin group or Private chat");
                return;
            }

            await _telegramService.SendTextAsync("Sedang mengambil pengaturan..", replyToMsgId: 0);
            var settings = await _settingsService.GetSettingButtonByGroup(chatId);

            var btnMarkup = await settings.ToJson().JsonToButton(chunk: 2);
            Log.Debug("Settings: {Count}", settings.Count);

            await _telegramService.EditAsync("Settings Toggles", btnMarkup);
        }

19 Source : TestCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var param1 = _telegramService.MessageTextParts.ValueOfIndex(1);
            var param2 = _telegramService.MessageTextParts.ValueOfIndex(2);

            var chatId = _telegramService.ChatId;
            var chatType = _telegramService.Message.Chat.Type;
            var fromId = _telegramService.FromId;
            var msg = _telegramService.Message;
            var msgId = msg.MessageId;

            if (!_telegramService.IsFromSudo)
            {
                Log.Warning("Test only for Sudo!");
                return;
            }

            Log.Information("Adding easy caching..");
            await _easyCachingProvider.SetAsync(msgId.ToString(), msg, TimeSpan.FromMinutes(1));

            Log.Information("Test started..");
            await _telegramService.AppendTextAsync("Sedang mengetes sesuatu");

            if (param1.IsNullOrEmpty())
            {
                await _telegramService.AppendTextAsync("No Test Param");
                return;
            }

            await _telegramService.AppendTextAsync($"Flags: {param1}");

            switch (param1)
            {
                case "ex-keyboard":
                    await ExtractReplyMarkup();
                    break;

                // case "mk-remove-all":
                //     MonkeyCacheRemoveAll();
                //     break;

                // case "mk-remove-expires":
                //     MonkeyCacheRemoveExpires();
                //     break;

                // case "mk-view-all":
                //     MonkeyCacheViewAll();
                //     break;

                // case "mk-save-current":
                //     MonkeyCacheSaveCurrent();
                //     break;

                case "ml-nlp":
                    MachineLearningProcessNlp();
                    break;

                case "ml-predict":
                    await MachineLearningPredict();
                    break;

                case "nsfw-detect":
                    await NsfwDetect();
                    break;

                case "ldb-save-current":
                    await LiteDbSaveCurrent();
                    break;

                case "sysinfo":
                    await GetSysInfo();
                    break;

                case "uniqid-gen":
                    var id = StringUtil.GenerateUniqueId(param2.ToInt());
                    await _telegramService.AppendTextAsync($"UniqueID: {id}");
                    break;

                case "wh-check":
                    await WebhookCheck();
                    break;

                case "dl-gen":
                    var directLink = await DirectLinkParser(param2);
                    await _telegramService.AppendTextAsync($"DL: {directLink}");
                    break;

                case "parse-bl":
                    var url = "https://raw.githubusercontent.com/mhhakim/pihole-blocklist/master/replaced.txt";
                    var listUrl = await _blockListService.ParseList(url);
                    var msgText = $"{listUrl.Name}" +
                              $"\n{listUrl.Source}" +
                              $"\n{listUrl.LastUpdate}" +
                              $"\n{listUrl.DomainCount}";

                    await _telegramService.AppendTextAsync($"{msgText}");
                    break;

                default:
                    await _telegramService.AppendTextAsync($"Feature '{param1}' is not available.");
                    Log.Warning("Feature '{0}' is not available", param1);

                    break;
            }

            await _telegramService.AppendTextAsync("Complete");
        }

19 Source : BanCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var kickTargets = new List<User>();

            var msg = _telegramService.Message;
            var fromId = _telegramService.FromId;

            kickTargets.Add(msg.From);

            if (msg.ReplyToMessage != null)
            {
                kickTargets.Clear();

                var repMsg = msg.ReplyToMessage;
                kickTargets.Add(repMsg.From);

                if (repMsg.NewChatMembers != null)
                {
                    kickTargets.AddRange(repMsg.NewChatMembers);
                }
            }

            await _telegramService.DeleteAsync(msg.MessageId);

            var isAdmin = await _telegramService.IsAdminGroup();

            var containFromId = kickTargets.Where((user, i) => user.Id == fromId).Any();

            if (!containFromId && !isAdmin)
            {
                Log.Warning("No privilege for execute this command!");
                return;
            }

            var sbKickResult = new StringBuilder($"Sedang memblokir {kickTargets.Count} pengguna..");
            sbKickResult.AppendLine();

            foreach (var userId in kickTargets.Select(kickTarget => kickTarget.Id))
            {
                var isKicked = await _telegramService.KickMemberAsync(userId, true);

                if (isKicked)
                {
                    sbKickResult.Append($"{userId} berhasil di blokir ");
                    sbKickResult.AppendLine(userId == fromId ? $"oleh Self-ban" : "");
                }
                else
                {
                    sbKickResult.AppendLine($"Gagal memblokir {userId}");
                }
            }

            await _telegramService.AppendTextAsync(sbKickResult.ToTrimmedString());
        }

19 Source : KickCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var kickTargets = new List<User>();

            var msg = _telegramService.Message;
            var fromId = _telegramService.FromId;

            kickTargets.Add(msg.From);

            if (msg.ReplyToMessage != null)
            {
                kickTargets.Clear();

                var repMsg = msg.ReplyToMessage;
                kickTargets.Add(repMsg.From);

                if (repMsg.NewChatMembers != null)
                {
                    kickTargets.AddRange(repMsg.NewChatMembers);
                }
            }

            await _telegramService.DeleteAsync(msg.MessageId);

            var isAdmin = await _telegramService.IsAdminGroup();

            var containFromId = kickTargets.Where((user, i) => user.Id == fromId).Any();

            if (!containFromId && !isAdmin)
            {
                Log.Warning("No privilege for execute this command!");
                return;
            }

            var sbKickResult = new StringBuilder($"Sedang menendang {kickTargets.Count} pengguna..");
            sbKickResult.AppendLine();

            foreach (var userId in kickTargets.Select(kickTarget => kickTarget.Id))
            {
                var isKicked = await _telegramService.KickMemberAsync(userId, true);

                if (isKicked)
                {
                    sbKickResult.Append($"{userId} berhasil di tendang ");
                    sbKickResult.AppendLine(userId == fromId ? $"oleh Self-kick" : "");
                }
                else
                {
                    sbKickResult.AppendLine($"Gagal menendang {userId}");
                }
            }

            await _telegramService.AppendTextAsync(sbKickResult.ToTrimmedString());
        }

19 Source : PinCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var msg = _telegramService.MessageOrEdited;
            var client = context.Bot.Client;

            var sendText = "Balas pesan yang akan di pin";

            var isAdmin = _telegramService.IsFromAdmin;
            if (!isAdmin)
            {
                Log.Warning("Pin message only for Admin on Current Chat");
                await _telegramService.DeleteAsync(msg.MessageId);
                return;
            }

            if (msg.ReplyToMessage != null)
            {
                await client.PinChatMessageAsync(
                    msg.Chat.Id,
                    msg.ReplyToMessage.MessageId,
                    cancellationToken: cancellationToken);
                return;
            }

            await _telegramService.SendTextAsync(sendText, replyToMsgId: msg.MessageId);
        }

19 Source : RssPullCommand.cs
with MIT License
from WinTenDev

public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args,
            CancellationToken cancellationToken)
        {
            await _telegramService.AddUpdateContext(context);

            var chatId = _telegramService.Message.Chat.Id;
            var isAdmin = await _telegramService.IsAdminGroup();

            if (!isAdmin && !_telegramService.IsPrivateChat)
            {
                Log.Warning("You must Admin or Private chat");

                return;
            }

            Log.Information("Pulling RSS in {0}", chatId);

#pragma warning disable 4014
            Task.Run(async () =>
#pragma warning restore 4014
            {
                await _telegramService.SendTextAsync("Sedang memeriksa RSS feed baru..");

                var reducedChatId = chatId.ReduceChatId();
                var recurringId = $"rss-{reducedChatId}";
                var count = HangfireUtil.TriggerJobs(recurringId);

                if (count == 0)
                {
                    await _telegramService.EditAsync("Tampaknya tidak ada RSS baru saat ini");
                }
                else
                {
                    await _telegramService.DeleteAsync(_telegramService.SentMessageId);
                }

            }, cancellationToken);
        }

19 Source : OcrSpaceService.cs
with MIT License
from WinTenDev

public async Task<string> ScanImage(string filePath)
        {
            var result = "";
            try
            {
                await using var fs = File.OpenRead(filePath);
                var url = "https://api.ocr.space/Parse/Image";
                var ocrKey = "BotSettings.OcrSpaceKey";
                var fileName = Path.GetFileName(filePath);

                if (ocrKey.IsNullOrEmpty())
                {
                    Log.Warning("OCR can't be continue because API KEY is missing.");
                    return string.Empty;
                }

                Log.Information("Sending {FilePath} to {Url}", filePath, url);
                var postResult = await url
                    .PostMultipartAsync(post =>
                        post.AddFile("image", fs, fileName)
                            .AddString("apikey", ocrKey)
                            .AddString("language", "eng"));

                Log.Information("OCR: {StatusCode}", postResult.StatusCode);
                var json = await postResult.GetStringAsync();

                var map = JsonConvert.DeserializeObject<OcrResult>(json);

                if (map.OcrExitCode == 1)
                {
                    result = map.ParsedResults.Aggregate(result, (current, t) =>
                        current + t.ParsedText);
                }

                Log.Information("Scan complete.");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error OCR Space");
            }

            return result;
        }

19 Source : CekResiService.cs
with MIT License
from WinTenDev

public async Task<CekResi> RunCekResi(string resi)
        {
            Log.Information("Checking Resi {0}", resi);
            var couriers = GetCouriers();
            var pigooraConfig = "_appConfig.PigooraConfig";
            var cekResiUrl = "pigooraConfig.CekResiUrl";
            var cekResiToken = "pigooraConfig.CekResiToken";

            CekResi cekResi = null;

            Log.Information("Searching on {0} couriers", couriers.Count);
            foreach (var courier in couriers)
            {
                Log.Information("Searching on courier {0}", courier);
                cekResi = await cekResiUrl
                    .SetQueryParam("key", cekResiToken)
                    .SetQueryParam("resi", resi)
                    .SetQueryParam("kurir", courier)
                    .SetQueryParams()
                    .WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0")
                    .WithHeader("Host", "api.cekresi.pigoora.com")
                    .WithHeader("Origin", "https://cekresi.pigoora.com")
                    .WithHeader("Referer", "https://cekresi.pigoora.com/")
                    .GetJsonAsync<CekResi>();

                if (cekResi.Result != null)
                {
                    Log.Warning("Searching resi break!");
                    break;
                }

                await Task.Delay(100);
            }

            Log.Debug("Resi Check finish.");
            return cekResi;
        }

See More Examples