public ImageSource TryGetImage(IconId iconId, IconTheme theme, IThemedIconManagerPerThemeCache cache, OnError onerror)
        {
            var emojiIconId = iconId as EmojiIconId;

            var image = emojiIconId?.Emoji.Bitmap();
            return image;
        }
Example #2
0
        public TweetLoader()
        {
            loaded = 0;
            Source = new SafeObservable<ITweetable>();
            requestsInProgress = 0;

            if (_rateResetTime == null)
                _rateResetTime = DateTime.MinValue;

            Error += new OnError(CheckForRateLimit);

            LoadDefaultSettings();
        }
Example #3
0
        public static void AddElementToStore(MapStorageType storageType, string stylePath, Element element, Range<int> levelOfDetails, OnError onError)
        {
            double[] coordinates = new double[element.Geometry.Length*2];
            for (int i = 0; i < element.Geometry.Length; ++i)
            {
                coordinates[i*2] = element.Geometry[i].Latitude;
                coordinates[i*2 + 1] = element.Geometry[i].Longitude;
            }

            string[] tags = new string[element.Tags.Count * 2];
            var tagKeys = element.Tags.Keys.ToArray();
            for (int i = 0; i < tagKeys.Length; ++i)
            {
                tags[i*2] = tagKeys[i];
                tags[i*2 + 1] = element.Tags[tagKeys[i]];
            }

            addToStoreElement(GetStoreKey(storageType), stylePath, element.Id,
                coordinates, coordinates.Length,
                tags, tags.Length,
                levelOfDetails.Minimum, levelOfDetails.Maximum, onError);
        }
 public abstract void LoadPreferredTerms(OnLoaded onLoaded, OnError onError, string terminologyId, string language, string[] conceptIds);
Example #5
0
        /// <summary>
        /// Starts the API.
        /// </summary>
        public void Start()
        {
            Stopwatch s = new Stopwatch();

            s.Start();

            Logger.LogInfo("Starting EliteAPI.");
            Logger.LogDebug("EliteAPI by CMDR Somfic (discord.gg/jwpFUPZ) (github.com/EliteAPI/EliteAPI).");
            Logger.LogDebug("EliteAPI v" + Version + ".");

            //Check for updates.
            CheckForUpdate();

            Logger.LogInfo($"Journal directory set to '{JournalDirectory}'.");

            //Mark the API as running.
            IsRunning = true;

            //We'll process the journal one time first, to catch up.
            //Select the last edited Journal file.
            FileInfo journalFile = null;

            //Find the last edited Journal file.
            try
            {
                Logger.LogDebug($"Searching for 'Journal.*.log' files.");
                journalFile = JournalDirectory.GetFiles("Journal.*").OrderByDescending(x => x.LastWriteTime).First();
                Logger.LogDebug($"Found '{journalFile}'.");
            }
            catch (Exception ex)
            {
                IsRunning = false;
                OnError?.Invoke(this, new Tuple <string, Exception>($"Could not find Journal files in '{JournalDirectory}'", ex));
                return;
            }

            //Check for the support JSON files.
            bool foundStatus = false;

            try
            {
                //Status.json.
                if (File.Exists(JournalDirectory.FullName + "\\Status.json"))
                {
                    Logger.LogDebug("Found 'Status.json'."); foundStatus = true;
                }
                else
                {
                    Logger.LogWarning($"Could not find 'Status.json' file."); foundStatus = false;
                }

                //Cargo.json.
                if (File.Exists(JournalDirectory.FullName + "\\Cargo.json"))
                {
                    Logger.LogDebug("Found 'Cargo.json'.");
                }
                else
                {
                    Logger.LogWarning($"Could not find 'Cargo.json' file.");
                }

                //Shipyard.json.
                if (File.Exists(JournalDirectory.FullName + "\\Shipyard.json"))
                {
                    Logger.LogDebug("Found 'Shipyard.json'.");
                }
                else
                {
                    Logger.LogDebug($"Could not find 'Shipyard.json' file.");
                }

                //Outfitting.json.
                if (File.Exists(JournalDirectory.FullName + "\\Outfitting.json"))
                {
                    Logger.LogDebug("Found 'Outfitting.json'.");
                }
                else
                {
                    Logger.LogDebug($"Could not find 'Outfitting.json' file.");
                }

                //Market.json.
                if (File.Exists(JournalDirectory.FullName + "\\Market.json"))
                {
                    Logger.LogDebug("Found 'Market.json'.");
                }
                else
                {
                    Logger.LogDebug($"Could not find 'Market.json' file.");
                }

                //ModulesInfo.json.
                if (File.Exists(JournalDirectory.FullName + "\\ModulesInfo.json"))
                {
                    Logger.LogDebug("Found 'ModulesInfo.json'.");
                }
                else
                {
                    Logger.LogDebug($"Could not find 'ModulesInfo.json' file.");
                }
            }
            catch { }

            if (foundStatus)
            {
                Logger.LogInfo("Found Journal and Status files.");
            }

            //Check if Elite: Dangerous is running.
            if (!Status.IsRunning)
            {
                Logger.LogWarning("Elite: Dangerous is not in-game.");
            }

            //Process the journal file.
            if (!SkipCatchUp)
            {
                Logger.LogDebug("Catching up with past events from this session.");
            }
            JournalParser.ProcessJournal(journalFile, SkipCatchUp);
            if (!SkipCatchUp)
            {
                Logger.LogDebug("Catchup on past events completed.");
            }

            //Go async.
            Task.Run(() =>
            {
                //Run for as long as we're running.
                while (IsRunning)
                {
                    //Select the last edited Journal file.
                    FileInfo newJournalFile = JournalDirectory.GetFiles("Journal.*").OrderByDescending(x => x.LastWriteTime).First();
                    if (journalFile.FullName != newJournalFile.FullName)
                    {
                        Logger.LogDebug($"Switched to '{newJournalFile}'."); JournalParser.processedLogs.Clear();
                    }
                    journalFile = newJournalFile;

                    //Process the journal file.
                    JournalParser.ProcessJournal(journalFile, false);

                    //Wait half a second to avoid overusing the CPU.
                    Thread.Sleep(500);
                }
            });

            s.Stop();

            Logger.LogDebug($"Finished in {s.ElapsedMilliseconds}ms.");
            IsReady = true;
            OnReady?.Invoke(this, EventArgs.Empty);
        }
 public abstract void LoadConcepts(OnLoaded onLoaded, OnError onError, string terminologyId, string language);
Example #7
0
 protected internal void RaiseError(object sender, PluginErrorEventArgs e)
 => OnError?.Invoke(sender, e);
Example #8
0
 ///<summary>
 /// Creates the folder
 ///</summary>
 ///<param name="onError">Allows you to set the error behavior</param>
 ///<returns></returns>
 public Directory Create(OnError onError)
 {
     FailableActionExecutor.DoAction(onError, _fileSystemWrapper.CreateDirectory, _path);
     return this;
 }
Example #9
0
 /// <summary> Loads quadkey. </summary>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="quadKey"> QuadKey</param>
 /// <param name="onMeshBuilt"></param>
 /// <param name="onElementLoaded"></param>
 /// <param name="onError"></param>
 public static void LoadQuadKey(string stylePath, QuadKey quadKey,
     OnMeshBuilt onMeshBuilt, OnElementLoaded onElementLoaded, OnError onError)
 {
     loadQuadKey(stylePath, quadKey.TileX, quadKey.TileY, quadKey.LevelOfDetail,
         onMeshBuilt, onElementLoaded, onError);
 }
Example #10
0
 private static extern void configure(string stringPath, string elePath, OnError errorHandler);
Example #11
0
 /// <summary> Loads quadkey. </summary>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="quadKey"> QuadKey</param>
 /// <param name="onMeshBuilt"></param>
 /// <param name="onElementLoaded"></param>
 /// <param name="onError"></param>
 public static void LoadQuadKey(string stylePath, QuadKey quadKey,
                                OnMeshBuilt onMeshBuilt, OnElementLoaded onElementLoaded, OnError onError)
 {
     loadQuadKey(stylePath, quadKey.TileX, quadKey.TileY, quadKey.LevelOfDetail,
                 onMeshBuilt, onElementLoaded, onError);
 }
Example #12
0
 private static extern void configure(string stringPath, string elePath, OnError errorHandler);
Example #13
0
 private void OnConsumerShutdown(object sender, ShutdownEventArgs e)
 {
     OnError?.Invoke(sender, e.Cause?.ToString());
 }
Example #14
0
        private void _client_OnReceive(byte[] data)
        {
            Actived = DateTimeHelper.Now;

            if (data != null)
            {
                this._messageContext.Unpacker.Unpack(data, (s) =>
                {
                    if (s.Content != null)
                    {
                        try
                        {
                            var cm = SerializeHelper.PBDeserialize <ChatMessage>(s.Content);

                            switch (cm.Type)
                            {
                            case ChatMessageType.LoginAnswer:
                                this.Logined = true;
                                break;

                            case ChatMessageType.SubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _subscribed = true;
                                }
                                else
                                {
                                    _subscribed = false;
                                }
                                break;

                            case ChatMessageType.UnSubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _unsubscribed = true;
                                }
                                else
                                {
                                    _unsubscribed = false;
                                }
                                break;

                            case ChatMessageType.ChannelMessage:
                                TaskHelper.Run(() => OnChannelMessage?.Invoke(cm.GetIMessage <ChannelMessage>()));
                                break;

                            case ChatMessageType.PrivateMessage:
                                TaskHelper.Run(() => OnPrivateMessage?.Invoke(cm.GetIMessage <PrivateMessage>()));
                                break;

                            case ChatMessageType.GroupMessage:
                                TaskHelper.Run(() => OnGroupMessage?.Invoke(cm.GetIMessage <GroupMessage>()));
                                break;

                            case ChatMessageType.PrivateMessageAnswer:
                                break;

                            case ChatMessageType.CreateGroupAnswer:
                            case ChatMessageType.RemoveGroupAnswer:
                            case ChatMessageType.AddMemberAnswer:
                            case ChatMessageType.RemoveMemberAnswer:
                                break;

                            case ChatMessageType.GroupMessageAnswer:
                                break;

                            default:
                                ConsoleHelper.WriteLine("cm.Type", cm.Type);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            OnError?.Invoke(_messageContext.UserToken.ID, ex);
                        }
                    }
                }, null, null);
            }
        }
Example #15
0
        private async Task Reader()
        {
            string message = "";


            while (IsConnected)
            {
                try {
                    var buffer = new byte[1024];

                    var res = await WSConnection.ReceiveAsync(new ArraySegment <byte>(buffer), default);

                    if (res.MessageType == WebSocketMessageType.Close)
                    {
                        Close();
                        break;
                    }

                    if (res.Count == 0)
                    {
                        Close();
                        break;
                    }

                    switch (res.MessageType)
                    {
                    case WebSocketMessageType.Close:
                        Close();
                        return;

                    case WebSocketMessageType.Text when !res.EndOfMessage:
                        message += (Encoding.UTF8.GetString(buffer).TrimEnd('\0'));
                        continue;

                    case WebSocketMessageType.Text:
                        message += (Encoding.UTF8.GetString(buffer).TrimEnd('\0'));
                        OnMessage?.Invoke(this, new OnMessageEventArgs()
                        {
                            Message = message
                        });
                        break;

                    case WebSocketMessageType.Binary:
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    message = "";
                } catch (IOException) {
                    Close();
                } catch (WebSocketException) {
                    Close();
                } catch (Exception ex) {
                    OnError?.Invoke(this, new OnErrorEventArgs()
                    {
                        Exception = ex
                    });
                    break;
                }
            }
        }
Example #16
0
 /// <summary>
 /// SSE Pushサーバからエラー受信時の処理を登録
 /// </summary>
 /// <param name="Callback">エラー受信時の処理</param>
 public void RegisterOnError(OnError Callback)
 {
     _onErrorCallback = Callback;
 }
 public void Error(Exception e)
 {
     Set(Task.FromException(e));
     LastException = e;
     OnError?.Invoke(e);
 }
Example #18
0
 public static extern void HP_Set_FN_Server_OnError(IntPtr pListener, OnError fn);
Example #19
0
 /// <summary>
 ///     Adds map data to in-memory storage to specific quadkey.
 ///     Supported formats: shapefile, osm xml, osm pbf.
 /// </summary>
 /// <param name="storageType"> Map data storage. </param>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="path"> Path to file. </param>
 /// <param name="quadKey"> QuadKey. </param>
 /// <param name="onError"> OnError callback. </param>
 public static void AddToStore(MapStorageType storageType, string stylePath, string path, QuadKey quadKey, OnError onError)
 {
     addToStoreInQuadKey(GetStoreKey(storageType), stylePath, path, quadKey.TileX, quadKey.TileY, quadKey.LevelOfDetail, onError);
 }
Example #20
0
 ///<summary>
 /// Deletes the file 
 ///<remarks>If the file does not exist no error will be thrown (even if OnError is set to fail)</remarks>
 /// <param name="onError">Sets wether to fail or continue if an error occurs</param>
 ///</summary>
 public void Delete(OnError onError)
 {
     FailableActionExecutor.DoAction(onError, _fileSystemWrapper.DeleteFile, Path);
 }
 private void Socket_OnError(Exception ex)
 {
     Log($"OnError invoked, {ex.Message}");
     OnError?.Invoke(ex);
 }
Example #22
0
 private static extern void addToStoreInQuadKey(string key, string stylePath, string path, int tileX, int tileY, int lod, OnError errorHandler);
Example #23
0
    public static void Connect(string host = "localhost", int port = 3075)
    {
        _lastHost = host;
        _lastPort = port;
        // Set extensions to default resolver.
        var resolver = CompositeResolver.Create(
            MathResolver.Instance,
            NativeGuidResolver.Instance,
            StandardResolver.Instance
            );
        var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);

        MessagePackSerializer.DefaultOptions = options;

        EventBasedNetListener listener = new EventBasedNetListener();

        _client = new NetManager(listener)
        {
//            UnsyncedEvents = true,
            NatPunchEnabled = true
        };
        _client.Start(3074);
        _peer = _client.Connect(host, port, "aetheria-cc65a44d");
        Observable.EveryUpdate().Subscribe(_ => _client.PollEvents());
        listener.NetworkErrorEvent   += (point, code) => Logger($"{point.Address}: Error {code}");
        listener.NetworkReceiveEvent += (peer, reader, method) =>
        {
            var bytes = reader.GetRemainingBytes();
            Logger($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
            var message = MessagePackSerializer.Deserialize <Message>(bytes);
            var type    = message.GetType();

            if (!Verified)
            {
                switch (message)
                {
                case LoginSuccessMessage loginSuccess:
                    _token = loginSuccess.Session;
                    break;

                case NetErrorMessage error:
                    OnError?.Invoke(error.Error);
                    break;
                }
            }

            if (_messageCallbacks.ContainsKey(type))
            {
                typeof(ActionCollection <>).MakeGenericType(new[] { type }).GetMethod("Invoke")
                .Invoke(_messageCallbacks[type], new object[] { message });
            }
            else
            {
                Logger(
                    $"Received {type.Name} message but no one is listening for it so I'll just leave it here " +
                    $"¯\\_(ツ)_/¯\n{MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
            }
        };

        listener.PeerConnectedEvent += peer =>
        {
            Logger($"Peer {peer.EndPoint.Address}:{peer.EndPoint.Port} connected.");
            _peer = peer;
            if (Verified)
            {
                peer.Send(new VerifyMessage {
                    Session = _token
                });
            }
        };

        listener.PeerDisconnectedEvent += (peer, info) =>
        {
            Logger($"Peer {peer.EndPoint.Address}:{peer.EndPoint.Port} disconnected: {info.Reason}.");
            _peer = null;
            Connect(_lastHost, _lastPort);
        };

        listener.NetworkLatencyUpdateEvent +=
            (peer, latency) => Ping         = latency; //Logger($"Ping received: {latency} ms");
    }
Example #24
0
 private static extern void addToStoreInRange(string key, string stylePath, string path, int startLod, int endLod, OnError errorHandler);
Example #25
0
 private void WSClient_OnError(string id, Exception ex)
 {
     OnError?.Invoke(id, ex);
 }
Example #26
0
 /// <summary>
 /// Show the error message
 /// </summary>
 /// <param name="error">Error type</param>
 public void ShowErrorMessage(ErrorType error)
 {
     OnError?.Invoke(_errorMessages[error]);
 }
Example #27
0
 private static extern void addToStoreInQuadKey(string key, string stylePath, string path, int tileX, int tileY, int lod, OnError errorHandler);
Example #28
0
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            Debug.Log("BYTE =>" + code);

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    serializer = new SchemaSerializer <T>();
                }
                else if (SerializerId == "fossil-delta")
                {
                    serializer = (ISerializer <T>) new FossilDeltaSerializer();
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.ERROR)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var errorCode    = Decode.DecodeNumber(bytes, it);
                var errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                var message = (Schema.Schema)Activator.CreateInstance(messageType);
                message.Decode(bytes, new Schema.Iterator {
                    Offset = 2
                });

                IMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for Schema message: " + message.GetType());
                }
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Debug.Log("ROOM_STATE_PATCH");
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                IMessageHandler handler = null;
                object          type;

                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    var message = (bytes.Length > it.Offset)
                                                ? MsgPack.Deserialize(handler.Type, new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                                                : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for: " + type);
                }
            }
        }
Example #29
0
 private static extern void addToStoreElement(string key, string stylePath, long id, double[] vertices, int vertexLength,
                                              string[] tags, int tagLength, int startLod, int endLod, OnError errorHandler);
        /// <summary>
        /// Installs a windows service. Ensures user has Logon as a service right by calling <see cref="Security.SetLogonAsAService"/>
        /// </summary>
        /// <param name="svcName">Name of the service.</param>
        /// <param name="svcDispName">Display name of the service</param>
        /// <param name="svcPath">The service file path.</param>
        /// <param name="description">The service description.</param>
        /// <param name="username">The username to run the service.</param>
        /// <param name="password">The password of the user running the service.</param>
        /// <param name="svcType">Type of the service.</param>
        /// <param name="errHandle">The error handle type.</param>
        /// <param name="svcStartMode">The service start mode.</param>
        /// <param name="interactWithDesktop">if set to true service can interact with desktop.</param>
        /// <param name="loadOrderGroup">The load order group.</param>
        /// <param name="loadOrderGroupDependencies">The load order group dependencies.</param>
        /// <param name="svcDependencies">Any service dependencies.</param>
        /// <returns><see cref="WMI.ReturnValue"/></returns>
        public ReturnValue InstallService(string svcName,
                                            string svcDispName,
                                            string svcPath,
                                            string description,
                                            string username = null,
                                            string password = null,
                                            ServiceType svcType = ServiceType.OwnProcess,
                                            OnError errHandle = OnError.UserIsNotified,
                                            StartMode svcStartMode = StartMode.Auto,
                                            bool interactWithDesktop = false,
                                            string loadOrderGroup = null,
                                            string[] loadOrderGroupDependencies = null,
                                            string[] svcDependencies = null)
        {
            var service = new ServiceInfo
                {
                    Name = svcName,
                    DisplayName = svcDispName,
                    Description = description,
                    PathName = svcPath,
                    ServiceType = svcType,
                    ErrorHandle = errHandle,
                    StartMode = svcStartMode,
                    InteractWithDesktop = interactWithDesktop,
                    LoadOrderGroup = loadOrderGroup,
                    LoadOrderGroupDependencies = loadOrderGroupDependencies,
                    Dependencies = svcDependencies,
                    Username = ComputerManager.EnsureDomain(username),
                    Password = password
                };
            return InstallService(service);

        }
Example #31
0
 private static extern void loadQuadKey(string stylePath, int tileX, int tileY, int levelOfDetails,
                                        OnMeshBuilt meshBuiltHandler, OnElementLoaded elementLoadedHandler, OnError errorHandler);
Example #32
0
 /// <summary>
 /// Deletes the folder.
 /// </summary>
 ///<param name="onError">Sets the behavior of how to handle an error</param>
 ///<returns></returns>
 public Directory Delete(OnError onError)
 {
     FailableActionExecutor.DoAction(onError, _fileSystemWrapper.DeleteDirectory, _path, true);
     return this;
 }
Example #33
0
        /// <summary> Configure utymap. Should be called before any core API usage. </summary>
        /// <param name="stringPath"> Path to string table. </param>
        /// <param name="mapDataPath">Path for map data. </param>
        /// <param name="elePath"> Path to elevation data. </param>
        /// <param name="onError"> OnError callback. </param>
        public static void Configure(string stringPath, string mapDataPath, string elePath, OnError onError)
        {
            lock (__lockObj)
            {
                // NOTE this directories should be created in advance (and some others..)
                if (!Directory.Exists(stringPath) || !Directory.Exists(mapDataPath))
                {
                    throw new DirectoryNotFoundException(String.Format("Cannot find {0} or {1}", stringPath, mapDataPath));
                }

                if (_isConfigured)
                {
                    return;
                }

                configure(stringPath, elePath, onError);

                // NOTE actually, it is possible to have multiple in-memory and persistent
                // storages at the same time.
                registerInMemoryStore(InMemoryStoreKey);
                registerPersistentStore(PersistentStoreKey, mapDataPath);

                _isConfigured = true;
            }
        }
 public abstract void LoadTerminologyLanguages(Terminology terminology, OnError onError);
Example #35
0
 /// <summary>
 ///     Adds map data to in-memory storage to specific level of detail range.
 ///     Supported formats: shapefile, osm xml, osm pbf.
 /// </summary>
 /// <param name="storageType"> Map data storage. </param>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="path"> Path to file. </param>
 /// <param name="levelOfDetails"> Specifies level of details for which data should be imported. </param>
 /// <param name="onError"> OnError callback. </param>
 public static void AddToStore(MapStorageType storageType, string stylePath, string path, Range <int> levelOfDetails, OnError onError)
 {
     addToStoreInRange(GetStoreKey(storageType), stylePath, path, levelOfDetails.Minimum, levelOfDetails.Maximum, onError);
 }
 public abstract void LoadChildConceptsFromSubset(OnLoaded onLoaded, OnError onError, string terminologyId, string queryId, string language, string parentConcept);
Example #37
0
 /// <summary>
 ///     Adds map data to in-memory storage to specific quadkey.
 ///     Supported formats: shapefile, osm xml, osm pbf.
 /// </summary>
 /// <param name="storageType"> Map data storage. </param>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="path"> Path to file. </param>
 /// <param name="quadKey"> QuadKey. </param>
 /// <param name="onError"> OnError callback. </param>
 public static void AddToStore(MapStorageType storageType, string stylePath, string path, QuadKey quadKey, OnError onError)
 {
     addToStoreInQuadKey(GetStoreKey(storageType), stylePath, path, quadKey.TileX, quadKey.TileY, quadKey.LevelOfDetail, onError);
 }
Example #38
0
 public static extern void HP_Set_FN_Client_OnError(IntPtr pListener, OnError fn);
Example #39
0
        public static void AddElementToStore(MapStorageType storageType, string stylePath, Element element, Range <int> levelOfDetails, OnError onError)
        {
            double[] coordinates = new double[element.Geometry.Length * 2];
            for (int i = 0; i < element.Geometry.Length; ++i)
            {
                coordinates[i * 2]     = element.Geometry[i].Latitude;
                coordinates[i * 2 + 1] = element.Geometry[i].Longitude;
            }

            string[] tags    = new string[element.Tags.Count * 2];
            var      tagKeys = element.Tags.Keys.ToArray();

            for (int i = 0; i < tagKeys.Length; ++i)
            {
                tags[i * 2]     = tagKeys[i];
                tags[i * 2 + 1] = element.Tags[tagKeys[i]];
            }

            addToStoreElement(GetStoreKey(storageType), stylePath, element.Id,
                              coordinates, coordinates.Length,
                              tags, tags.Length,
                              levelOfDetails.Minimum, levelOfDetails.Maximum, onError);
        }
Example #40
0
 protected void FireOnError(object sender, Exception ex)
 {
     OnError?.Invoke(sender, ex);
 }
Example #41
0
        public override int Capture(FrameInfo frame)
        {
            var res = new Result(-1);

            try
            {
                //Try to get the duplicated output frame within given time.
                res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource);

                if (FrameCount == 0 && (res.Failure || resource == null))
                {
                    //Somehow, it was not possible to retrieve the resource, frame or metadata.
                    resource?.Dispose();
                    return(FrameCount);
                }

                #region Process changes

                //Something on screen was moved or changed.
                if (info.TotalMetadataBufferSize > 0)
                {
                    //Copy resource into memory that can be accessed by the CPU.
                    using (var screenTexture = resource.QueryInterface <Texture2D>())
                    {
                        #region Moved rectangles

                        var movedRectangles = new OutputDuplicateMoveRectangle[info.TotalMetadataBufferSize];
                        DuplicatedOutput.GetFrameMoveRects(movedRectangles.Length, movedRectangles, out var movedRegionsLength);

                        for (var movedIndex = 0; movedIndex < movedRegionsLength / Marshal.SizeOf(typeof(OutputDuplicateMoveRectangle)); movedIndex++)
                        {
                            //Crop the destination rectangle to the screen area rectangle.
                            var left   = Math.Max(movedRectangles[movedIndex].DestinationRect.Left, Left - OffsetLeft);
                            var right  = Math.Min(movedRectangles[movedIndex].DestinationRect.Right, Left + Width - OffsetLeft);
                            var top    = Math.Max(movedRectangles[movedIndex].DestinationRect.Top, Top - OffsetTop);
                            var bottom = Math.Min(movedRectangles[movedIndex].DestinationRect.Bottom, Top + Height - OffsetTop);

                            //Copies from the screen texture only the area which the user wants to capture.
                            if (right > left && bottom > top)
                            {
                                //Limit the source rectangle to the available size within the destination rectangle.
                                var sourceWidth  = movedRectangles[movedIndex].SourcePoint.X + (right - left);
                                var sourceHeight = movedRectangles[movedIndex].SourcePoint.Y + (bottom - top);

                                Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0,
                                                                              new ResourceRegion(movedRectangles[movedIndex].SourcePoint.X, movedRectangles[movedIndex].SourcePoint.Y, 0, sourceWidth, sourceHeight, 1),
                                                                              StagingTexture, 0, left - (Left - OffsetLeft), top - (Top - OffsetTop));
                            }
                        }

                        #endregion

                        #region Dirty rectangles

                        var dirtyRectangles = new RawRectangle[info.TotalMetadataBufferSize];
                        DuplicatedOutput.GetFrameDirtyRects(dirtyRectangles.Length, dirtyRectangles, out var dirtyRegionsLength);

                        for (var dirtyIndex = 0; dirtyIndex < dirtyRegionsLength / Marshal.SizeOf(typeof(RawRectangle)); dirtyIndex++)
                        {
                            //Crop screen positions and size to frame sizes.
                            var left   = Math.Max(dirtyRectangles[dirtyIndex].Left, Left - OffsetLeft);
                            var right  = Math.Min(dirtyRectangles[dirtyIndex].Right, Left + Width - OffsetLeft);
                            var top    = Math.Max(dirtyRectangles[dirtyIndex].Top, Top - OffsetTop);
                            var bottom = Math.Min(dirtyRectangles[dirtyIndex].Bottom, Top + Height - OffsetTop);

                            //Copies from the screen texture only the area which the user wants to capture.
                            if (right > left && bottom > top)
                            {
                                Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(left, top, 0, right, bottom, 1), StagingTexture, 0, left - (Left - OffsetLeft), top - (Top - OffsetTop));
                            }
                        }

                        #endregion
                    }
                }

                #endregion

                #region Gets the image data

                //Gets the staging texture as a stream.
                var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None, out var stream);

                if (data.IsEmpty)
                {
                    Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
                    stream?.Dispose();
                    resource?.Dispose();
                    return(FrameCount);
                }

                //Set frame details.
                FrameCount++;
                frame.Path       = $"{Project.FullPath}{FrameCount}.png";
                frame.Delay      = FrameRate.GetMilliseconds();
                frame.DataLength = stream.Length;
                frame.Data       = new byte[stream.Length];

                //BGRA32 is 4 bytes.
                for (var height = 0; height < Height; height++)
                {
                    stream.Position = height * data.RowPitch;
                    Marshal.Copy(new IntPtr(stream.DataPointer.ToInt64() + height * data.RowPitch), frame.Data, height * Width * 4, Width * 4);
                }

                BlockingCollection.Add(frame);

                #endregion

                Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);

                resource?.Dispose();
                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
            {
                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code)
            {
                //When the device gets lost or reset, the resources should be instantiated again.
                DisposeInternal();
                Initialize();

                return(FrameCount);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX.");

                Application.Current.Dispatcher.Invoke(() => OnError.Invoke(ex));
                return(FrameCount);
            }
            finally
            {
                try
                {
                    //Only release the frame if there was a sucess in capturing it.
                    if (res.Success)
                    {
                        DuplicatedOutput.ReleaseFrame();
                    }
                }
                catch (Exception e)
                {
                    LogWriter.Log(e, "It was not possible to release the frame.");
                }
            }
        }
        public static ReturnValue InstallService(string svcName, string svcDispName, string svcPath, ServiceType svcType,
            OnError errHandle, StartMode svcStartMode, bool interactWithDesktop, string svcStartName, string svcPassword,
            string loadOrderGroup, string[] loadOrderGroupDependencies, string[] svcDependencies)
        {
            var mc = new ManagementClass("Win32_Service");
            ManagementBaseObject inParams = mc.GetMethodParameters("create");
            inParams["Name"] = svcName;
            inParams["DisplayName"] = svcDispName;
            inParams["PathName"] = svcPath;
            inParams["ServiceType"] = svcType;
            inParams["ErrorControl"] = errHandle;
            inParams["StartMode"] = svcStartMode.ToString();
            inParams["DesktopInteract"] = interactWithDesktop;
            inParams["StartName"] = svcStartName;
            inParams["StartPassword"] = svcPassword;
            inParams["LoadOrderGroup"] = loadOrderGroup;
            inParams["LoadOrderGroupDependencies"] = loadOrderGroupDependencies;
            inParams["ServiceDependencies"] = svcDependencies;

            try
            {
                ManagementBaseObject outParams = mc.InvokeMethod("create", inParams, null);

                return (ReturnValue) Enum.Parse(typeof (ReturnValue), outParams["ReturnValue"].ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #43
0
        public int Capture2(FrameInfo frame)
        {
            var res = new Result(-1);

            try
            {
                //Try to get the duplicated output frame within given time.
                res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource);

                //Somehow, it was not possible to retrieve the resource or any frame.
                if (res.Failure || resource == null || info.AccumulatedFrames == 0)
                {
                    resource?.Dispose();
                    return(FrameCount);
                }

                //Copy resource into memory that can be accessed by the CPU.
                using (var screenTexture = resource.QueryInterface <Texture2D>())
                {
                    //Copies from the screen texture only the area which the user wants to capture.
                    Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), StagingTexture, 0);
                }

                //Get the desktop capture texture.
                var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None, out var stream);

                if (data.IsEmpty)
                {
                    Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);

                    stream?.Dispose();
                    resource.Dispose();
                    return(FrameCount);
                }

                #region Get image data

                //Set frame details.
                FrameCount++;
                frame.Path       = $"{Project.FullPath}{FrameCount}.png";
                frame.Delay      = FrameRate.GetMilliseconds();
                frame.DataLength = stream.Length;
                frame.Data       = new byte[stream.Length];

                //BGRA32 is 4 bytes.
                for (var height = 0; height < Height; height++)
                {
                    stream.Position = height * data.RowPitch;
                    Marshal.Copy(new IntPtr(stream.DataPointer.ToInt64() + height * data.RowPitch), frame.Data, height * Width * 4, Width * 4);
                }

                BlockingCollection.Add(frame);

                #endregion

                Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);

                resource.Dispose();
                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
            {
                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code)
            {
                //When the device gets lost or reset, the resources should be instantiated again.
                DisposeInternal();
                Initialize();

                return(FrameCount);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX.");

                Application.Current.Dispatcher.Invoke(() => OnError.Invoke(ex));
                return(FrameCount);
            }
            finally
            {
                try
                {
                    //Only release the frame if there was a sucess in capturing it.
                    if (res.Success)
                    {
                        DuplicatedOutput.ReleaseFrame();
                    }
                }
                catch (Exception e)
                {
                    LogWriter.Log(e, "It was not possible to release the frame.");
                }
            }
        }
Example #44
0
 private static extern void addToStoreElement(string key, string stylePath, long id, double[] vertices, int vertexLength, 
     string[] tags, int tagLength, int startLod, int endLod, OnError errorHandler);
Example #45
0
        public int CaptureWithCursor2(FrameInfo frame)
        {
            var res = new Result(-1);

            try
            {
                //Try to get the duplicated output frame within given time.
                res = DuplicatedOutput.TryAcquireNextFrame(0, out var info, out var resource);

                //Checks how to proceed with the capture. It could have failed, or the screen, cursor or both could have been captured.
                if (res.Failure || resource == null || (info.AccumulatedFrames == 0 && info.LastMouseUpdateTime <= LastProcessTime))
                {
                    //Somehow, it was not possible to retrieve the resource, frame or metadata.
                    resource?.Dispose();
                    return(FrameCount);
                }
                else if (info.AccumulatedFrames == 0 && info.LastMouseUpdateTime > LastProcessTime)
                {
                    //Gets the cursor shape if the screen hasn't changed in between, so the cursor will be available for the next frame.
                    GetCursor(null, info, frame);

                    resource.Dispose();
                    return(FrameCount);

                    //TODO: if only the mouse changed, but there's no frame accumulated, but there's data in the texture from the previous frame, I need to merge with the cursor and add to the list.
                }

                //Saves the most recent capture time.
                LastProcessTime = Math.Max(info.LastPresentTime, info.LastMouseUpdateTime);

                //Copy resource into memory that can be accessed by the CPU.
                using (var screenTexture = resource.QueryInterface <Texture2D>())
                {
                    //Copies from the screen texture only the area which the user wants to capture.
                    Device.ImmediateContext.CopySubresourceRegion(screenTexture, 0, new ResourceRegion(TrueLeft, TrueTop, 0, TrueRight, TrueBottom, 1), BackingTexture, 0);

                    //Copy the captured desktop texture into a staging texture, in order to show the mouse cursor and not make the captured texture dirty with it.
                    Device.ImmediateContext.CopyResource(BackingTexture, StagingTexture);

                    //Gets the cursor image and merges with the staging texture.
                    GetCursor(StagingTexture, info, frame);
                }

                //Get the desktop capture texture.
                var data = Device.ImmediateContext.MapSubresource(StagingTexture, 0, MapMode.Read, MapFlags.None, out var stream);

                if (data.IsEmpty)
                {
                    Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
                    stream?.Dispose();
                    resource.Dispose();
                    return(FrameCount);
                }

                #region Get image data

                //Set frame details.
                FrameCount++;
                frame.Path       = $"{Project.FullPath}{FrameCount}.png";
                frame.Delay      = FrameRate.GetMilliseconds();
                frame.DataLength = stream.Length;
                frame.Data       = new byte[stream.Length];

                //BGRA32 is 4 bytes.
                for (var height = 0; height < Height; height++)
                {
                    stream.Position = height * data.RowPitch;
                    Marshal.Copy(new IntPtr(stream.DataPointer.ToInt64() + height * data.RowPitch), frame.Data, height * Width * 4, Width * 4);
                }

                BlockingCollection.Add(frame);

                #endregion

                Device.ImmediateContext.UnmapSubresource(StagingTexture, 0);
                stream.Dispose();
                resource.Dispose();

                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
            {
                return(FrameCount);
            }
            catch (SharpDXException se) when(se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceRemoved.Result.Code || se.ResultCode.Code == SharpDX.DXGI.ResultCode.DeviceReset.Result.Code)
            {
                //When the device gets lost or reset, the resources should be instantiated again.
                DisposeInternal();
                Initialize();

                return(FrameCount);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "It was not possible to finish capturing the frame with DirectX.");

                MajorCrashHappened = true;
                Application.Current.Dispatcher.Invoke(() => OnError.Invoke(ex));
                return(FrameCount);
            }
            finally
            {
                try
                {
                    //Only release the frame if there was a sucess in capturing it.
                    if (res.Success)
                    {
                        DuplicatedOutput.ReleaseFrame();
                    }
                }
                catch (Exception e)
                {
                    LogWriter.Log(e, "It was not possible to release the frame.");
                }
            }
        }
Example #46
0
 private static extern void addToStoreInRange(string key, string stylePath, string path, int startLod, int endLod, OnError errorHandler);
Example #47
0
 public void Error(OnErrorEventArgs eventArgs)
 {
     OnError?.Invoke(this, eventArgs);
 }
Example #48
0
 private static extern void loadQuadKey(string stylePath, int tileX, int tileY, int levelOfDetails,
     OnMeshBuilt meshBuiltHandler, OnElementLoaded elementLoadedHandler, OnError errorHandler);
Example #49
0
        public async Task OpenAsync()
        {
            await ExecuteRetryPolicy();

            subscriptions.Clear();

            if (channel != null)
            {
                try
                {
                    channel.Dispose();
                    channel = null;
                    client  = null;
                    logger?.LogDebug("Disposed internal channel.");
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "Fault disposing internal channel.");
                }
            }

            try
            {
                channel = new WebSocketClientChannel(endpointUrl, securityToken, "mqtt", new WebSocketConfig(),
                                                     CancellationToken.None);
                client = new PiraeusMqttClient(new MqttConfig(180), channel);
                client.OnChannelError       += Client_OnChannelError;
                client.OnChannelStateChange += Client_OnChannelStateChange;

                string         sessionId = Guid.NewGuid().ToString();
                ConnectAckCode code      = await client.ConnectAsync(sessionId, "JWT", securityToken, 180);

                if (code != ConnectAckCode.ConnectionAccepted)
                {
                    logger?.LogWarning($"Module client connect return code = '{code}'.");
                    OnError?.Invoke(this,
                                    new ChannelErrorEventArgs(channel.Id,
                                                              new Exception($"Module channel failed to open with code = {code}")));
                }
                else
                {
                    logger?.LogInformation("Module client connected.");
                    foreach (var slave in config.Slaves)
                    {
                        string inputPiSystem = UriGenerator.GetRtuPiSystem(config.Hostname, config.VirtualRtuId,
                                                                           config.DeviceId, slave.UnitId, true);
                        await client.SubscribeAsync(inputPiSystem, QualityOfServiceLevelType.AtMostOnce,
                                                    ModuleReceived);

                        logger?.LogDebug($"Module client subscribed to '{inputPiSystem}'");
                    }

                    try
                    {
                        diag = new DiagnosticsChannel(config, client, logger);
                        diag.StartAsync().GetAwaiter();
                    }
                    catch (Exception ex)
                    {
                        diag = null;
                        logger?.LogError(ex, "Diagnostics channel faulted.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Fault opening module channel.");
            }
        }
Example #50
0
 /// <summary>
 ///     Adds map data to in-memory storage to specific level of detail range.
 ///     Supported formats: shapefile, osm xml, osm pbf.
 /// </summary>
 /// <param name="storageType"> Map data storage. </param>
 /// <param name="stylePath"> Stylesheet path. </param>
 /// <param name="path"> Path to file. </param>
 /// <param name="levelOfDetails"> Specifies level of details for which data should be imported. </param>
 /// <param name="onError"> OnError callback. </param>
 public static void AddToStore(MapStorageType storageType, string stylePath, string path, Range<int> levelOfDetails, OnError onError)
 {
     addToStoreInRange(GetStoreKey(storageType), stylePath, path, levelOfDetails.Minimum, levelOfDetails.Maximum, onError);
 }
Example #51
0
 private void Client_OnChannelError(object sender, ChannelErrorEventArgs args)
 {
     OnError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, args.Error));
 }
Example #52
0
        /// <summary> Configure utymap. Should be called first. </summary>
        /// <param name="stringPath"> Path to string table. </param>
        /// <param name="mapDataPath">Path for map data. </param>
        /// <param name="elePath"> Path to elevation data. </param>
        /// <param name="onError"> OnError callback. </param>
        public static void Configure(string stringPath, string mapDataPath, string elePath, OnError onError)
        {
            configure(stringPath, elePath, onError);

            // NOTE actually, it is possible to have multiple in-memory and persistent
            // storages at the same time.
            registerInMemoryStore(InMemoryStoreKey);
            registerPersistentStore(PersistentStoreKey, mapDataPath);

            // NOTE core library can't create directories so far
            for (int i = 1; i <= 16; ++i)
                Directory.CreateDirectory(Path.Combine(mapDataPath, i.ToString()));
        }
Example #53
0
 private void ErrorEventMainThread(object obj)
 {
     OnError?.Invoke(this, (EventArgs)obj);
 }