public async Task <IHttpActionResult> Edit(EditDeviceBindingModel model)
        {
            if (model != null)
            {
                var device = await _repo.Get(model.Id);

                if (device != null)
                {
                    device.Name         = model.Name;
                    device.Manufacturer = model.Manufacturer;
                    device.Year         = model.Year;
                    device.Image        = model.Image;
                    foreach (int recoveryId in model.RecoveryIds)
                    {
                        Recovery temp = await _repo2.Get(recoveryId);

                        if (temp != null)
                        {
                            device.Recoveries.Clear();
                            device.Recoveries.Add(temp);
                        }
                    }
                    if (await _repo.Edit(device))
                    {
                        return(Ok());
                    }
                    return(NotFound());
                }
            }
            return(BadRequest("Model error."));
        }
 private void btnconfirmar_Click(object sender, EventArgs e)
 {
     try
     {
         if (txtUsuario.Text.Trim() == "")
         {
             MessageBox.Show("Complete el campo de usuario", "Llene los campos", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         else
         {
             try
             {
                 Recovery user   = new Recovery();
                 var      result = user.recovery(txtUsuario.Text);
                 txtcodigo.Enabled = true;
                 button1.Enabled   = true;
             }
             catch (Exception)
             {
                 MessageBox.Show("Error al embiar el correo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
     catch (Exception)
     {
         MessageBox.Show("Error al embiar el correo electronico");
     }
 }
        public async Task <IHttpActionResult> Create(CreateDeviceBindingModel model)
        {
            if (model != null)
            {
                var device = new Device {
                    Name = model.Name, Manufacturer = model.Manufacturer, Year = model.Year, Image = model.Image
                };
                if (model.RecoveryIds != null)
                {
                    foreach (int recoveryId in model.RecoveryIds)
                    {
                        Recovery temp = await _repo2.Get(recoveryId);

                        if (temp != null)
                        {
                            device.Recoveries.Add(temp);
                        }
                    }
                }
                if (await _repo.Create(device))
                {
                    return(Ok());
                }
            }
            return(BadRequest("Model error."));
        }
        private static bool DeleteToken(Recovery recovery)
        {
            SqlConnection connection      = ConnectionString.GetConnection();
            string        insertstatement =
                "DELETE FROM [Goke's Rentals].[dbo].[RecoveryToken] " + "WHERE TenantID = @TenantId";
            SqlCommand insertcommand =
                new SqlCommand(insertstatement, connection);

            insertcommand.Parameters.AddWithValue("@TenantID", recovery.userID);
            try
            {
                connection.Open();
                int count = insertcommand.ExecuteNonQuery();
                if (count > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }
Beispiel #5
0
        public async Task <bool> Create(Recovery recovery)
        {
            _db.Recoveries.Add(recovery);
            await Save();

            return(true);
        }
Beispiel #6
0
        public override bool OnIpV6Restore()
        {
            foreach (IpV6ModeEntry entry in m_listIpV6Mode)
            {
                if (entry.Mode == "Off")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6off", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "Automatic")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6automatic", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "LinkLocal")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6LinkLocal", SystemShell.EscapeInsideQuote(entry.Interface) });
                }
                else if (entry.Mode == "Manual")
                {
                    SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-setv6manual", SystemShell.EscapeInsideQuote(entry.Interface), entry.Address, entry.PrefixLength, entry.Router });
                }

                Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface));
            }

            m_listIpV6Mode.Clear();

            Recovery.Save();

            base.OnIpV6Restore();

            return(true);
        }
Beispiel #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void incompleteHeaderOfLastOfMoreThanOneLogFilesShouldNotCauseFailure() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IncompleteHeaderOfLastOfMoreThanOneLogFilesShouldNotCauseFailure()
        {
            // Given
            // we use a RaftLog to create two log files, in order to chop the header of the second
            SegmentedRaftLog raftLog = CreateRaftLog(1);

            raftLog.Start();

            raftLog.Append(new RaftLogEntry(4, new NewLeaderBarrier()));                   // will cause rotation

            raftLog.Stop();

            // We use a temporary RecoveryProtocol to get the file to chop
            RecoveryProtocol recovery      = CreateRecoveryProtocol();
            State            recoveryState = Recovery.run();
            string           logFilename   = recoveryState.Segments.last().Filename;

            recoveryState.Segments.close();
            File logFile = new File(_logDirectory, logFilename);

            // When
            // We remove any number of bytes from the end of the second file and try to recover
            // Then
            // No exceptions should be thrown
            TruncateAndRecover(logFile, 0);
        }
        private static bool SaveToken(Recovery recovery, bool isAdmin = false)
        {
            SqlConnection connection      = ConnectionString.GetConnection();
            string        insertstatement =
                "Insert into [Goke's Rentals].[dbo].[RecoveryToken] " + "(tenantID, token, expirationDate, isAdmin) " +
                "VALUES (@TenantID, @token, @expirationDate, @isAdmin)";
            SqlCommand insertcommand =
                new SqlCommand(insertstatement, connection);

            insertcommand.Parameters.AddWithValue("@TenantID", recovery.userID);
            insertcommand.Parameters.AddWithValue("@token", recovery.Token);
            insertcommand.Parameters.AddWithValue("@expirationDate", recovery.ExpirationDate);
            insertcommand.Parameters.AddWithValue("@isAdmin", isAdmin);
            try
            {
                connection.Open();
                int count = insertcommand.ExecuteNonQuery();
                if (count > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }
Beispiel #9
0
        public override bool OnIpV6Restore()
        {
            foreach (IpV6ModeEntry entry in m_listIpV6Mode)
            {
                if (entry.Mode == "Off")
                {
                    ShellCmd("networksetup -setv6off \"" + entry.Interface + "\"");
                }
                else if (entry.Mode == "Automatic")
                {
                    ShellCmd("networksetup -setv6automatic \"" + entry.Interface + "\"");
                }
                else if (entry.Mode == "LinkLocal")
                {
                    ShellCmd("networksetup -setv6LinkLocal \"" + entry.Interface + "\"");
                }
                else if (entry.Mode == "Manual")
                {
                    ShellCmd("networksetup -setv6manual \"" + entry.Interface + "\" " + entry.Address + " " + entry.PrefixLength + " " + entry.Router);
                }

                Engine.Instance.Log(Engine.LogType.Info, Messages.Format(Messages.NetworkAdapterIpV6Restored, entry.Interface));
            }

            m_listIpV6Mode.Clear();

            Recovery.Save();

            base.OnIpV6Restore();

            return(true);
        }
        public async Task <IHttpActionResult> Get(string name)
        {
            Recovery recovery = await _repo.Get(name);

            if (recovery != null)
            {
                ShowRecoveryModel viewModel = new ShowRecoveryModel()
                {
                    Id       = recovery.Id,
                    Name     = recovery.Name,
                    Version  = recovery.Version,
                    Download = recovery.Download,
                };
                if (recovery.Device != null)
                {
                    viewModel.Device = new
                    {
                        Id           = recovery.Device.Id,
                        Name         = recovery.Device.Name,
                        Manufacturer = recovery.Device.Manufacturer,
                        Year         = recovery.Device.Year,
                        Image        = recovery.Device.Image
                    };
                }
                return(Ok(viewModel));
            }
            return(BadRequest());
        }
        private void btnRecu_Click(object sender, EventArgs e)
        {
            //try
            //{
            if (txtUsuario.Text.Trim() == "")
            {
                MessageBox.Show("Complete el campo de usuario", "Llene los campos", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //try
                //{
                Recovery user = new Recovery();
                ContructorLogin2.usuario = txtUsuario.Text;
                var result = user.recovery(ContructorLogin2.usuario);
                txtcodigo.Enabled  = true;
                btnvalidar.Enabled = true;
                //}
                //catch (Exception)
                //{

                //    MessageBox.Show("Error al enviar el correo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //}
            }
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("Error al enviar el correo electronico");
            //}
        }
Beispiel #12
0
        static void Main(String[] args)
        {
            foreach (String argument in args)
            {
                // Deve exportar as tabelas do banco
                if (argument.ToUpper().Contains("/E"))
                {
                    // Busca parâmetros de conexão na linha de comando, caso existam
                    DBAccess saAccess = null;
                    saAccess = DBAccess.GetDbAccess(args);

                    // Cria o diretório onde para onde os dados serão exportados
                    String baseDir       = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.ToString());
                    String dataDirectory = PathFormat.Adjust(baseDir) + "Data";
                    Directory.CreateDirectory(dataDirectory);

                    // Executa a exportação dos databases
                    Recovery recovery = new Recovery(saAccess, dataDirectory);
                    recovery.DBExport("AppCommon");
                    recovery.DBExport("Accounting");

                    return;
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
Beispiel #13
0
    public async Task <IActionResult> UpdateAsync(int id, [FromBody] RecoveryDto input)
    {
        // Map.
        var recovery = _mapper.Map <Recovery>(input);

        recovery.Id = id;

        Recovery recovery_existing = await _recoveryRepository.GetByIdAsync(id);

        if (recovery_existing.Attribution.Creator == input.Reviewer)
        {
            throw new AuthorizationException();
        }

        // Act.
        await _recoveryRepository.UpdateAsync(recovery);

        // FUTURE: Does this make sense?
        // Only when this item was rejected can we move into
        // a pending state after update.
        if (recovery.State.AuditStatus == AuditStatus.Rejected)
        {
            // Transition.
            recovery.State.TransitionToPending();

            // Act.
            await _recoveryRepository.SetAuditStatusAsync(recovery.Id, recovery);
        }

        // Return.
        return(NoContent());
    }
Beispiel #14
0
        public override bool OnIpV6Do()
        {
            if (Engine.Instance.Storage.Get("ipv6.mode") == "disable")
            {
                // http://support.microsoft.com/kb/929852

                m_oldIpV6 = Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\TCPIP6\\Parameters", "DisabledComponents", "");
                if (Conversions.ToUInt32(m_oldIpV6, 0) == 0)                 // 0 is the Windows default if the key doesn't exist.
                {
                    m_oldIpV6 = 0;
                }

                if (Conversions.ToUInt32(m_oldIpV6, 0) == 17)                 // Nothing to do
                {
                    m_oldIpV6 = null;
                }
                else
                {
                    UInt32 newValue = 17;
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\TCPIP6\\Parameters", "DisabledComponents", newValue, RegistryValueKind.DWord);

                    Engine.Instance.Log(Engine.LogType.Info, Messages.IpV6Disabled);

                    Recovery.Save();
                }

                base.OnIpV6Do();
            }

            return(true);
        }
Beispiel #15
0
    public async Task <IActionResult> CreateAsync(int recoveryId, [FromBody] RecoverySampleDto input, [FromServices] IGeocoderTranslation geocoderTranslation)
    {
        Address address = await geocoderTranslation.GetAddressIdAsync(input.Address);

        // Map.
        var recoverySample = _mapper.Map <RecoverySample>(input);

        recoverySample.Address  = address.Id;
        recoverySample.Recovery = recoveryId;

        // Act.
        // FUTURE: Too much logic
        Recovery recovery = await _recoveryRepository.GetByIdAsync(recoverySample.Recovery);

        if (!recovery.State.AllowWrite)
        {
            throw new EntityReadOnlyException();
        }

        recoverySample = await _recoverySampleRepository.AddGetAsync(recoverySample);

        recovery.State.TransitionToPending();
        await _recoveryRepository.SetAuditStatusAsync(recovery.Id, recovery);

        // Map.
        var output = _mapper.Map <RecoverySampleDto>(recoverySample);

        // Return.
        return(Ok(output));
    }
Beispiel #16
0
    public async Task <IActionResult> UpdateAsync(int recoveryId, int id, [FromBody] RecoverySampleDto input)
    {
        // Map.
        var recoverySample = _mapper.Map <RecoverySample>(input);

        recoverySample.Id       = id;
        recoverySample.Recovery = recoveryId;

        // Act.
        // FUTURE: Too much logic
        Recovery recovery = await _recoveryRepository.GetByIdAsync(recoverySample.Recovery);

        if (!recovery.State.AllowWrite)
        {
            throw new EntityReadOnlyException();
        }

        await _recoverySampleRepository.UpdateAsync(recoverySample);

        recovery.State.TransitionToPending();
        await _recoveryRepository.SetAuditStatusAsync(recovery.Id, recovery);

        // Return.
        return(NoContent());
    }
        /// <summary>  </summary>
        public static Health Create(Recovery type)
        {
            Health health  = null;
            string recover = Enum.GetName(typeof(Recovery), type);

            switch (recover)
            {
            case "Heart":
                health = new Heart();
                break;

            case "RainbowHeart":
                health = new RainbowHeart();
                break;

            case "BlackHeart":
                health = new BlackHeart();
                break;

            default:
                break;
            }

            return(health);
        }
Beispiel #18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void incompleteEntriesAtTheEndShouldNotCauseFailures() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IncompleteEntriesAtTheEndShouldNotCauseFailures()
        {
            // Given
            // we use a RaftLog to create a raft log file and then we will start chopping bits off from the end
            SegmentedRaftLog raftLog = CreateRaftLog(100_000);

            raftLog.Start();

            // Add a bunch of entries, preferably one of each available kind.
            raftLog.Append(new RaftLogEntry(4, new NewLeaderBarrier()));
            raftLog.Append(new RaftLogEntry(4, new ReplicatedIdAllocationRequest(new MemberId(System.Guid.randomUUID()), IdType.RELATIONSHIP, 1, 1024)));
            raftLog.Append(new RaftLogEntry(4, new ReplicatedIdAllocationRequest(new MemberId(System.Guid.randomUUID()), IdType.RELATIONSHIP, 1025, 1024)));
            raftLog.Append(new RaftLogEntry(4, new ReplicatedLockTokenRequest(new MemberId(System.Guid.randomUUID()), 1)));
            raftLog.Append(new RaftLogEntry(4, new NewLeaderBarrier()));
            raftLog.Append(new RaftLogEntry(5, new ReplicatedTokenRequest(TokenType.LABEL, "labelToken", new sbyte[] { 1, 2, 3 })));
            raftLog.Append(new RaftLogEntry(5, ReplicatedTransaction.from(new sbyte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })));

            raftLog.Stop();

            // We use a temporary RecoveryProtocol to get the file to chop
            RecoveryProtocol recovery      = CreateRecoveryProtocol();
            State            recoveryState = Recovery.run();
            string           logFilename   = recoveryState.Segments.last().Filename;

            recoveryState.Segments.close();
            File logFile = new File(_logDirectory, logFilename);

            // When
            // We remove any number of bytes from the end (up to but not including the header) and try to recover
            // Then
            // No exceptions should be thrown
            TruncateAndRecover(logFile, SegmentHeader.Size);
        }
Beispiel #19
0
        public void RecoveryHumana()
        {
            var workflow = new Recovery();

            chromeDriver.Navigate().GoToUrl(new Constants().Humana_url);
            workflow.FullFlow(chromeDriver);
        }
Beispiel #20
0
        public override bool OnDnsSwitchDo(IpAddresses dns)
        {
            string mode = Engine.Instance.Storage.GetLower("dns.mode");

            if (mode == "auto")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string currentStr = SystemShell.Shell("/usr/sbin/networksetup", new string[] { "-getdnsservers", SystemShell.EscapeInsideQuote(i2) });

                    // v2
                    IpAddresses current = new IpAddresses();
                    foreach (string line in currentStr.Split('\n'))
                    {
                        string ip = line.Trim();
                        if (IpAddress.IsIP(ip))
                        {
                            current.Add(ip);
                        }
                    }

                    if (dns.Equals(current) == false)
                    {
                        DnsSwitchEntry e = new DnsSwitchEntry();
                        e.Name = i2;
                        e.Dns  = current.Addresses;
                        m_listDnsSwitch.Add(e);

                        SystemShell s = new SystemShell();
                        s.Path = LocateExecutable("networksetup");
                        s.Arguments.Add("-setdnsservers");
                        s.Arguments.Add(SystemShell.EscapeInsideQuote(i2));
                        if (dns.IPs.Count == 0)
                        {
                            s.Arguments.Add("empty");
                        }
                        else
                        {
                            foreach (IpAddress ip in dns.IPs)
                            {
                                s.Arguments.Add(ip.Address);
                            }
                        }
                        s.Run();

                        Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkAdapterDnsDone, i2, ((current.Count == 0) ? "Automatic" : current.Addresses), dns.Addresses));
                    }
                }

                Recovery.Save();
            }

            base.OnDnsSwitchDo(dns);

            return(true);
        }
Beispiel #21
0
        public override void OnSessionStop()
        {
            SwitchToStaticRestore();

            FlushDNS();

            Recovery.Save();
        }
Beispiel #22
0
        public async Task <Device> GetDevice(int id)
        {
            Recovery recovery = await Get(id);

            await _db.Entry(recovery).Reference(x => x.Device).LoadAsync();

            return(recovery.Device);
        }
 public IResponse VisitRecovery(Recovery recovery)
 {
     while (!(this.replicaState.State is NormalStateMessageProcessor))
     {
         this.replicaState.HandlerStateChanged.WaitOne();
     }
     return(recovery.Accept(this.replicaState.State));
 }
 void Start()
 {
     _panelController = GameObject.Find("PanelController").GetComponent <PanelController>();
     _recovery        = GameObject.Find("Recovery(Clone)").GetComponent <Recovery>();
     if (Num == 0)
     {
         islight = 1;
     }
 }
        public bool sendEmail(ref Recovery theRecovery)
        {
            StudentRegistrationsModel db = new StudentRegistrationsModel();
            theRecovery.recovery_key = this.keyCode();
            //retrieve settings from webconfig
            string FromAddress = System.Configuration.ConfigurationManager.AppSettings.Get("FromAddress");
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings.Get("SmtpServer");
            string UserName = System.Configuration.ConfigurationManager.AppSettings.Get("UserName");
            string Password = System.Configuration.ConfigurationManager.AppSettings.Get("Password");
            string EnableSSL = System.Configuration.ConfigurationManager.AppSettings.Get("EnableSSL");
            int SMTPPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("SMTPPort"));
            string ReplyTo = System.Configuration.ConfigurationManager.AppSettings.Get("ReplyTo");

            var fromAddress = new MailAddress(FromAddress, "no-reply");
            var toAddress = new MailAddress(theRecovery.Administrator.Email);
            //const string fromPassword = Password;
            string subject = "Password Recovery";
            string body = String.Format("Your Reset password key is : {0}", theRecovery.recovery_key);

            var smtp = new SmtpClient
            {
                Host = SmtpServer,
                Port = SMTPPort,
                EnableSsl = false,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(UserName, Password)

            };
            using (var message = new MailMessage(fromAddress, toAddress)

            {
                Subject = subject,
                Body = body,
                //Priority = MailPriority.High,
                //IsBodyHtml = true,
                Headers =
                {

                    //to solve spam issue add random message id
                    //soulition from http://stackoverflow.com/questions/6874964/why-emails-sent-by-net-smtpclient-are-missing-message-id
                    { "Message-ID", String.Format("<{0}@{1}>", Guid.NewGuid().ToString(), "lukes-server.com") },
                    { "X-Sender" ,FromAddress},
                    { "User-Agent" ,"ITxC# App"}
                }

            })
            {
                smtp.Send(message);
            }
            //we end here if success
            //db.Recoveries.Attach(theRecovery);
            //db.Recoveries.Attach(theRecovery);
            //db.SaveChanges();
            return true;
        }
        public async Task <Recovery> Update(long id, int uId, Recovery model)
        {
            var entity = await _context.Recoveries.AsAsyncEnumerable().SingleOrDefaultAsync(x => x.UserId == uId && x.RecoveryId == id);

            entity.Fatigue  = model.Fatigue;
            entity.MuscleId = model.MuscleId;
            _context.Recoveries.Update(entity);
            _context.SaveChanges();
            return(entity);
        }
Beispiel #27
0
        public override bool OnDnsSwitchDo(string dns)
        {
            string[] dnsArray = dns.Split(',');

            string mode = Engine.Instance.Storage.Get("dns.mode").ToLowerInvariant();

            if (mode == "auto")
            {
                try
                {
                    ManagementClass            objMC  = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection objMOC = objMC.GetInstances();

                    foreach (ManagementObject objMO in objMOC)
                    {
                        /*
                         * if (!((bool)objMO["IPEnabled"]))
                         *      continue;
                         */
                        NetworkManagerDnsEntry entry = new NetworkManagerDnsEntry();

                        entry.Guid        = objMO["SettingID"] as string;
                        entry.Description = objMO["Description"] as string;
                        entry.Dns         = objMO["DNSServerSearchOrder"] as string[];

                        entry.AutoDns = ((Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\" + entry.Guid, "NameServer", "") as string) == "");

                        if (entry.Dns == null)
                        {
                            continue;
                        }

                        Engine.Instance.Log(Engine.LogType.Info, Messages.Format(Messages.NetworkAdapterDnsDone, entry.Description));

                        ManagementBaseObject objSetDNSServerSearchOrder = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                        //objSetDNSServerSearchOrder["DNSServerSearchOrder"] = null;
                        //objSetDNSServerSearchOrder["DNSServerSearchOrder"] = new string[] { Constants.DnsVpn };
                        objSetDNSServerSearchOrder["DNSServerSearchOrder"] = dnsArray;
                        ManagementBaseObject objSetDNSServerSearchOrderMethod = objMO.InvokeMethod("SetDNSServerSearchOrder", objSetDNSServerSearchOrder, null);

                        m_listOldDns.Add(entry);
                    }
                }
                catch (Exception e)
                {
                    Engine.Instance.Log(e);
                }

                Recovery.Save();
            }

            base.OnDnsSwitchDo(dns);

            return(true);
        }
Beispiel #28
0
        public async Task CanRecoverEncryptedDatabase()
        {
            string dbName = SetupEncryptedDatabase(out X509Certificate2 adminCert, out var masterKey);

            var dbPath             = NewDataPath(prefix: Guid.NewGuid().ToString());
            var recoveryExportPath = NewDataPath(prefix: Guid.NewGuid().ToString());

            DatabaseStatistics databaseStatistics;

            using (var store = GetDocumentStore(new Options()
            {
                AdminCertificate = adminCert,
                ClientCertificate = adminCert,
                ModifyDatabaseName = s => dbName,
                ModifyDatabaseRecord = record => record.Encrypted = true,
                Path = dbPath
            }))
            {
                store.Maintenance.Send(new CreateSampleDataOperation());

                databaseStatistics = store.Maintenance.Send(new GetStatisticsOperation());
            }

            using (var recovery = new Recovery(new VoronRecoveryConfiguration()
            {
                LoggingMode = Sparrow.Logging.LogMode.None,
                DataFileDirectory = dbPath,
                PathToDataFile = Path.Combine(dbPath, "Raven.voron"),
                OutputFileName = Path.Combine(recoveryExportPath, "recovery.ravendump"),
                MasterKey = masterKey
            }))
            {
                recovery.Execute(TextWriter.Null, CancellationToken.None);
            }


            using (var store = GetDocumentStore(new Options()
            {
                AdminCertificate = adminCert,
                ClientCertificate = adminCert,
            }))
            {
                var op = await store.Smuggler.ImportAsync(new DatabaseSmugglerImportOptions()
                {
                }, Path.Combine(recoveryExportPath, "recovery-2-Documents.ravendump"));

                op.WaitForCompletion(TimeSpan.FromMinutes(2));

                var currentStats = store.Maintenance.Send(new GetStatisticsOperation());

                // + 1 as recovery adds some artificial items
                Assert.Equal(databaseStatistics.CountOfAttachments + 1, currentStats.CountOfAttachments);
                Assert.Equal(databaseStatistics.CountOfDocuments + 1, currentStats.CountOfDocuments);
            }
        }
Beispiel #29
0
        public override bool OnDnsSwitchDo(string dns)
        {
            string mode = Engine.Instance.Storage.GetLower("dns.mode");

            if (mode == "auto")
            {
                string[] interfaces = GetInterfaces();
                foreach (string i in interfaces)
                {
                    string i2 = i.Trim();

                    string current = ShellCmd("networksetup -getdnsservers \"" + i2 + "\"");

                    // v2
                    List <string> ips = new List <string>();
                    foreach (string line in current.Split('\n'))
                    {
                        string ip = line.Trim();
                        if (IpAddress.IsIP(ip))
                        {
                            ips.Add(ip);
                        }
                    }

                    if (ips.Count != 0)
                    {
                        current = String.Join(",", ips.ToArray());
                    }
                    else
                    {
                        current = "";
                    }
                    if (current != dns)
                    {
                        // Switch
                        Engine.Instance.Logs.Log(LogType.Verbose, Messages.Format(Messages.NetworkAdapterDnsDone, i2, ((current == "") ? "Automatic" : current), dns));

                        DnsSwitchEntry e = new DnsSwitchEntry();
                        e.Name = i2;
                        e.Dns  = current;
                        m_listDnsSwitch.Add(e);

                        string dns2 = dns.Replace(",", "\" \"");
                        ShellCmd("networksetup -setdnsservers \"" + i2 + "\" \"" + dns2 + "\"");
                    }
                }

                Recovery.Save();
            }

            base.OnDnsSwitchDo(dns);

            return(true);
        }
Beispiel #30
0
    public async Task <IActionResult> GetAsync(int id)
    {
        // Act.
        Recovery recovery = await _recoveryRepository.GetByIdAsync(id);

        // Map.
        var output = _mapper.Map <RecoveryDto>(recovery);

        // Return.
        return(Ok(output));
    }
Beispiel #31
0
        public override void OnSessionStart()
        {
            // https://airvpn.org/topic/11162-airvpn-client-advanced-features/ -> Switch DHCP to Static
            if (Engine.Instance.Storage.GetBool("advanced.windows.dhcp_disable"))
            {
                SwitchToStaticDo();
            }

            FlushDNS();

            Recovery.Save();
        }
        public bool sendSMS(ref Recovery theRecovery)
        {
            StudentRegistrationsModel db = new StudentRegistrationsModel();
            //021023517
            //021023517775
            //string mobileNumber = theRecovery.Administrator.mobile;
            //string keyCode = this.keyCode();
            string api_key = System.Configuration.ConfigurationManager.AppSettings.Get("api_key");
            string api_uri = System.Configuration.ConfigurationManager.AppSettings.Get("api_uri");

            theRecovery.recovery_key = this.keyCode();

            if (theRecovery.Administrator.mobile.Count() < 8 || theRecovery.Administrator.mobile.Count() > 13) return false;

            //string uriString = "http://home.lukes-server.com/sms/api.php";

            using (var client = new WebClient())
            {
                var values = new NameValueCollection
                {
                    { "api_key", api_key },
                    { "text", String.Format("Your Reset password key is : {0} ", theRecovery.recovery_key) },
                    { "dest",   theRecovery.Administrator.mobile }
                };
                client.QueryString = values;

                var response = client.UploadValues(api_uri, values);
                string result = System.Text.Encoding.UTF8.GetString(response);

                //API key will expire in 1 month after school assignment hand in
                if (result == "incorrect api key")
                    return false;

                //we end here if success

                return (result == "received");

            }
        }
Beispiel #33
0
 private void Button_Click_2(object sender, RoutedEventArgs e)
 {
     Recovery r = new Recovery();
     r.Show();
 }
Beispiel #34
0
 private void StartRecovery(Recovery recovery)
 {
     ChangeState(RecoveryStarted(recovery.ReplayMax));
     LoadSnapshot(SnapshotterId, recovery.FromSnapshot, recovery.ToSequenceNr);
 }
Beispiel #35
0
 public DeleteSnapshotTestActor(string name, Recovery recovery, IActorRef probe)
     : base(name, recovery, probe)
 {
 }
Beispiel #36
0
 public LoadSnapshotTestActor(string name, Recovery recovery, IActorRef probe)
     : base(name)
 {
     _probe = probe;
     _recovery = recovery;
 }