示例#1
0
        public void Xfs5VhdxZip()
        {
            SetupHelper.SetupComplete();
            using (FileStream fs = File.OpenRead(Path.Combine("..", "..", "..", "Xfs", "Data", "xfs5.zip")))
                using (Stream vhdx = ZipUtilities.ReadFileFromZip(fs))
                    using (var diskImage = new DiskImageFile(vhdx, Ownership.Dispose))
                        using (var disk = new Disk(new List <DiskImageFile> {
                            diskImage
                        }, Ownership.Dispose))
                        {
                            var manager        = new VolumeManager(disk);
                            var logicalVolumes = manager.GetLogicalVolumes();
                            Assert.Equal(1, logicalVolumes.Length);

                            var volume      = logicalVolumes[0];
                            var filesystems = FileSystemManager.DetectFileSystems(volume);
                            Assert.Equal(1, filesystems.Length);

                            var filesystem = filesystems[0];
                            Assert.Equal("xfs", filesystem.Name);

                            using (var xfs = filesystem.Open(volume))
                            {
                                Assert.IsType <XfsFileSystem>(xfs);

                                Assert.Equal(9082445824, xfs.AvailableSpace);
                                Assert.Equal(10725883904, xfs.Size);
                                Assert.Equal(1643438080, xfs.UsedSpace);
                                ValidateContent(xfs);
                            }
                        }
        }
示例#2
0
        static void Main(string[] args)
        {
            SetupHelper.SetupTransports();

            Program program = new Program();

            program.Run(args);
        }
示例#3
0
 public ActionResult SetLogLevel(int logLevel)
 {
     SetupHelper.LoadSetup();
     SetupHelper.LoggingLevel = logLevel;
     SetupHelper.SaveSetup();
     ShowMessage("Log Levels save successful. <a href='/Home/RestartHost'> Restart Site</a> for change effect.", MessageType.Success);
     return(RedirectToAction("Logging"));
 }
示例#4
0
        static void Main(string[] args)
        {
            SetupHelper.RegisterAssembly(typeof(NtfsFileSystem).Assembly);

            Program program = new Program();

            program.Run(args);
        }
示例#5
0
        public NccDbContext Create(DbContextFactoryOptions options)
        {
            SetupHelper.LoadSetup();
            var opts         = SetupHelper.GetDbContextOptions();
            var nccDbConetxt = new NccDbContext(opts);

            return(nccDbConetxt);
        }
示例#6
0
        public NccDbContext CreateDbContext(string[] args)
        {
            SetupHelper.LoadSetup();
            var opts         = SetupHelper.GetDbContextOptions();
            var nccDbConetxt = new NccDbContext(opts);

            return(nccDbConetxt);
        }
示例#7
0
        static void Main(string[] args)
        {
            SetupHelper.SetupFileSystems();

            Program program = new Program();

            program.Run(args);
        }
示例#8
0
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFirstName.Text.Trim()))
            {
                MessageBox.Show("Please enter your First Name", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (string.IsNullOrEmpty(txtLastName.Text.Trim()))
            {
                MessageBox.Show("Please enter your Last Name", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!rbMale.Checked && !rbFemale.Checked)
            {
                MessageBox.Show("Please select your Gender", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!SetupHelper.IsDateValid(ddDay, ddMonth, ddYear))
            {
                MessageBox.Show("Please select your Date of Birth", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (!SetupHelper.IsGeoValid(ddCountry, ddState, ddTownCity))
            {
                MessageBox.Show("Please select your Location", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (ddOccupationSector.SelectedIndex == 0)
            {
                MessageBox.Show("Please select your Occupational Sector", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (ddEmploymentLevel.SelectedIndex == 0)
            {
                MessageBox.Show("Please select your Employment Level", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (ddAnnualHouseholdIncome.SelectedIndex == 0)
            {
                MessageBox.Show("Please select your Annual Household Income", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            AppDataSingleton.Instance.FirstName = txtFirstName.Text;
            AppDataSingleton.Instance.LastName  = txtLastName.Text;
            SetupHelper.SaveAgeGender(rbMale, ddDay, ddMonth, ddYear);
            SetupHelper.SaveGeo(ddCountry, ddState, ddTownCity);
            SetupHelper.SaveSocioEconomicStatus(ddOccupationSector, ddEmploymentLevel, ddAnnualHouseholdIncome);

            SetupHelper.OpenForm <PCNameStreamSubscriptionsForm>(this);
        }
示例#9
0
 static void Main(string[] args)
 {
     SetupHelper.Initialize(args);
     SetupHelper.Install       += new EventHandler <EventArgs>(SetupHelper_Install);
     SetupHelper.SilentInstall += new EventHandler <EventArgs>(SetupHelper_SilentInstall);
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     SetupHelper.StartInstallation();
 }
示例#10
0
        public static void InitializeIdentityForEf(ApplicationDbContext db)
        {
            var userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var roleManager = HttpContext.Current.GetOwinContext().Get <ApplicationRoleManager>();

            SetupHelper.SetupRoles(roleManager);
            CrateStartupAdminUsers(userManager);
            //make sure you check the default connection database pointer
        }
示例#11
0
        private void ddCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_bGeoDropDownsSet)
            {
                return;
            }

            SetupHelper.SetStateTownCityDropDownsByCountry((ComboBox)sender, ddState, ddTownCity, lblState);
        }
示例#12
0
        private void ddState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_bGeoDropDownsSet)
            {
                return;
            }

            SetupHelper.SetTownCityDropDownByState(ddCountry, (ComboBox)sender, ddTownCity);
        }
示例#13
0
 public ActionResult Back()
 {
     if (SetupHelper.IsDbCreateComplete)
     {
         SetupHelper.IsDbCreateComplete = false;
         SetupHelper.DeleteSetup();
     }
     return(RedirectToAction("Index"));
 }
示例#14
0
        private void UninstallProgressForm_Shown(object sender, EventArgs e)
        {
            string userGUID         = null;
            string machineGUID      = null;
            string binaryPath       = null;
            string dataSettingsPath = null;

            Application.DoEvents();

            if (!SetupHelper.GetValuesFromRegistry(ref userGUID, ref machineGUID, ref dataSettingsPath, ref binaryPath))
            {
                MessageBox.Show("Cannot proceed with installation. Registry entries are corrupted.\r\nPlease run the installer again in repair mode.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return;
            }

            progressBar.Value = 3;

            Setup.UserManagementServicesLive.SimpleErrorWrapper wrapper = SetupHelper.SendUninstallInfo(userGUID, machineGUID);

            if (wrapper.ErrorStatus != Setup.UserManagementServicesLive.ErrorStatus1.Success)
            {
                if (wrapper.ErrorCode == "CONN")
                {
                    MessageBox.Show("Oxigen needs an active internet connection to uninstall. Please ensure that you are connected to the Internet.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(wrapper.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                Application.Exit();
                return;
            }

            progressBar.Value = 10;

            ScreenSaver.SetScreenSaverActive(0);
            SetupHelper.KillApplications();

            progressBar.Value = 70;

            SetupHelper.ShowMessage(lblProgress, "Removing binaries...");

            SetupHelper.UninstallMSI(this);

            progressBar.Value = 90;

            SetupHelper.ShowMessage(lblProgress, "Cleaning up...");

            SetupHelper.RemoveAllFiles(binaryPath + "bin", SetupHelper.GetSystemDirectory(), dataSettingsPath);

            progressBar.Value = 100;

            SetupHelper.OpenForm <UninstallComplete>(this);
        }
示例#15
0
 /// <summary>
 /// The main Extractor class.
 /// </summary>
 public Extractor()
 {
     SetupHelper.RegisterAssembly(typeof(BtrfsFileSystem).Assembly);
     SetupHelper.RegisterAssembly(typeof(ExtFileSystem).Assembly);
     SetupHelper.RegisterAssembly(typeof(FatFileSystem).Assembly);
     SetupHelper.RegisterAssembly(typeof(HfsPlusFileSystem).Assembly);
     SetupHelper.RegisterAssembly(typeof(NtfsFileSystem).Assembly);
     SetupHelper.RegisterAssembly(typeof(XfsFileSystem).Assembly);
     SetDefaultExtractors();
 }
示例#16
0
        private void btnBack_Click(object sender, EventArgs e)
        {
            if (AppDataSingleton.Instance.Repair)
            {
                SetupHelper.OpenForm <OxigenExistsForm>(this);
                return;
            }

            SetupHelper.OpenForm <WelcomeForm>(this);
        }
示例#17
0
        public IHttpActionResult GetRoles()
        {
            SetupHelper.SetupRoles(RoleManager);
            var roles = RoleManager.Roles.Select(a => new { a.Name, a.Users.Count });

            return(Ok(new
            {
                Total = roles.Count(),
                Items = roles
            }));
        }
示例#18
0
 private void btnBack_Click(object sender, EventArgs e)
 {
     if (AppDataSingleton.Instance.PrerequisitesFullyMet)
     {
         SetupHelper.OpenForm <WelcomeForm>(this);
     }
     else
     {
         SetupHelper.OpenForm <PrerequisitesForm>(this);
     }
 }
示例#19
0
        public Stream Open(string fileName, FileMode mode, FileAccess access, FileShare share)
        {
            var args = new FileOpenEventArgs(fileName, mode, access, share, OpenFile);

            SetupHelper.OnOpeningFile(this, args);
            if (args.Result != null)
            {
                return(args.Result);
            }
            return(OpenFile(args.FileName, args.FileMode, args.FileAccess, args.FileShare));
        }
示例#20
0
        private void PrerequisitesForm_Load(object sender, EventArgs e)
        {
            ClientLogger logger = new PersistentClientLogger();

            logger.Log("2-Prerequisites");

            IInstallationPrerequisiteProvider installationPrerequisiteProvider;

            if (!AppDataSingleton.Instance.DebugMode)
            {
                installationPrerequisiteProvider = new RealInstallationPrerequisiteProvider();
            }
            else
            {
                installationPrerequisiteProvider = new MockInstallationPrerequisiteProvider()
                {
                    DotNet35PrerequisiteStatus     = PrerequisiteStatus.Exists,
                    FlashActiveXPrerequisiteStatus = PrerequisiteStatus.Exists,
                    QTPrerequisiteStatus           = PrerequisiteStatus.DoesNotExist,
                    RamPrerequisiteStatus          = PrerequisiteStatus.Exists,
                    WMPPrerequisiteStatus          = PrerequisiteStatus.DoesNotExist
                };
            }
            InstallationPrerequisiteCollection prerequisites = new InstallationPrerequisiteCollection(installationPrerequisiteProvider);

            prerequisites.Add(new DotNet35Prerequisite(lnkNET, dotNetIndicator));
            prerequisites.Add(new FlashActiveXPerequisite(lnkFlash, flashIndicator));
            prerequisites.Add(new QTPrerequisite(lnkQuickTime, quickTimeIndicator));
            prerequisites.Add(new RAMPrerequisite(ramIndicator));
            prerequisites.Add(new WMPPrerequisite(lnkWMP, wmpIndicator));

            prerequisites.CheckAllPrerequisites();

            AppDataSingleton.Instance.PrerequisitesFullyMet = prerequisites.PrerequisitesFullyMet;

            if (prerequisites.PrerequisitesFullyMet)
            {
                SetupHelper.OpenForm <ExistingUserPromptForm>(this);
                return;
            }

            prerequisites.LogNotMetPrerequisites(logger);
            prerequisites.SetVisualIndicators();

            if (prerequisites.CanContinueWithInstallation)
            {
                lblStatus.Text  = "To enjoy Oxigen to the maximum, it is recommended that you install the optional components above.";
                btnNext.Enabled = true;
            }
            else
            {
                lblStatus.Text = "Please follow the links above to install the required software.";
            }
        }
示例#21
0
        /// <summary>
        ///     Coverts a raw DD image into a VHD file suitable for FFU imaging.
        /// </summary>
        /// <param name="ddfile">The path to the DD file.</param>
        /// <param name="vhdfile">The path to the output VHD file.</param>
        /// <returns></returns>
        public static void ConvertDD2VHD(string ddfile, string vhdfile, string[] partitions, bool Recovery, int SectorSize)
        {
            SetupHelper.SetupContainers();
            Stream strm;

            if (ddfile.ToLower().Contains(@"\\.\physicaldrive"))
            {
                strm = new DeviceStream(ddfile);
            }
            else
            {
                strm = new FileStream(ddfile, FileMode.Open);
            }

            Stream fstream;

            if (!Recovery)
            {
                fstream = new EPartitionStream(strm, partitions);
            }
            else
            {
                fstream = strm;
            }

            using (var inDisk = new Disk(fstream, Ownership.Dispose))
            {
                var diskParams = inDisk.Parameters;

                using (var outDisk = VirtualDisk.CreateDisk("VHD", "dynamic", vhdfile, diskParams, "", ""))
                {
                    var contentStream = inDisk.Content;

                    var pump = new StreamPump
                    {
                        InputStream     = contentStream,
                        OutputStream    = outDisk.Content,
                        SparseCopy      = true,
                        SparseChunkSize = SectorSize,
                        BufferSize      = SectorSize * 1024
                    };

                    var totalBytes = contentStream.Length;

                    var now = DateTime.Now;
                    pump.ProgressEvent += (o, e) => { ShowProgress(totalBytes, now, o, e); };

                    Logging.Log("Converting RAW to VHD");
                    pump.Run();
                    Console.WriteLine();
                }
            }
        }
示例#22
0
        // new user communication
        private void RegisterUserDetails()
        {
            _bThreadStarted = true;

            string macAddress = SetupHelper.GetMACAddress();

            lock (_lockObj)
            {
                try
                {
                    AppDataSingleton.Instance.SetupLogger.WriteMessage("RegisterUserDetails 2");

                    AppDataSingleton.Instance.SetupLogger.WriteMessage("RegisterUserDetails 3");
                    using (var client = new UserDataManagementClient())
                    {
                        AppDataSingleton.Instance.SetupLogger.WriteMessage("RegisterUserDetails 4");

                        _wrapper = client.RegisterNewUser(AppDataSingleton.Instance.EmailAddress,
                                                          AppDataSingleton.Instance.Password,
                                                          AppDataSingleton.Instance.FirstName,
                                                          AppDataSingleton.Instance.LastName,
                                                          AppDataSingleton.Instance.Gender,
                                                          AppDataSingleton.Instance.DOB,
                                                          true,
                                                          AppDataSingleton.Instance.TownCity,
                                                          AppDataSingleton.Instance.State,
                                                          AppDataSingleton.Instance.Country,
                                                          AppDataSingleton.Instance.OccupationSector,
                                                          AppDataSingleton.Instance.EmploymentLevel,
                                                          AppDataSingleton.Instance.AnnualHouseholdIncome,
                                                          AppDataSingleton.Instance.User.UserGUID,
                                                          AppDataSingleton.Instance.User.MachineGUID,
                                                          AppDataSingleton.Instance.User.SoftwareMajorVersionNumber,
                                                          true,
                                                          AppDataSingleton.Instance.User.SoftwareMinorVersionNumber,
                                                          true,
                                                          macAddress,
                                                          AppDataSingleton.Instance.PCName,
                                                          AppDataSingleton.Instance.ChannelSubscriptionsToUpload,
                                                          "password");
                    }



                    AppDataSingleton.Instance.SetupLogger.WriteMessage("RegisterUserDetails 5");
                }
                catch (System.Net.WebException ex)
                {
                    AppDataSingleton.Instance.SetupLogger.WriteError(ex);
                    _wrapper = SetupHelper.GetGenericErrorConnectingWrapper();
                }
            }
        }
示例#23
0
        private void CheckOptionalRequirements(ref bool bWMPExists, ref bool bQTExists)
        {
            if (SetupHelper.WindowsMediaPlayerRightVersionExists())
            {
                bWMPExists = true;
            }

            if (SetupHelper.QuickTimeRightVersionExists())
            {
                bQTExists = true;
            }
        }
        public static void InitializeIdentityForEf(ApplicationDbContext db)
        {
            var authContext = new ApplicationDbContext();
            var rmsContext  = new RMSEntities();
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(authContext));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>());

            SetupHelper.SetupRoles(roleManager);
            CrateStartupAdminUsers(userManager);
            CreateLevel(rmsContext);
            CreateSemester(rmsContext);
        }
示例#25
0
        static void Main(string[] args)
        {
            SetupHelper.RegisterAssembly(typeof(NtfsFileSystem).Assembly);
            SetupHelper.RegisterAssembly(typeof(DiscUtils.Vmdk.Disk).Assembly);
            SetupHelper.RegisterAssembly(typeof(VirtualDiskManager).Assembly);
            SetupHelper.RegisterAssembly(typeof(VirtualDisk).Assembly);
            SetupHelper.RegisterAssembly((typeof(DiscUtils.Vhd.Disk).Assembly));

            if (args.Length != 0 && !string.IsNullOrEmpty(GetArgument(args, "--command")))
            {
                string command = GetArgument(args, "--command");
                if (command.ToLower() == "dir" && GetArgument(args, "--source") != null)
                {
                    var diskimagepath = GetArgument(args, "--source");
                    var directorypath = GetArgument(args, "--directory");
                    try
                    {
                        GetDirListing(diskimagepath, directorypath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\r\n [!] An exception occured: {0}", ex);
                        throw;
                    }
                }
                else if (command.ToLower() == "cp" && GetArgument(args, "--source") != null &&
                         GetArgument(args, "--file2copy") != null && GetArgument(args, "--destination") != null)
                {
                    var diskimagepath = GetArgument(args, "--source");
                    var filepath      = GetArgument(args, "--file2copy");
                    var destination   = GetArgument(args, "--destination");

                    try
                    {
                        GetFile(diskimagepath, filepath, destination);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\r\n [!] An exception occured: {0}", ex);
                        throw;
                    }
                }
                else
                {
                    GetHelp();
                }
            }
            else
            {
                GetHelp();
            }
        }
示例#26
0
        public async Task GetSummaryReportAsync_ShouldReturnSummaryReportDto()
        {
            var now    = DateTimeOffset.UtcNow;
            var client = await SetupHelper.CreateTestClientAsync(_client, _workspaceId);

            var project = await SetupHelper.CreateTestProjectAsync(_client, _workspaceId, client.Id);

            await SetupHelper.CreateTestTimeEntryAsync(_client, _workspaceId, now, project.Id);

            var userResponse = await _client.GetCurrentUserAsync();

            userResponse.IsSuccessful.Should().BeTrue();

            var nowWithTimeZone = DateTimeHelper.ConvertToTimeZone(userResponse.Data.Settings.TimeZone, now);

            var summaryReportRequest = new SummaryReportRequest()
            {
                ExportType         = ExportType.JSON,
                DateRangeStart     = nowWithTimeZone.AddMinutes(-2),
                DateRangeEnd       = nowWithTimeZone.AddMinutes(2),
                SortOrder          = SortOrderType.DESCENDING,
                Description        = String.Empty,
                Rounding           = false,
                WithoutDescription = false,
                AmountShown        = AmountShownType.EARNED,
                Clients            = new ClientsFilterDto {
                    Contains = ContainsType.CONTAINS,
                    Ids      = new List <string> {
                        client.Id
                    },
                    Status = StatusType.ACTIVE
                },
                SummaryFilter = new SummaryFilterDto()
                {
                    Groups = new List <GroupType>()
                    {
                        GroupType.PROJECT
                    }
                },
                TimeZone = userResponse.Data.Settings.TimeZone
            };

            var getSummaryReportResult = await _client.GetSummaryReportAsync(_workspaceId, summaryReportRequest);

            getSummaryReportResult.IsSuccessful.Should().BeTrue();
            getSummaryReportResult.Data.Should().NotBeNull();

            // Cleanup
            var deleteProject = await _client.ArchiveAndDeleteProject(_workspaceId, project.Id);

            deleteProject.IsSuccessful.Should().BeTrue();
        }
        public async Task Invoke(HttpContext httpContext,
                                 IConfiguration configuration,
                                 IHostApplicationLifetime appLifetime,
                                 ILogger <FirstRunMiddleware> logger)
        {
            var initFlag = AppDomain.CurrentDomain.GetData(Token);

            if (null != initFlag)
            {
                // Don't need to check bool true or false, exists means everything
                await _next(httpContext);

                return;
            }

            var conn        = configuration.GetConnectionString(Constants.DbConnectionName);
            var setupHelper = new SetupHelper(conn);

            if (!setupHelper.TestDatabaseConnection(exception =>
            {
                logger.LogCritical(exception, $"Error {nameof(SetupHelper.TestDatabaseConnection)}, connection string: {conn}");
            }))
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await httpContext.Response.WriteAsync("Database connection failed. Please see error log, fix it and RESTART this application.");

                appLifetime.StopApplication();
            }
            else
            {
                if (setupHelper.IsFirstRun())
                {
                    try
                    {
                        logger.LogInformation("Initializing first run configuration...");
                        setupHelper.InitFirstRun();
                        logger.LogInformation("Database setup successfully.");
                    }
                    catch (Exception e)
                    {
                        logger.LogCritical(e, e.Message);
                        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        await httpContext.Response.WriteAsync("Error initializing first run, please check error log.");

                        appLifetime.StopApplication();
                    }
                }

                AppDomain.CurrentDomain.SetData(Token, true);
                await _next(httpContext);
            }
        }
示例#28
0
 private void btnBack_Click(object sender, EventArgs e)
 {
     if (AppDataSingleton.Instance.ChannelSubscriptionsToUpload != null &&
         AppDataSingleton.Instance.ChannelSubscriptionsToUpload.SubscriptionSet != null &&
         AppDataSingleton.Instance.ChannelSubscriptionsToUpload.SubscriptionSet.Length > 0)
     {
         SetupHelper.OpenForm <PCNameStreamSubscriptionsForm>(this);
     }
     else
     {
         SetupHelper.OpenForm <UserDetailsForm>(this);
     }
 }
示例#29
0
        public async Task AddUserToWorkspace_ShouldReturnWorkspaceSettings()
        {
            string _workspaceId = await SetupHelper.CreateOrFindWorkspaceAsync(_client, "Clockify.NetTestWorkspace");

            var request = new WorkspaceAddUserRequest
            {
                Email = Guid.NewGuid() + "@example.com",
            };

            var response = await _client.AddWorkspaceUser(_workspaceId, request);

            response.StatusCode.Equals(HttpStatusCode.Created);
        }
示例#30
0
        public ActionResult Upgrading_Database_Ready()
        {
            SqlConnection sqlConnection = GetConnection();

            //注册应用中的Application.Config
            foreach (var applicationConfig in ApplicationConfigManager.Instance().GetAllApplicationConfigs())
            {
                if (applicationConfig.Element("tenantAttachmentSettings") != null)
                {
                    TenantAttachmentSettings.RegisterSettings(applicationConfig.Element("tenantAttachmentSettings"));
                }
                if (applicationConfig.Element("tenantLogoSettings") != null)
                {
                    TenantLogoSettings.RegisterSettings(applicationConfig.Element("tenantLogoSettings"));
                }
            }

            ConcurrentDictionary <string, string> messages = new ConcurrentDictionary <string, string>();

            //修改3.2版本的表名
            string reNameSqlFile = SetupHelper.GetUpgradeReNameFile();

            try
            {
                SetupHelper.ExecuteInFile(sqlConnection, reNameSqlFile, out messages);
            }
            catch (Exception e)
            {
                if (!messages.ContainsKey("在文件:" + reNameSqlFile + " 中产生异常"))
                {
                    messages["在文件:" + reNameSqlFile + " 中产生异常"] = e.Message + "\r\n";
                }
                else
                {
                    messages["在文件:" + reNameSqlFile + " 中产生异常"] += e.Message + "\r\n";
                }
            }

            foreach (var message in messages)
            {
                WriteLogFile(string.Format("{0}:{1}", message.Key, message.Value));
            }
            if (messages.Count > 0)
            {
                return(Json(new StatusMessageData(StatusMessageType.Error, "升级数据库准备失败,请查看升级日志")));
            }
            else
            {
                return(Json(new StatusMessageData(StatusMessageType.Success, "升级数据库准备就绪。")));
            }
        }
示例#31
0
        /// <summary>
        /// Helper function to read and validate the header
        /// </summary>
        private void ReadEncryptionHeader(string password)
        {
            byte[] tmp = new byte[MAGIC_HEADER.Length + 2];
            if (m_stream.Read(tmp, 0, tmp.Length) != tmp.Length)
                throw new InvalidDataException(Strings.InvalidHeaderMarker);

            for (int i = 0; i < MAGIC_HEADER.Length; i++)
                if (MAGIC_HEADER[i] != tmp[i])
                    throw new InvalidDataException(Strings.InvalidHeaderMarker);

            m_version = tmp[MAGIC_HEADER.Length];
            if (m_version > MAX_FILE_VERSION)
                throw new InvalidDataException(string.Format(Strings.UnsupportedFileVersion, m_version));

            if (m_version == 0)
            {
                m_paddingSize = tmp[MAGIC_HEADER.Length + 1];
                if (m_paddingSize >= BLOCK_SIZE)
                    throw new InvalidDataException(Strings.InvalidHeaderMarker);
            }
            else if (tmp[MAGIC_HEADER.Length + 1] != 0)
                throw new InvalidDataException(Strings.InvalidReservedFieldValue);

            //Extensions are only supported in v2+
            if (m_version >= 2)
            {
                int extensionLength = 0;
                do
                {
                    byte[] tmpLength = RepeatRead(m_stream, 2);
                    extensionLength = (((int)tmpLength[0]) << 8) | (tmpLength[1]);

                    if (extensionLength != 0)
                    {
                        byte[] data = RepeatRead(m_stream, extensionLength);
                        int separatorIndex = Array.IndexOf<byte>(data, 0);
                        if (separatorIndex < 0)
                            throw new InvalidDataException(Strings.InvalidExtensionData);

                        string key = System.Text.Encoding.UTF8.GetString(data, 0, separatorIndex);
                        byte[] value = new byte[data.Length - separatorIndex - 1];
                        Array.Copy(data, separatorIndex + 1, value, 0, value.Length);

                        m_extensions.Add(new KeyValuePair<string, byte[]>(key, value));
                    }

                } while (extensionLength > 0);
            }

            byte[] iv1 = RepeatRead(m_stream, IV_SIZE);
            m_helper = new SetupHelper(m_mode, password, iv1);

            if (m_version >= 1)
            {
                byte[] hmac1 = m_helper.DecryptAESKey2(RepeatRead(m_stream, IV_SIZE + KEY_SIZE));
                byte[] hmac2 = RepeatRead(m_stream, hmac1.Length);
                for (int i = 0; i < hmac1.Length; i++)
                    if (hmac1[i] != hmac2[i])
                        throw new CryptographicException(Strings.InvalidPassword);

                m_payloadLength = m_stream.Length - m_stream.Position - (HASH_SIZE + 1);
            }
            else
            {
                m_helper.SetBulkKeyToKey1();

                m_payloadLength = m_stream.Length - m_stream.Position - HASH_SIZE;
            }

            if (m_payloadLength % BLOCK_SIZE != 0)
                throw new CryptographicException(Strings.InvalidFileLength);
        }
示例#32
0
        /// <summary>
        /// Releases all resources used by the instance, and flushes any data currently held, into the stream
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                if (m_mode == OperationMode.Encrypt && !m_hasFlushedFinalBlock)
                    FlushFinalBlock();

                m_crypto.Dispose();
                m_crypto = null;
                m_stream.Dispose();
                m_stream = null;
                m_extensions = null;
                m_helper.Dispose();
                m_helper = null;
                m_hmac = null;
            }
        }
示例#33
0
        /// <summary>
        /// Constructs a new AESCrypt instance, operating on the supplied stream
        /// </summary>
        /// <param name="password">The password used for encryption or decryption</param>
        /// <param name="stream">The stream to operate on, must be writeable for encryption, and readable for decryption</param>
        /// <param name="mode">The mode of operation, either OperationMode.Encrypt or OperationMode.Decrypt</param>
        public SharpAESCrypt(string password, Stream stream, OperationMode mode)
        {
            //Basic input checks
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (password == null)
                throw new ArgumentNullException("password");
            if (mode != OperationMode.Encrypt && mode != OperationMode.Decrypt)
                throw new ArgumentException(Strings.InvalidOperationMode, "mode");
            if (mode == OperationMode.Encrypt && !stream.CanWrite)
                throw new ArgumentException(Strings.StreamMustBeWriteAble, "stream");
            if (mode == OperationMode.Decrypt && !stream.CanRead)
                throw new ArgumentException(Strings.StreamMustBeReadAble, "stream");

            m_mode = mode;
            m_stream = stream;
            m_extensions = new List<KeyValuePair<string, byte[]>>();

            if (mode == OperationMode.Encrypt)
            {
                this.Version = DefaultFileVersion;

                m_helper = new SetupHelper(mode, password, null);

                //Setup default extensions
                if (Extension_InsertCreateByIdentifier)
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-BY", System.Text.Encoding.UTF8.GetBytes(Extension_CreatedByIdentifier)));

                if (Extension_InsertTimeStamp)
                {
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-DATE", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy-MM-dd"))));
                    m_extensions.Add(new KeyValuePair<string, byte[]>("CREATED-TIME", System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToUniversalTime().ToString("hh-mm-ss"))));
                }

                if (Extension_InsertPlaceholder)
                    m_extensions.Add(new KeyValuePair<string, byte[]>("", new byte[127])); //Suggested extension space

                //We defer creation of the cryptostream until it is needed,
                // so the caller can change version, extensions, etc.
                // before we write the header
                m_crypto = null;
            }
            else
            {
                //Read and validate
                ReadEncryptionHeader(password);

                m_hmac = m_helper.GetHMAC();

                //Insert the HMAC before the decryption so the HMAC is calculated for the ciphertext
                m_crypto = new CryptoStream(new CryptoStream(new StreamHider(m_stream, m_version == 0 ? HASH_SIZE : (HASH_SIZE + 1)), m_hmac, CryptoStreamMode.Read), m_helper.CreateCryptoStream(m_mode), CryptoStreamMode.Read);
            }
        }