Esempio n. 1
0
        public bool SendMessage(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return(false);
            }
            if (!NativeClient.Connected)
            {
                return(false);
            }

            var strm   = NativeClient.GetStream();
            var writer = new StreamWriter(strm)
            {
                AutoFlush = true
            };

            try
            {
                Logger?.Log.Debug($"<ecos> {msg}");

                if (NativeClient.Connected)
                {
                    writer.WriteLine(msg);
                }

                return(true);
            }
            catch (Exception ex)
            {
                SendFailed?.Invoke(this, ex);
                Logger?.Log?.Error("SendMessage failed", ex);
                return(false);
            }
        }
Esempio n. 2
0
        public async Task HandleLines()
        {
            try
            {
                var strm = NativeClient.GetStream();
                using var reader = new StreamReader(strm, Encoding.UTF8);
                string line;
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    LineReceived?.Invoke(this, line);
                }
            }
            catch (IOException ex)
            {
                //Logger?.Log?.Error("HandleLines::IOException", ex);
                Failed?.Invoke(this, new MessageEventArgs(ex.Message));
            }
            catch (InvalidOperationException ex)
            {
                Logger?.Log?.Error("HandleLines::InvalidOperationException", ex);
                Failed?.Invoke(this, new MessageEventArgs(ex.Message));
            }

            Disconnected?.Invoke(this, null !);

            await Task.Delay(1000);
        }
Esempio n. 3
0
        private void CreateRpcConnection(string server, RpcProtocol protocol, NetworkCredential credential = null)
        {
            EndpointBindingInfo binding;

            switch (protocol)
            {
            case RpcProtocol.TCP:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_ip_tcp, server, null);
                break;

            case RpcProtocol.SMB:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_np, server, DrsNamedPipeName);
                if (credential != null)
                {
                    // Connect named pipe
                    this.npConnection = new NamedPipeConnection(server, credential);
                }
                break;

            default:
                // TODO: Custom exception type
                // TODO: Extract as string
                throw new Exception("Unsupported RPC protocol");
            }
            NetworkCredential rpcCredential = credential ?? Client.Self;

            this.rpcConnection = new NativeClient(binding);
            this.rpcConnection.AuthenticateAs(rpcCredential);
        }
Esempio n. 4
0
        protected override PackageCollection GetResult()
        {
            var operationStatus = NativeClient.GetListOperationData(Id);
            var packageList     = operationStatus.packageList.Where(p => p.type != ShimPackageType);

            return(new PackageCollection(packageList, operationStatus.error));
        }
Esempio n. 5
0
        private void FetchError()
        {
            // We assume the request is empty when the Id is 0 and skip error fetching.
            // This happens during the serialization process as empty instances are created
            // in place of null references.
            if (Id == 0 || m_ErrorFetched || NativeStatus.ConvertToManaged() != StatusCode.Failure)
            {
                return;
            }

            m_ErrorFetched = true;
            m_Error        = NativeClient.GetOperationError(Id);

            if (m_Error == null)
            {
                if (NativeStatus == NativeStatusCode.NotFound)
                {
                    m_Error = new Error(NativeErrorCode.NotFound, "Operation not found");
                }
                else
                {
                    m_Error = new Error(NativeErrorCode.Unknown, "Unknown error");
                }
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (this.drsConnection != null)
            {
                this.drsConnection.Dispose();
                this.drsConnection = null;
            }

            if (this.rpcConnection != null)
            {
                this.rpcConnection.Dispose();
                this.rpcConnection = null;
            }

            if (this.npConnection != null)
            {
                this.npConnection.Dispose();
                this.npConnection = null;
            }
        }
        private void CreateRpcConnection(string server, RpcProtocol protocol, NetworkCredential credential = null)
        {
            EndpointBindingInfo binding;

            switch (protocol)
            {
            case RpcProtocol.TCP:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_ip_tcp, server, null);
                break;

            case RpcProtocol.SMB:
                binding = new EndpointBindingInfo(RpcProtseq.ncacn_np, server, DrsNamedPipeName);
                if (credential != null)
                {
                    // Connect named pipe
                    this.npConnection = new NamedPipeConnection(server, credential);
                }
                break;

            default:
                // TODO: Extract as string
                throw new NotImplementedException("The requested RPC protocol is not supported.");
            }
            this.rpcConnection = new NativeClient(binding);

            NetworkCredential rpcCredential = credential ?? Client.Self;
            string            spn           = String.Format(ServicePrincipalNameFormat, server);

            this.rpcConnection.AuthenticateAs(spn, rpcCredential, RPC_C_AUTHN_LEVEL.RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_AUTHN.RPC_C_AUTHN_GSS_NEGOTIATE);
        }
Esempio n. 8
0
        protected override PackageCollection GetResult()
        {
            var operationStatus = NativeClient.GetListOperationData(Id);
            var packageList     = operationStatus.packageList.Select(p => (PackageInfo)p);

            return(new PackageCollection(packageList, operationStatus.error));
        }
Esempio n. 9
0
 [MethodImpl(MethodImplOptions.Synchronized)] private static void EnsureAssemblyInit()
 {
     if (!_previouslyInitialized)
     {
         NativeClient.EnsureAssemblyInit();
         _previouslyInitialized = true;
     }
 }
Esempio n. 10
0
        protected override PackageCollection GetResult()
        {
            OperationStatus listOperationData = NativeClient.GetListOperationData(base.Id);
            IEnumerable <UnityEditor.PackageManager.PackageInfo> packages = from p in listOperationData.packageList
                                                                            select p;

            return(new PackageCollection(packages, listOperationData.error));
        }
        bool CheckXiaomiPackageVersions()
        {
            if (isVersionInitialized)
            {
                return(true);
            }

            NativeStatusCode getCurrentVersionOperationStatus;

            if (getCurrentVersionOperationId < 0)
            {
                getCurrentVersionOperationStatus = NativeClient.List(out getCurrentVersionOperationId);
            }
            else
            {
                getCurrentVersionOperationStatus = NativeClient.GetOperationStatus(getCurrentVersionOperationId);
            }

            // Reset and return false if it fails with StatusCode.Error or Status.NotFound.
            if (getCurrentVersionOperationStatus > NativeStatusCode.Done)
            {
                getCurrentVersionOperationId = -1;
                return(false);
            }

            NativeStatusCode getLatestVersionOperationStatus;

            if (getLatestVersionOperationId < 0)
            {
                getLatestVersionOperationStatus = NativeClient.Search(out getLatestVersionOperationId, xiaomiPackageName);
            }
            else
            {
                getLatestVersionOperationStatus = NativeClient.GetOperationStatus(getLatestVersionOperationId);
            }

            // Reset and return false if it fails with StatusCode.Error or Status.NotFound.
            if (getLatestVersionOperationStatus > NativeStatusCode.Done)
            {
                getLatestVersionOperationId = -1;
                return(false);
            }

            // Get version info if both operations are done.
            if (getCurrentVersionOperationStatus == NativeStatusCode.Done && getLatestVersionOperationStatus == NativeStatusCode.Done)
            {
                CheckPackmanOperation(getCurrentVersionOperationId, PackmanOperationType.List);
                CheckPackmanOperation(getLatestVersionOperationId, PackmanOperationType.Search);

                System.Console.WriteLine("Current xiaomi package version is " + (string.IsNullOrEmpty(currentXiaomiPackageVersion) ? "empty" : currentXiaomiPackageVersion));
                System.Console.WriteLine("Latest xiaomi package version is " + (string.IsNullOrEmpty(latestXiaomiPackageVersion) ? "empty" : latestXiaomiPackageVersion));

                isVersionInitialized = true;
                return(true);
            }

            return(false);
        }
        void ExtractLatestXiaomiPackageInfo(long operationId)
        {
            var packageList = NativeClient.GetSearchOperationData(operationId);

            foreach (var package in packageList)
            {
                latestXiaomiPackageVersion = package.version;
            }
        }
Esempio n. 13
0
        internal Task <string> SendRpc(string method, object[] args, Dictionary <string, object> in3 = null)
        {
            if (Configuration.HasChanged())
            {
                NativeClient.ApplyConfiguration(Configuration);
            }

            return(new Runner(NativeClient).Run(RpcHandler.To(method, args, in3)));
        }
Esempio n. 14
0
        public void TestErrorsNoServerListening()
        {
            var endPointName = Implementer + DateTime.Now.Ticks;

            var endpointBindingInfo = new EndpointBindingInfo(RpcProtseq.ncalrpc, null, endPointName);


            var client = new NativeClient(endpointBindingInfo);

            CallErrorHandlingServer(client.Binding);
        }
Esempio n. 15
0
 private IN3(Chain chainId)
 {
     // Starting to get convoluted. Need to think of a better way.
     Transport     = new DefaultTransport();
     Storage       = new InMemoryStorage();
     Signer        = new Crypto.SimpleWallet(this);
     NativeClient  = new NativeClient(this, chainId);
     Btc           = new Btc.Api(this);
     Eth1          = new Eth1.Api(this);
     Crypto        = new Crypto.Api(this);
     Ipfs          = new Ipfs.Api(this);
     Configuration = NativeClient.ReadConfiguration();
 }
        bool CheckPackmanOperation(long operationId, PackmanOperationType operationType)
        {
            NativeStatusCode statusCode = NativeClient.GetOperationStatus(operationId);

            if (statusCode == NativeStatusCode.NotFound)
            {
                Debug.LogError("OperationID " + operationId + " Not Found");
                return(true);
            }
            else if (statusCode == NativeStatusCode.Error)
            {
                Error error = NativeClient.GetOperationError(operationId);
                Debug.LogError("OperationID " + operationId + " failed with Error: " + error);
                return(true);
            }
            else if (statusCode == NativeStatusCode.InProgress || statusCode == NativeStatusCode.InQueue)
            {
                return(false);
            }
            else if (statusCode == NativeStatusCode.Done)
            {
                System.Console.WriteLine("OperationID " + operationId + " Done");
                switch (operationType)
                {
                case PackmanOperationType.List:
                    ExtractCurrentXiaomiPackageInfo(operationId);
                    break;

                case PackmanOperationType.Add:
                    currentXiaomiPackageVersion = latestXiaomiPackageVersion;
                    xiaomiPackageInstalled      = true;
                    break;

                case PackmanOperationType.Remove:
                    currentXiaomiPackageVersion = "";
                    xiaomiPackageInstalled      = false;
                    break;

                case PackmanOperationType.Search:
                    ExtractLatestXiaomiPackageInfo(operationId);
                    break;

                default:
                    System.Console.WriteLine("Type " + operationType + " Not Supported");
                    break;
                }
                return(true);
            }

            return(true);
        }
        void ExtractCurrentXiaomiPackageInfo(long operationId)
        {
            // Get the package list to find if xiaomi package has been installed.
            OperationStatus operationStatus = NativeClient.GetListOperationData(operationId);

            foreach (var package in operationStatus.packageList)
            {
                if (package.packageId.StartsWith(xiaomiPackageName))
                {
                    xiaomiPackageInstalled      = true;
                    currentXiaomiPackageVersion = package.version;
                }
            }
        }
Esempio n. 18
0
        internal void SetUserInfo(RaygunIdentifierMessage userInfo)
        {
            if (_activeBatch != null)
            {
                // Each batch is tied to the UserInfo at the time it's created.
                // So when the user info changes, we end any current batch, so the next one can pick up the new user info.
                _activeBatch.Done();
            }

            // Check info is valid
            if (string.IsNullOrWhiteSpace(userInfo?.Identifier) || string.IsNullOrEmpty(userInfo.Identifier))
            {
                userInfo = GetAnonymousUserInfo();
            }

            // Has the user changed ?
            if (_userInfo != null &&
                _userInfo.Identifier != userInfo.Identifier &&
                _userInfo.IsAnonymous == false)
            {
                if (!string.IsNullOrEmpty(_sessionId))
                {
                    SendPulseSessionEventNow(RaygunPulseSessionEventType.SessionEnd);
                    _userInfo = userInfo;
                    _user     = userInfo.Identifier;
                    SendPulseSessionEventNow(RaygunPulseSessionEventType.SessionStart);
                }
            }
            else
            {
                _userInfo = userInfo;
                _user     = userInfo.Identifier;
            }

            // Pass on the info to the native Raygun reporter.
            if (NativeClient != null)
            {
                var info = new NativeRaygunUserInfo();
                info.Identifier  = _userInfo.Identifier;
                info.IsAnonymous = _userInfo.IsAnonymous;
                info.Email       = _userInfo.Email;
                info.FullName    = _userInfo.FullName;
                info.FirstName   = _userInfo.FirstName;
                NativeClient.IdentifyWithUserInfo(info);
            }
        }
Esempio n. 19
0
        public void TestCppExceptions()
        {
            var server = GetErrorHandlingServer();

            var serverInterface = (RPC_SERVER_INTERFACE)Marshal.PtrToStructure(server, typeof(RPC_SERVER_INTERFACE));
            var endPointName    = Implementer + DateTime.Now.Ticks + serverInterface.InterfaceId.SyntaxGUID.ToString("N");

            var endpointBindingInfo = new EndpointBindingInfo(RpcProtseq.ncalrpc, null, endPointName);

            NativeHost.StartServer(endpointBindingInfo, server);

            RPC_STATUS status;

            var client = new NativeClient(endpointBindingInfo);

            CallErrorThrowingServer(client.Binding);
        }
Esempio n. 20
0
        public void Disconnect()
        {
            try
            {
                if (NativeClient == null)
                {
                    return;
                }

                NativeClient.Close();
                NativeClient.Dispose();
                NativeClient = null;
            }
            catch
            {
                // ignore
            }
        }
Esempio n. 21
0
        public static async Task Main()
        {
            NativeClient.Logging.VerbosityLevel = 1;
            var eval          = new ScriptEvaluator();
            var cts           = new CancellationTokenSource();
            var ct            = cts.Token;
            var canceltasksrc = new TaskCompletionSource <bool>();

            ct.Register(canceltasksrc.SetCanceled);
            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("stopping...");
                cts.Cancel();
                e.Cancel = true;
            };

            using var client = NativeClient.Create(AuthHandler);
            waitAuthReady    = new TaskCompletionSource <bool>();


            await Task.WhenAny(waitAuthReady.Task, canceltasksrc.Task);

            if (waitAuthReady.Task.IsCompleted)
            {
                var me = await client.GetMe();

                if (!(me.Type is UserTypeBot))
                {
                    await client.SendMessage(me.Id, inputMessageContent : new InputMessageText("hello from TDLibCore"));
                }
                Console.WriteLine(me.ToJsonString(indented: true));
                Console.WriteLine(eval.FormatObject(me));
                await Task.Run(async() =>
                {
                    await eval.Initialize(new ScriptingGlobals {
                        client = client
                    });
                    await eval.StartInteractive();
                }, cts.Token);
            }
            await client.Close();
        }
Esempio n. 22
0
        public void TestCallback()
        {
            var server = GetExplicitWithCallbacksServer();

            var endPointName = Implementer + DateTime.Now.Ticks;

            var serverInterface = (RPC_SERVER_INTERFACE)Marshal.PtrToStructure(server, typeof(RPC_SERVER_INTERFACE));

            var endpointBindingInfo = new EndpointBindingInfo(RpcProtseq.ncalrpc, null, endPointName);

            NativeHost.StartServer(endpointBindingInfo, server);



            RPC_STATUS status;


            var client = new NativeClient(endpointBindingInfo);

            CallExplicitWithCallbacksServer(client.Binding);
        }
Esempio n. 23
0
        private void FetchError()
        {
            if (m_ErrorFetched || NativeStatus.ConvertToManaged() != StatusCode.Failure)
            {
                return;
            }

            m_ErrorFetched = true;
            m_Error        = NativeClient.GetOperationError(Id);

            if (m_Error == null)
            {
                if (NativeStatus == NativeStatusCode.NotFound)
                {
                    m_Error = new Error(ErrorCode.NotFound, "Operation not found");
                }
                else
                {
                    m_Error = new Error(ErrorCode.Unknown, "Unknown error");
                }
            }
        }
        private unsafe void LoadFromConfigHelper()
        {
            var nativeResult    = NativeClient.FabricGetDefaultRollingUpgradeMonitoringPolicy();
            var nativePolicyPtr = nativeResult.get_Policy();

            ReleaseAssert.AssertIf(nativePolicyPtr == IntPtr.Zero, string.Format(CultureInfo.CurrentCulture, StringResources.Error_NativeDataNull_Formatted, "nativePolicyPtr"));

            var nativePolicy = (NativeTypes.FABRIC_ROLLING_UPGRADE_MONITORING_POLICY *)nativePolicyPtr;

            this.FailureAction           = (UpgradeFailureAction)nativePolicy->FailureAction;
            this.HealthCheckWaitDuration = FromNativeTimeInSeconds(nativePolicy->HealthCheckWaitDurationInSeconds);
            this.HealthCheckRetryTimeout = FromNativeTimeInSeconds(nativePolicy->HealthCheckRetryTimeoutInSeconds);
            this.UpgradeTimeout          = FromNativeTimeInSeconds(nativePolicy->UpgradeTimeoutInSeconds);
            this.UpgradeDomainTimeout    = FromNativeTimeInSeconds(nativePolicy->UpgradeDomainTimeoutInSeconds);

            if (nativePolicy->Reserved != IntPtr.Zero)
            {
                var ex1Ptr = (NativeTypes.FABRIC_ROLLING_UPGRADE_MONITORING_POLICY_EX1 *)nativePolicy->Reserved;
                this.HealthCheckStableDuration = FromNativeTimeInSeconds(ex1Ptr->HealthCheckStableDurationInSeconds);
            }

            GC.KeepAlive(nativeResult);
        }
Esempio n. 25
0
 protected override CachedPackageInfo[] GetResult()
 {
     return(NativeClient.GetGetCachedPackagesOperationData(Id));
 }
Esempio n. 26
0
 protected override PackageInfo[] GetResult()
 {
     return(NativeClient.GetSearchOperationData(Id).Select(p => (PackageInfo)p).ToArray());
 }
Esempio n. 27
0
 public void Crash()
 {
     NativeClient.Crash();
 }
Esempio n. 28
0
 protected override PackageInfo GetResult()
 {
     return(NativeClient.GetAddOperationData(Id));
 }
 protected override SearchResults GetResult()
 {
     return(NativeClient.GetSearchOperationData(Id));
 }
Esempio n. 30
0
 protected override PackOperationResult GetResult()
 {
     return(NativeClient.GetPackOperationData(Id));
 }