Beispiel #1
0
 protected void OnPropertyChanged(string propertyName)
 {
     if (PropertyChanged != null)
     {
         Portability.DispatchAction(() => PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
     }
 }
 private string UnwrapRazorBlock(RazorBlock block)
 {
     return(RunWithSingleWriter(delegate(TextWriter writer)
     {
         Portability.RenderHtmlString(block(null), writer);
     }));
 }
Beispiel #3
0
 public TsProgram(ushort programNumber, TableStream programMapStream)
 {
     ProgramNumber    = programNumber;
     ProgramMapStream = programMapStream;
     ProgramMapStream.UnitReceived += ProgramMapTableReceived;
     Streams = Portability.CreateList <TsStream>();
 }
Beispiel #4
0
        public DescriptionTable(byte[] buffer, int offset, int length) : base(buffer, offset, length)
        {
            Descriptors = Portability.CreateList <TsDescriptor>();

            while (_position < _sectionLengthStartOffset + SectionLength - 4 && _position < offset + length - 4)
            {
                var descriptor = new UnknownDescriptor(buffer, _position);
                Descriptors.Add(descriptor);
                _position += descriptor.Length;
            }
        }
        public static async Task <SynchronizerViewModel> Startup(BlockChainIdentity activeNetwork, string walletAppDataDir,
                                                                 bool searchPath, string extraArgs)
        {
            if (activeNetwork == null)
            {
                throw new ArgumentNullException(nameof(activeNetwork));
            }
            if (walletAppDataDir == null)
            {
                throw new ArgumentNullException(nameof(walletAppDataDir));
            }
            if (extraArgs == null)
            {
                throw new ArgumentNullException(nameof(extraArgs));
            }

            // Begin the asynchronous reading of the certificate before starting the wallet
            // process.  This uses filesystem events to know when to begin reading the certificate,
            // and if there is too much delay between wallet writing the cert and this process
            // beginning to observe the change, the event may never fire and the cert won't be read.
            var rootCertificateTask = TransportSecurity.ReadModifiedCertificateAsync(walletAppDataDir);

            string walletProcessPath = null;

            if (!searchPath)
            {
                walletProcessPath = Portability.ExecutableInstallationPath(
                    Environment.OSVersion.Platform, AssemblyResources.Organization, WalletProcess.ProcessName);
            }
            KillLeftoverWalletProcess(activeNetwork);
            var walletProcess = WalletProcess.Start(activeNetwork, walletAppDataDir, walletProcessPath, extraArgs);

            WalletClient walletClient;

            try
            {
                var listenAddress   = WalletProcess.RpcListenAddress("localhost", activeNetwork);
                var rootCertificate = await rootCertificateTask;
                walletClient = await WalletClient.ConnectAsync(listenAddress, rootCertificate);
            }
            catch (Exception)
            {
                if (walletProcess.HasExited)
                {
                    throw new Exception("Wallet process closed unexpectedly");
                }
                walletProcess.KillIfExecuting();
                throw;
            }

            return(new SynchronizerViewModel(walletProcess, walletClient));
        }
Beispiel #6
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var args = ProcessArguments.ParseArguments(e.Args);

            var activeNetwork = args.IntendedNetwork;

            WalletClient.Initialize();

            var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                      AssemblyResources.Organization, AssemblyResources.ProductName);

            Directory.CreateDirectory(appDataDir);

            var startupTask = Task.Run(async() =>
            {
                // Begin the asynchronous reading of the certificate before starting the wallet
                // process.  This uses filesystem events to know when to begin reading the certificate,
                // and if there is too much delay between wallet writing the cert and this process
                // beginning to observe the change, the event may never fire and the cert won't be read.
                var rootCertificateTask = TransportSecurity.ReadModifiedCertificateAsync(appDataDir);

                var walletProcess = WalletProcess.Start(activeNetwork, appDataDir);

                WalletClient walletClient;
                try
                {
                    var listenAddress   = WalletProcess.RpcListenAddress("localhost", activeNetwork);
                    var rootCertificate = await rootCertificateTask;
                    walletClient        = await WalletClient.ConnectAsync(listenAddress, rootCertificate);
                }
                catch (Exception)
                {
                    if (walletProcess.HasExited)
                    {
                        throw new Exception("Wallet process closed unexpectedly");
                    }
                    walletProcess.KillIfExecuting();
                    throw;
                }

                return(Tuple.Create(walletProcess, walletClient));
            });

            startupTask.Wait();
            var startupResult = startupTask.Result;

            ActiveNetwork             = activeNetwork;
            WalletRpcProcess          = startupResult.Item1;
            WalletRpcClient           = startupResult.Item2;
            Application.Current.Exit += Application_Exit;
        }
Beispiel #7
0
        public void LaunchPaymetheus()
        {
            if (Interlocked.Exchange(ref _paymetheusProcessStarted, 1) != 0)
            {
                throw new InvalidOperationException("Paymetheus already started");
            }

            const string processName = "Paymetheus";
            var          fileName    = processName;

            if (!parsedArguments.SearchPathForProcesses)
            {
                fileName = Portability.ExecutableInstallationPath(Environment.OSVersion.Platform, "Decred", processName);
            }

            var procInfo = new ProcessStartInfo
            {
                FileName        = fileName,
                Arguments       = string.Join(" ", arguments), // pass arguments vertabim
                UseShellExecute = false,
            };

            _paymetheusProcess = Process.Start(procInfo);

            // For now only hide the launcher when running on mainnet.
            if (parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    App.Current.MainWindow.Hide();
                });
            }

            Task.Run(async() =>
            {
                await _paymetheusProcess.WaitForExitAsync();
                if (parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet)
                {
                    await App.Current.Dispatcher.InvokeAsync(() =>
                    {
                        App.Current.MainWindow.Show();
                    });
                }
                SignalConsensusServerShutdown();
            });
        }
Beispiel #8
0
        private object ExecuteUploadChunkCommand(IDictionary <string, object> args)
        {
            FileChunkMetadata fileChunkMetadata = JsonConvert.DeserializeObject <FileChunkMetadata>(GetCommandParam("chunkMetadata", args));
            string            uploadedFileName  = GetUploadedFileName(fileChunkMetadata.UploadId);

            ValidateFileExtension(fileChunkMetadata.FileName);
            ValidateMaxUploadFileSize(fileChunkMetadata.FileSize);
            using (Stream chunkStream = Portability.GetRequestFileStream(FileSystemConfiguration.Request))
            {
                UploadFileChunk(uploadedFileName, chunkStream);
            }
            if (fileChunkMetadata.Index == fileChunkMetadata.TotalCount - 1)
            {
                string destinationKey = Path.Combine(GetCommandParam("destinationId", args), fileChunkMetadata.FileName);
                FileSystemProvider.MoveUploadedFile(new FileInfo(uploadedFileName), destinationKey);
            }
            return(null);
        }
Beispiel #9
0
        public ProgramMap(byte[] buffer, int offset)
        {
            var position = offset;

            StreamType       = (StreamType)buffer[position++];
            PacketIdentifier = (ushort)(((buffer[position++] << 8) | buffer[position++]) & 0x1FFF);
            var streamInfoLength = (ushort)(((buffer[position++] << 8) | buffer[position++]) & 0x0FFF);

            StreamInfo = Portability.CreateList <TsDescriptor>();
            var descriptorEndPosition = position + streamInfoLength;

            while (position < descriptorEndPosition)
            {
                var descriptor = new UnknownDescriptor(buffer, position);
                StreamInfo.Add(descriptor);
                position += descriptor.Length;
            }
        }
Beispiel #10
0
        public void LaunchConcensusServer(out AnonymousPipeServerStream rx, out AnonymousPipeServerStream tx)
        {
            if (Interlocked.Exchange(ref _consensusServerStarted, 1) != 0)
            {
                throw new InvalidOperationException("Consensus server already started");
            }

            const string processName = "dcrd";
            var          fileName    = processName;

            if (!parsedArguments.SearchPathForProcesses)
            {
                fileName = Portability.ExecutableInstallationPath(Environment.OSVersion.Platform, "Decred", processName);
            }

            var procInfo = new ProcessStartInfo
            {
                FileName        = fileName,
                Arguments       = $"--piperx {_outPipe.GetClientHandleAsString()} --pipetx {_inPipe.GetClientHandleAsString()} --lifetimeevents",
                CreateNoWindow  = parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet, // only hide on mainnet
                UseShellExecute = false,
            };

            if (parsedArguments.IntendedNetwork != BlockChainIdentity.MainNet)
            {
                procInfo.Arguments += $" --{parsedArguments.IntendedNetwork.Name}";
            }

            _consensusServerProcess = Process.Start(procInfo);

            rx = _inPipe;
            tx = _outPipe;

            Task.Run(async() =>
            {
                var exitCode = await _consensusServerProcess.WaitForExitAsync();
                if (exitCode != 0)
                {
                    MessageBox.Show($"Consensus server exited with code {exitCode}");
                }
                await Application.Current.Dispatcher.InvokeAsync(Application.Current.Shutdown);
            });
        }
Beispiel #11
0
        public TsDemuxer()
        {
            Programs = Portability.CreateList <TsProgram>();

            var programAssociationStream = new TableStream()
            {
                PacketIdentifier = (ushort)PacketIdentifier.ProgramAssociationTable
            };

            programAssociationStream.UnitReceived += ProgramAssociationTableReceived;
            _streams.Add((ushort)PacketIdentifier.ProgramAssociationTable, programAssociationStream);

            var descriptionStream = new TableStream()
            {
                PacketIdentifier = (ushort)PacketIdentifier.TsDescriptionTable
            };

            descriptionStream.UnitReceived += DescriptionTableReceived;
            _streams.Add((ushort)PacketIdentifier.TsDescriptionTable, descriptionStream);
        }
Beispiel #12
0
        public object GetClientCommandResult()
        {
            object errorId             = null;
            FileManagementException ex = Exception as FileManagementException;

            if (ex != null)
            {
                errorId = ex.ErrorCode;
            }
            if (IsFileContentResult && Success)
            {
                FileContentResult fileContentResult = (FileContentResult)Result;
                return(Portability.CreateFileContentResult(fileContentResult.FileStream, fileContentResult.FileName));
            }
            return(new
            {
                success = Success,
                errorId = errorId,
                result = GetClientResult()
            });
        }
Beispiel #13
0
        private string RenderCore()
        {
            bool     flag     = Portability.GetFormValue(base.ViewContext, "DXCallbackName") != null;
            Renderer renderer = new Renderer
            {
                PluginName             = base.JsName,
                ElementID              = InternalID,
                Options                = base.Options,
                ViewContext            = base.ViewContext,
                ValidationRules        = ValidationRules,
                CurrentValidationGroup = _currentValidationGroup,
                TranscludedContent     = base.TranscludedContent,
                RequireStartupScriptID = flag
            };
            StringBuilder stringBuilder = new StringBuilder();

            if (_declaredInTemplate)
            {
                renderer.RenderWithUnderscore(stringBuilder);
                return(stringBuilder.ToString());
            }
            if (InternalID.IsExpr)
            {
                throw new ArgumentException("The ID of a widget defined outside of a template is specified as a JS expression.");
            }
            if (!base.Globals.ConfigScriptBlockRendered)
            {
                Renderer.RenderStartupScriptOpenTag(stringBuilder, flag ? "_devextreme_config_block" : null);
                stringBuilder.AppendFormat("DevExpress.config({0});DevExpress.aspnet.setTemplateEngine();</script>", JsonUtils.SafeSerialize(new Dictionary <string, object>
                {
                    ["serverDecimalSeparator"] = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
                }));
                base.Globals.ConfigScriptBlockRendered = true;
            }
            renderer.Templates = base.Globals.Templates.ToArray();
            base.Globals.Templates.Clear();
            renderer.RenderWithStaticMarkup(stringBuilder);
            return(stringBuilder.ToString());
        }
Beispiel #14
0
        public ProgramMapTable(byte[] buffer, int offset, int length)
            : base(buffer, offset, length)
        {
            _programClockReferencePid = (ushort)((buffer[_position++] << 8) | buffer[_position++]);
            _programInfoLength        = (ushort)((buffer[_position++] << 8) | buffer[_position++]);

            ProgramInfo = Portability.CreateList <TsDescriptor>();
            var descriptorEndPosition = _position + ProgramInfoLength;

            while (_position < descriptorEndPosition)
            {
                var descriptor = new UnknownDescriptor(buffer, _position);
                ProgramInfo.Add(descriptor);
                _position += descriptor.Length;
            }

            while (_position < _sectionLengthStartOffset + SectionLength - 4 && _position < offset + length - 4)
            {
                var row = new ProgramMap(buffer, _position);
                _position += row.Length;
                Rows.Add(row);
            }
        }
        private string GetActionUrl(string actionName)
        {
            bool useLegacyRouting = Compatibility.DataSource.UseLegacyRouting;
            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            if (useLegacyRouting || !string.IsNullOrEmpty(_controllerName))
            {
                dictionary["controller"] = _controllerName;
            }
            if (useLegacyRouting || !string.IsNullOrEmpty(actionName))
            {
                dictionary["action"] = actionName;
            }
            if (_useHttpRouting)
            {
                dictionary["httproute"] = true;
            }
            if (_areaAssigned)
            {
                dictionary["area"] = _areaName;
            }
            return(Portability.GetActionUrl(base.ViewContext, _routeName, dictionary));
        }
Beispiel #16
0
 public ModelExplorer GetModelSource <TModel, TProperty>(Expression <Func <TModel, TProperty> > expression, ViewDataDictionary <TModel> viewData)
 {
     return(Portability.GetModelExpressionProvider(ViewContext).GetModelExplorer(expression, viewData));
 }
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                                                               ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await App.Current.Synchronizer.WalletRpcClient.StartConsensusRpc(rpcOptions);
                }
                catch (Exception ex) when(ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to start {ConsensusServerRpcOptions.ApplicationName} RPC.\n\nCheck connection settings and try again.", "Error");
                    return;
                }

                await Task.Run(() =>
                {
                    // save defaults to a file so that the user doesn't have to type this information again
                    var ini = new IniData();
                    ini.Sections.AddSection("Application Options");
                    ini["Application Options"]["rpcuser"]   = ConsensusServerRpcUsername;
                    ini["Application Options"]["rpcpass"]   = ConsensusServerRpcPassword;
                    ini["Application Options"]["rpclisten"] = ConsensusServerNetworkAddress;
                    var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                              AssemblyResources.Organization, AssemblyResources.ProductName);
                    var parser = new FileIniDataParser();
                    parser.WriteFile(Path.Combine(appDataDir, "defaults.ini"), ini);
                });

                var walletExists = await App.Current.Synchronizer.WalletRpcClient.WalletExistsAsync();

                if (!walletExists)
                {
                    _wizard.CurrentDialog = new CreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // TODO: Determine whether the public encryption is enabled and a prompt for the
                    // public passphrase prompt is needed before the wallet can be opened.  If it
                    // does not, then the wallet can be opened directly here instead of creating
                    // another dialog.
                    _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);

                    //await _walletClient.OpenWallet("public");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
 public RemoteFileProviderBuilder Url(string url)
 {
     base.StoreOptions["endpointUrl"] = Portability.GetContentUrl(base.ViewContext, url);
     return(this);
 }
Beispiel #19
0
 public TsUnit(IEnumerable <TsPacket> packets)
 {
     _packets = Portability.CreateList(packets);
     _payload = new TsUnitPayload(_packets);
 }
Beispiel #20
0
 public TsUnit(int capacity)
 {
     _packets = Portability.CreateList <TsPacket>(capacity);
     _payload = new TsUnitPayload(_packets);
 }
Beispiel #21
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // WPF defaults to using the en-US culture for all formatted bindings.
            // Override this with the system's current culture.
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),
                                                               new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            var args = ProcessArguments.ParseArguments(e.Args);

            var activeNetwork = args.IntendedNetwork;

            WalletClient.Initialize();

            Directory.CreateDirectory(AppDataDir);

            // try to obtain some default rpc settings to autofill the startup dialogs with.
            // try paymetheus defaults first, and if that fails, look for a dcrd config.
            try
            {
                var     iniParser    = new FileIniDataParser();
                IniData config       = null;
                string  defaultsFile = Path.Combine(AppDataDir, "defaults.ini");
                if (File.Exists(defaultsFile))
                {
                    config = iniParser.ReadFile(defaultsFile);
                }
                else
                {
                    var consensusRpcAppData = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                                       "", ConsensusServerRpcOptions.ApplicationName);
                    var consensusRpcConfig      = ConsensusServerRpcOptions.ApplicationName + ".conf";
                    var consensusConfigFilePath = Path.Combine(consensusRpcAppData, consensusRpcConfig);
                    if (File.Exists(consensusConfigFilePath))
                    {
                        config = iniParser.ReadFile(consensusConfigFilePath);
                    }
                }

                if (config != null)
                {
                    // Settings can be found in either the Application Options or global sections.
                    var section = config["Application Options"];
                    if (section == null)
                    {
                        section = config.Global;
                    }

                    var rpcUser   = section["rpcuser"] ?? "";
                    var rpcPass   = section["rpcpass"] ?? "";
                    var rpcListen = section["rpclisten"] ?? "";
                    var rpcCert   = section["rpccert"] ?? "";

                    // rpclisten and rpccert can be filled with sensible defaults when empty.  user and password can not.
                    if (rpcListen == "")
                    {
                        rpcListen = "127.0.0.1";
                    }
                    if (rpcCert == "")
                    {
                        var localCertPath = ConsensusServerRpcOptions.LocalCertificateFilePath();
                        if (File.Exists(localCertPath))
                        {
                            rpcCert = localCertPath;
                        }
                    }

                    DefaultCSRPO = new ConsensusServerRpcOptions(rpcListen, rpcUser, rpcPass, rpcCert);
                }
            }
            catch { } // Ignore any errors, this will just result in leaving defaults empty.

            var syncTask = Task.Run(async() =>
            {
                return(await SynchronizerViewModel.Startup(activeNetwork, AppDataDir, args.SearchPathForWalletProcess,
                                                           args.ExtraWalletArgs));
            });
            var synchronizer = syncTask.Result;

            SingletonViewModelLocator.RegisterInstance("Synchronizer", synchronizer);
            ActiveNetwork = activeNetwork;
            Synchronizer  = synchronizer;
            Current.Exit += Application_Exit;
        }
Beispiel #22
0
        private async void Connect()
        {
            try
            {
                ConnectCommand.Executable = false;

                if (string.IsNullOrWhiteSpace(ConsensusServerNetworkAddress))
                {
                    MessageBox.Show("Network address is required");
                    return;
                }
                if (string.IsNullOrWhiteSpace(ConsensusServerRpcUsername))
                {
                    MessageBox.Show("RPC username is required");
                    return;
                }
                if (ConsensusServerRpcPassword.Length == 0)
                {
                    MessageBox.Show("RPC password may not be empty");
                    return;
                }
                if (!File.Exists(ConsensusServerCertificateFile))
                {
                    MessageBox.Show("Certificate file not found");
                    return;
                }

                var walletClient = App.Current.Synchronizer.WalletRpcClient;

                var rpcOptions = new ConsensusServerRpcOptions(ConsensusServerNetworkAddress,
                                                               ConsensusServerRpcUsername, ConsensusServerRpcPassword, ConsensusServerCertificateFile);
                try
                {
                    await walletClient.StartConsensusRpc(rpcOptions);
                }
                catch (RpcException ex) when(ex.Status.StatusCode == StatusCode.NotFound)
                {
                    var msg = string.Format("Unable to connect to {0}.\n\nConnection could not be established with `{1}`.",
                                            ConsensusServerRpcOptions.ApplicationName, ConsensusServerNetworkAddress);

                    MessageBox.Show(msg, "Error");
                    return;
                }
                catch (Exception ex) when(ErrorHandling.IsTransient(ex) || ErrorHandling.IsClientError(ex))
                {
                    MessageBox.Show($"Unable to connect to {ConsensusServerRpcOptions.ApplicationName}.\n\nCheck authentication settings and try again.", "Error");
                    return;
                }

                await Task.Run(() =>
                {
                    // save defaults to a file so that the user doesn't have to type this information again
                    var ini = new IniData();
                    ini.Sections.AddSection("Application Options");
                    ini["Application Options"]["rpcuser"]   = ConsensusServerRpcUsername;
                    ini["Application Options"]["rpcpass"]   = ConsensusServerRpcPassword;
                    ini["Application Options"]["rpclisten"] = ConsensusServerNetworkAddress;
                    ini["Application Options"]["rpccert"]   = ConsensusServerCertificateFile;
                    var appDataDir = Portability.LocalAppData(Environment.OSVersion.Platform,
                                                              AssemblyResources.Organization, AssemblyResources.ProductName);
                    var parser = new FileIniDataParser();
                    parser.WriteFile(Path.Combine(appDataDir, "defaults.ini"), ini);
                });

                var walletExists = await walletClient.WalletExistsAsync();

                if (!walletExists)
                {
                    _wizard.CurrentDialog = new PickCreateOrImportSeedDialog(Wizard);
                }
                else
                {
                    // Attempt to open the wallet without any public passphrase.  If this succeeds,
                    // continue by syncing the wallet.  Otherwise, prompt for the public passphrase.
                    try
                    {
                        await walletClient.OpenWallet("");

                        _wizard.CurrentDialog = new OpenExistingWalletActivityProgress(Wizard);
                    }
                    catch (RpcException ex) when(ex.Status.StatusCode == StatusCode.InvalidArgument)
                    {
                        _wizard.CurrentDialog = new PromptPublicPassphraseDialog(Wizard);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            finally
            {
                ConnectCommand.Executable = true;
            }
        }
 /// <summary>
 /// Specifies the URL used to load JSON data.
 /// </summary>
 /// <param name="url">A URL string.</param>
 public StaticJsonDataSourceBuilder Url(string url)
 {
     url = Portability.GetContentUrl(base.ViewContext, url);
     StoreOptions["load"] = new JRaw("function() { return $.getJSON(" + JsonUtils.SafeSerialize(url) + "); }");
     return(this);
 }