public bool Handle(IPacket header, IIBLVMSocket socket)
        {
            if (header.Type == PacketType.ServerBitLockerUnlockRequest)
            {
                Utils.PacketValidation(socket.Status, (int)ClientSocketStatus.LoggedIn, header.GetPayloadSize(), false);

                IPayload <ServerBitLockerUnlock> packet = socket.PacketFactory.CreateServerBitLockerUnlockRequest(null, null, socket.CryptoProvider);
                packet.ParsePayload(header.GetPayloadSize(), socket.SocketStream);

                DriveInformation volume = packet.Payload.Drive;

                BitLocker bitLocker = BitLocker.GetVolume(volume.Name);
                bool      isSuccess = true;
                try
                {
                    bitLocker.Unlock(packet.Payload.Password);
                }
                catch (Exception)
                {
                    isSuccess = false;
                }

                IPayload <bool> result = socket.PacketFactory.CreateClientBitLockerCommandResponse(isSuccess);
                Utils.SendPacket(socket.SocketStream, result);
            }

            return(false);
        }
Exemplo n.º 2
0
        public ConfigItem(DriveInformation _DI)
        {
            DI = _DI;
            InitializeComponent();
            SourceLabel.Visibility              = Visibility.Collapsed;
            SourcePathTextBox.Visibility        = Visibility.Collapsed;
            DestinationLabel.Visibility         = Visibility.Collapsed;
            DestinationPathTextBox.Visibility   = Visibility.Collapsed;
            SaveButton.Visibility               = Visibility.Collapsed;
            SourceValidationIco.Visibility      = Visibility.Collapsed;
            DestinationValidationIco.Visibility = Visibility.Collapsed;

            if (DI.isMonitoring)
            {
                MonitoringCheckBox.IsChecked = true;

                SourcePathTextBox.Text      = DI.source;
                DestinationPathTextBox.Text = DI.destination;

                SourceLabel.Visibility            = Visibility.Visible;
                SourcePathTextBox.Visibility      = Visibility.Visible;
                DestinationLabel.Visibility       = Visibility.Visible;
                DestinationPathTextBox.Visibility = Visibility.Visible;
            }
        }
Exemplo n.º 3
0
        public List <DriveInformation> GetDriveInformation()
        {
            var q          = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
            var res        = new ManagementObjectSearcher(q);
            var driveNames = (from ManagementBaseObject o in res.Get() select o["Model"]?.ToString()).ToList();
            var driveList  = new List <DriveInformation>();
            var drives     = DriveInfo.GetDrives();

            for (var index = 0; index < drives.Length; index++)
            {
                var drive     = drives[index];
                var driveInfo = new DriveInformation();
                if (!drive.IsReady)
                {
                    continue;
                }
                driveInfo.Model         = driveNames.ElementAtOrDefault(index) != null ? driveNames[index] : "Unknown Model";
                driveInfo.Name          = drive.Name;
                driveInfo.FreeSpace     = drive.TotalFreeSpace;
                driveInfo.TotalSize     = drive.TotalSize;
                driveInfo.DriveType     = drive.DriveType.ToString();
                driveInfo.DriveFormat   = drive.DriveFormat;
                driveInfo.VolumeLabel   = drive.VolumeLabel;
                driveInfo.RootDirectory = drive.RootDirectory.ToString();
                driveInfo.IsReady       = drive.IsReady;
                driveList.Add(driveInfo);
            }
            return(driveList);
        }
Exemplo n.º 4
0
            public bool RequestBitLockerUnlock(IDevice device, DriveInformation drive, string password)
            {
                BitLockerControlEventArgs args = new BitLockerControlEventArgs(device, drive, false, password);

                BroadcastBitLockerControl(args);

                return(args.IsSuccess);
            }
Exemplo n.º 5
0
            public bool RequestBitLockerLock(IDevice device, DriveInformation drive)
            {
                BitLockerControlEventArgs args = new BitLockerControlEventArgs(device, drive, true);

                BroadcastBitLockerControl(args);

                return(args.IsSuccess);
            }
Exemplo n.º 6
0
        private void RegisterDialog_Load(object sender, EventArgs e)
        {
            this.BindingControlEventHandler();
            DriveInformation drv = Licensing.GetDriveInfo();

            this.GetSrvRegData();
            this.lblSN.Text          = RegisterDialog.ReadSernum();
            this.lblMachineCode.Text = Licensing.GetHDDSerialNumber(Licensing.GetSystemDriveLetter());
        }
Exemplo n.º 7
0
        public void UnlockBirLockerDrive(IDevice device, DriveInformation drive, string password)
        {
            if (Status != (int)ClientSocketStatus.LoggedIn)
            {
                throw new InvalidOperationException("Not logged in!");
            }

            Utils.SendPacket(SocketStream, PacketFactory.CreateManagerBitLockerUnlockRequest(new ClientDrive(device.DeviceIP, drive), password, CryptoProvider));
        }
Exemplo n.º 8
0
 public PanelClass()
 {
     _modelObject   = new DriveInformation();
     ListaDyskow    = ListaDyskow;
     WybranyDysk    = _listaDyskow[0];
     _wybranyFolder = -1;
     Sciezka        = WybranyDysk;
     ListaFolderow  = new string[] { "1", "2" };
     odswiez();
 }
Exemplo n.º 9
0
 public void ResolveToRootUNCTest(string path, object result)
 {
     // If result is null, the expected outcome is an exception.
     // otherwise its a string value with the drive name.
     if (result is null)
     {
         Assert.ThrowsException<ArgumentException>(() => DriveInformation.ResolveToRootUNC(path));
     }
     else
     {
         Assert.AreEqual(result, DriveInformation.ResolveToRootUNC(path));
     }
 }
Exemplo n.º 10
0
 public void IsNetworkDriveTest(string path, int result)
 {
     // If result = -1, the expected outcome is an exception.
     // otherwise its a boolean value.
     if(result == -1)
     {
         Assert.ThrowsException<ArgumentException>(() => DriveInformation.IsNetworkDrive(path));
     }
     else
     {
         Assert.AreEqual(Convert.ToBoolean(result), DriveInformation.IsNetworkDrive(path));
     }
 }
Exemplo n.º 11
0
        public void LockBitLockerDrive(IDevice device, DriveInformation drive)
        {
            if (Status != (int)ClientSocketStatus.LoggedIn)
            {
                throw new InvalidOperationException("Not logged in!");
            }

            if (!drive.IsBitLocker || drive.IsProtected)
            {
                throw new InvalidOperationException("Cannot BitLocker drive lock!");
            }

            Utils.SendPacket(SocketStream, PacketFactory.CreateManagerBitLockerLockRequest(new ClientDrive(device.DeviceIP, drive)));
        }
Exemplo n.º 12
0
        public void IsFreeSpaceAvailableTest(string path, object result)
        {
            var fileSize = 1L;

            // If result is null, the expected outcome is an exception.
            // otherwise its a string value with the drive name.
            if (result is null)
            {
                Assert.ThrowsException<ArgumentException>(() => DriveInformation.IsFreeSpaceAvailable(path, fileSize));
            }
            else
            {
                Assert.AreEqual(Convert.ToBoolean(result), DriveInformation.IsFreeSpaceAvailable(path, fileSize));
            }
        }
Exemplo n.º 13
0
        public Drive(DriveInformation _DI)
        {
            InitializeComponent();

            DI = _DI;

            DriveNameTextBlock.Text = _DI.Name;

            if (_DI.isMonitoring)
            {
                MonitoringIc.Visibility = Visibility.Visible;
                BeginFileManager();
            }
            else
            {
                MonitoringIc.Visibility = Visibility.Collapsed;
            }

            StatusLabel.Content = "Doing Nothing";
        }
Exemplo n.º 14
0
        public static string GetSourceName(string sourcePath)
        {
            switch (GetSourceType(sourcePath))
            {
            case SourceType.DiscVideoFolder:
                return(GetSourceNameFolder(sourcePath));

            case SourceType.Disc:
                var driveService      = Ioc.Get <IDriveService>();
                DriveInformation info = driveService.GetDriveInformationFromPath(sourcePath);
                if (info != null)
                {
                    return(info.VolumeLabel);
                }
                else
                {
                    return(GetSourceNameFile(sourcePath));
                }

            default:
                return(GetSourceNameFile(sourcePath));
            }
        }
Exemplo n.º 15
0
        public static int GetDirectoryId(SQLiteConnection db, DriveInformation drive, DirectoryInfo directory)
        {
            var directoryPath = directory.ToDirectoryPath();
            directoryPath = (directoryPath ?? string.Empty).Trim();

            var cmd = db.CreateCommand("Select * from " + typeof(DirectoryInformation).Name + " Where DriveId = ? AND Path = ?", drive.DriveId, directoryPath);
            var retVal = cmd.ExecuteQuery<DirectoryInformation>().FirstOrDefault();

            if (retVal != null) {
                return retVal.DirectoryId;
            }

            int? parentDirectoryInfo = null;

            if (directory.Parent != null) {
                var parentName = directory.Parent.FullName.Substring(3);
                parentDirectoryInfo = GetDirectoryId(db, drive, directory.Parent);
            }

            var directoryName = directory.Name;

            if (directoryName.IndexOf(":") > -1) {
                directoryName = directoryName.Substring(3);
            }

            //create a new record
            var newDirectory = new DirectoryInformation() {
                DriveId = drive.DriveId,
                Name = directoryName,
                ParentDirectoryId = parentDirectoryInfo.HasValue ? parentDirectoryInfo : null,
                Path = directoryPath
            };

            db.Insert(newDirectory);

            return newDirectory.DirectoryId;
        }
Exemplo n.º 16
0
 public IPayload <ServerBitLockerUnlock> CreateServerBitLockerUnlockRequest(DriveInformation drive, string password, CryptoProvider cryptor) => new ServerBitLockerUnlockRequest(drive, password, cryptor);
Exemplo n.º 17
0
        public List <DriveInformation> GetDriveInformation()
        {
            var q          = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
            var res        = new ManagementObjectSearcher(q);
            var driveNames = (from ManagementBaseObject o in res.Get() select o["Model"]?.ToString()).ToList();
            var driveList  = new List <DriveInformation>();
            var drives     = DriveInfo.GetDrives();

            for (var index = 0; index < drives.Length; index++)
            {
                try
                {
                    var drive     = drives[index];
                    var driveInfo = new DriveInformation();
                    if (!drive.IsReady)
                    {
                        continue;
                    }
                    driveInfo.Model         = driveNames.ElementAtOrDefault(index) != null ? driveNames[index] : "Unknown Model";
                    driveInfo.Name          = drive.Name;
                    driveInfo.FreeSpace     = drive.TotalFreeSpace;
                    driveInfo.TotalSize     = drive.TotalSize;
                    driveInfo.DriveType     = drive.DriveType.ToString();
                    driveInfo.DriveFormat   = drive.DriveFormat;
                    driveInfo.VolumeLabel   = drive.VolumeLabel;
                    driveInfo.RootDirectory = drive.RootDirectory.ToString();
                    driveInfo.IsReady       = drive.IsReady;
                    //just set it for now
                    driveInfo.SmartData  = new List <SmartModel>();
                    driveInfo.Partitions = new List <PartitionModel>();
                    driveList.Add(driveInfo);
                    try
                    {
                        var mosDisks =
                            new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" +
                                                         driveInfo.Model + "'").Get().GetEnumerator();
                        if (!mosDisks.MoveNext())
                        {
                            continue;
                        }
                        driveInfo.MediaType = mosDisks.Current.GetPropertyValue("MediaType")?.ToString() ?? "Unknown";
                        driveInfo.Serial    = mosDisks.Current.GetPropertyValue("SerialNumber")?.ToString()?.Trim() ??
                                              "Unknown";
                        driveInfo.Interface = mosDisks.Current.GetPropertyValue("InterfaceType")?.ToString() ??
                                              "Unknown";
                        driveInfo.TotalPartitions = mosDisks.Current.GetPropertyValue("Partitions")?.ToString() ??
                                                    "Unknown";
                        driveInfo.Signature = mosDisks.Current.GetPropertyValue("Signature")?.ToString() ?? "Unknown";
                        driveInfo.Firmware  = mosDisks.Current.GetPropertyValue("FirmwareRevision")?.ToString() ??
                                              "Unknown";
                        driveInfo.Cylinders = mosDisks.Current.GetPropertyValue("TotalCylinders")?.ToString() ??
                                              "Unknown";
                        driveInfo.Sectors        = mosDisks.Current.GetPropertyValue("TotalSectors")?.ToString() ?? "Unknown";
                        driveInfo.Heads          = mosDisks.Current.GetPropertyValue("TotalHeads")?.ToString() ?? "Unknown";
                        driveInfo.Tracks         = mosDisks.Current.GetPropertyValue("TotalTracks")?.ToString() ?? "Unknown";
                        driveInfo.BytesPerSecond = mosDisks.Current.GetPropertyValue("BytesPerSector")?.ToString() ??
                                                   "Unknown";
                        driveInfo.SectorsPerTrack = mosDisks.Current.GetPropertyValue("SectorsPerTrack")?.ToString() ??
                                                    "Unknown";
                        driveInfo.TracksPerCylinder =
                            mosDisks.Current.GetPropertyValue("TracksPerCylinder")?.ToString() ?? "Unknown";
                    }
                    catch (Exception ex)
                    {
                        // Console.WriteLine(ex.Message);
                        //Console.WriteLine(ex.StackTrace);
                    }

                    try
                    {
                        var mosPartition =
                            new ManagementObjectSearcher("SELECT * FROM Win32_DiskPartition WHERE DiskIndex = '" +
                                                         index + "'").Get().GetEnumerator();
                        while (mosPartition.MoveNext())
                        {
                            var partion = new PartitionModel
                            {
                                Name           = mosPartition.Current.GetPropertyValue("Name")?.ToString() ?? "Unknown",
                                Size           = mosPartition.Current.GetPropertyValue("Size")?.ToString() ?? "Unknown",
                                BlockSize      = mosPartition.Current.GetPropertyValue("BlockSize")?.ToString() ?? "Unknown",
                                StartingOffset =
                                    mosPartition.Current.GetPropertyValue("StartingOffset")?.ToString() ?? "Unknown",
                                Index         = mosPartition.Current.GetPropertyValue("Index")?.ToString() ?? "Unknown",
                                DiskIndex     = mosPartition.Current.GetPropertyValue("DiskIndex")?.ToString() ?? "Unknown",
                                BootPartition =
                                    mosPartition.Current.GetPropertyValue("BootPartition")?.ToString() ?? "Unknown",
                                PrimaryPartition =
                                    mosPartition.Current.GetPropertyValue("PrimaryPartition")?.ToString() ?? "Unknown",
                                Bootable = mosPartition.Current.GetPropertyValue("Bootable")?.ToString() ?? "Unknown"
                            };
                            driveInfo.Partitions.Add(partion);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Console.WriteLine(ex.Message);
                        //Console.WriteLine(ex.StackTrace);
                    }
                }
                catch (Exception ex)
                {
                    // Console.WriteLine(ex.Message);
                    // Console.WriteLine(ex.StackTrace);
                }
            }

            using (
                var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData")
                )
                using (
                    var thresSearcher = new ManagementObjectSearcher("root\\WMI",
                                                                     "SELECT * FROM MSStorageDriver_FailurePredictThresholds"))
                    using (
                        var failureSearch = new ManagementObjectSearcher("root\\WMI",
                                                                         "SELECT * FROM MSStorageDriver_FailurePredictStatus"))
                    {
                        try
                        {
                            var searcherEnumerator      = searcher.Get().GetEnumerator();
                            var thresSearcherEnumerator = thresSearcher.Get().GetEnumerator();
                            var failureSearchEnumerator = failureSearch.Get().GetEnumerator();

                            var index = 0;
                            while (searcherEnumerator.MoveNext() && thresSearcherEnumerator.MoveNext())
                            {
                                var arrVendorSpecific = (byte[])searcherEnumerator.Current.GetPropertyValue("VendorSpecific");
                                var arrThreshold      = (byte[])thresSearcherEnumerator.Current.GetPropertyValue("VendorSpecific");

                                /* Create SMART data from 'vendor specific' array */
                                var d         = new SmartData(arrVendorSpecific, arrThreshold);
                                var smartRows = (from b in d.Attributes
                                                 where !Regex.IsMatch(b.AttributeType.ToString(), @"^\d+$")
                                                 let rawData =
                                                     BitConverter.ToString(b.VendorData.Reverse().ToArray()).Replace("-", string.Empty)
                                                     select
                                                     new SmartModel(b.AttributeType.ToString(),
                                                                    b.Value.ToString(CultureInfo.InvariantCulture),
                                                                    b.Threshold.ToString(CultureInfo.InvariantCulture), rawData,
                                                                    long.Parse(rawData, NumberStyles.HexNumber).ToString(CultureInfo.InvariantCulture)))
                                                .ToList();
                                driveList.ElementAt(index).SmartData = smartRows;
                                if (failureSearchEnumerator.MoveNext())
                                {
                                    driveList.ElementAt(index).DriveHealth =
                                        (bool)failureSearchEnumerator.Current.GetPropertyValue("PredictFailure")
                                    ? "WARNING"
                                    : "OK";
                                }
                                index++;
                            }
                        }
                        catch (Exception ex)
                        {
                            //  Console.WriteLine(ex.Message);
                            //  Console.WriteLine(ex.StackTrace);
                        }
                    }
            return(driveList);
        }
Exemplo n.º 18
0
        private static void ProcessFolder(SQLiteConnection db, DriveInformation drive, List<string> arrHeaders, DirectoryInfo directory)
        {
            try {

                if (!directory.Exists)
                    return;

                if (IgnoreFolder(directory)) {
                    return;
                }

                //go get the cached items for the folder.

                var directoryId = DatabaseLookups.GetDirectoryId(db, drive, directory);

                var cmd = db.CreateCommand("Select * from " + typeof(FileInformation).Name + " Where DriveId = ? AND DirectoryId = ?", drive.DriveId, directoryId);
                var databaseFiles = cmd.ExecuteQuery<FileInformation>();

                //obtain the file metadata for all of the files in the directory so we can determine if we care about this folder.

                var processList = GetFilesToProcess(databaseFiles, arrHeaders, directory);

                if (processList.Count > 0) {

                    db.BeginTransaction();

                    Shell32.Shell shell = new Shell32.Shell();
                    Shell32.Folder folder = shell.NameSpace(directory.FullName);

                    foreach (var item in processList) {
                        try {
                            var fi = item.FileInfo;
                            var headerList = new List<FileAttributeInformation>();

                            for (int i = 0; i < arrHeaders.Count; i++) {

                                var header = arrHeaders[i];

                                if (!IgnoreHeader(header)) {
                                    var value = folder.GetDetailsOf(item.FolderItem, i);

                                    if (!string.IsNullOrWhiteSpace(value)) {
                                        headerList.Add(new FileAttributeInformation() {
                                            AttributeId = DatabaseLookups.GetAttributeId(db, header),
                                            Value = value
                                        });
                                    }
                                }
                            }

                            //this should have been already checked but we want to be safe.
                            if (fi.Exists) {

                                var fileInfo = databaseFiles.FirstOrDefault(info => info.FileName.Equals(fi.Name, StringComparison.OrdinalIgnoreCase));

                                if (fileInfo == null) {
                                    fileInfo = new FileInformation() {
                                        DriveId = drive.DriveId,
                                        DirectoryId = directoryId,
                                        FileName = fi.Name
                                    };
                                    SetFileInformation(fi, fileInfo);
                                    db.Insert(fileInfo);
                                    Console.WriteLine("Inserted:" + fi.FullName);
                                }
                                else {
                                    SetFileInformation(fi, fileInfo);
                                    db.Update(fileInfo);

                                    var deleteCount = db.Execute("Delete from " + typeof(FileAttributeInformation).Name + " WHERE FileId = ?", fileInfo.FileId);
                                    Console.WriteLine("Changed:" + fi.FullName);
                                }

                                //save the headers
                                headerList.ForEach(hl => hl.FileId = fileInfo.FileId);
                                db.InsertAll(headerList);
                            }
                        }
                        catch (Exception ex) {
                            Console.WriteLine(ex.ToString());
                        }
                    }

                    db.Commit();

                }

                //see if we have any additional folders. If we get access denied it will throw an error
                try {
                    foreach (var subDirectory in directory.GetDirectories()) {
                        ProcessFolder(db, drive, arrHeaders, subDirectory);
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                }
            }
            catch (UnauthorizedAccessException) {

            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 19
0
 public FunctionalityVM()
 {
     mainModelObject = new DriveInformation();
     lewy            = new PanelClass();
     prawy           = new PanelClass();
 }
Exemplo n.º 20
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            LoadingScreen ls = new LoadingScreen();

            ls.ShowCenterParent(this);

            SRV_RegisterData srv_regdata = new SRV_RegisterData();

            srv_regdata._conn_success  = false;
            srv_regdata._failed_reason = SRV_RegisterData.FAILED_REASON.NONE;

            LOC_RegisterData loc_regdata = new LOC_RegisterData();

            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += delegate
            {
                DriveInformation drive = Licensing.GetDriveInfo();

                //loc_regdata.token_key = Licensing.CalcMD5(drive.hddSerialNumber);
                //loc_regdata.machine_code = drive.hddSerialNumber;
                loc_regdata.token_key     = Licensing.CalcMD5(Licensing.GetHDDSerialNumber(Licensing.GetSystemDriveLetter()));
                loc_regdata.machine_code  = Licensing.GetHDDSerialNumber(Licensing.GetSystemDriveLetter());
                loc_regdata.comp_name     = Licensing.GetServerCompName();
                loc_regdata.reg_type      = (Licensing.IsLAN() ? "LAN" : "LOCAL");
                loc_regdata.sernum        = this.sernum;
                loc_regdata.contact       = this.contact;
                loc_regdata.telnum        = this.telnum;
                loc_regdata.email         = this.email;
                loc_regdata.remark        = this.remark;
                loc_regdata.slip_filename = Path.GetFileName(this.slip_file_path);
                loc_regdata.tax_filename  = Path.GetFileName(this.tax_file_path);

                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("token_key", loc_regdata.token_key);
                nvc.Add("machine_code", loc_regdata.machine_code);
                nvc.Add("comp_name", loc_regdata.comp_name);
                nvc.Add("reg_type", loc_regdata.reg_type);
                nvc.Add("sernum", loc_regdata.sernum);
                nvc.Add("contact", loc_regdata.contact);
                nvc.Add("telnum", loc_regdata.telnum);
                nvc.Add("email", loc_regdata.email);
                nvc.Add("remark", loc_regdata.remark);
                nvc.Add("slip_filename", loc_regdata.slip_filename);

                try
                {
                    string       upload_tax_result = WebComm.UploadMultipart("http://www.esg.co.th/XML-Exporter/upload_tax_file.php", this.tax_file_path, "file1", "image/jpg", nvc);
                    ServerResult sr = JsonConvert.DeserializeObject <ServerResult>(upload_tax_result);
                    nvc.Add("tax_filename", sr.message);

                    string web_result = WebComm.UploadMultipart("http://www.esg.co.th/XML-Exporter/upload_register.php", this.slip_file_path, "file1", "image/jpg", nvc);
                    //WebResult web_result = WebComm.UploadMultipart("http://www.weetee.com:3636/XML-Exporter/upload.php", this.file_path, "file1", "image/jpg", nvc);
                    srv_regdata = JsonConvert.DeserializeObject <SRV_RegisterData>(web_result);
                    //loc_regdata.status_code = srv_regdata.status_code;
                    //loc_regdata.status = srv_regdata.status;
                    loc_regdata.reg_date     = DateTime.Parse(srv_regdata.reg_date, CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
                    loc_regdata.reg_time     = srv_regdata.reg_time;
                    loc_regdata.reg_unixtime = srv_regdata.reg_unixtime;
                }
                catch (Exception ex)
                {
                    srv_regdata._conn_success = false;
                }
            };
            worker.RunWorkerCompleted += delegate
            {
                ls.Close();

                if (srv_regdata._conn_success)
                {
                    if ((int)srv_regdata._failed_reason == (int)SRV_RegisterData.FAILED_REASON.NONE)
                    {
                        //if (Licensing.WriteTokenKey(loc_regdata.token_key, loc_regdata.machine_code, loc_regdata.comp_name, loc_regdata.reg_type, loc_regdata.sernum, loc_regdata.contact, loc_regdata.telnum, loc_regdata.email, loc_regdata.remark, loc_regdata.slip_filename, loc_regdata.status_code, loc_regdata.status, loc_regdata.reg_date.ToString("yyyy-MM-dd", CultureInfo.GetCultureInfo("en-US")), loc_regdata.reg_time, loc_regdata.reg_unixtime))
                        if (Licensing.WriteTokenKey(loc_regdata.token_key, loc_regdata.machine_code, loc_regdata.comp_name, loc_regdata.reg_type, loc_regdata.sernum, loc_regdata.contact, loc_regdata.telnum, loc_regdata.email, loc_regdata.remark, loc_regdata.slip_filename, loc_regdata.reg_date.ToString("yyyy-MM-dd", CultureInfo.GetCultureInfo("en-US")), loc_regdata.reg_time, loc_regdata.reg_unixtime))
                        {
                            MessageBox.Show("ส่งข้อมูลการลงทะเบียนโปรแกรมเรียบร้อย, เมื่อข้อมูลดังกล่าวได้รับการตรวจสอบจากทางบริษัทฯ แล้ว ท่านจะสามารถใช้งานความสามารถทั้งหมดของโปรแกรมได้ในทันที\n(โดยปกติใช้เวลาไม่เกิน 1 วันทำการ)");
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        return;
                    }

                    if ((int)srv_regdata._failed_reason == (int)SRV_RegisterData.FAILED_REASON.DUPLICATE_SN)
                    {
                        MessageBox.Show(srv_regdata._failed_reason.ToReasonString());
                        return;
                    }
                }

                if (!srv_regdata._conn_success && srv_regdata._failed_reason == SRV_RegisterData.FAILED_REASON.NONE)
                {
                    MessageBox.Show("ไม่สามารถส่งข้อมูลการลงทะเบียนได้, กรุณาตรวจสอบการเชื่อมต่ออินเทอร์เน็ต", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            };
            worker.RunWorkerAsync();
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string xmlUserdataDrives   = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WindowsBackupManager\\userdata_drives.xml";
            string xmlUserdataSchedule = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WindowsBackupManager\\userdata_schedule.xml";
            string xmlUserdataMail     = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WindowsBackupManager\\userdata_mail.xml";
            string backupLogFolder     = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + "\\Logs\\WindowsBackup";
            string backupSuccessLog    = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\WindowsBackupManager\\backupSuccessLog.txt";
            bool   isBackupSuccess     = true;

            Console.WriteLine("Windows Backup Manager\nPROGRAMM START");
            Console.WriteLine();
            //LogFile
            string logFile = "log.txt";

            //Einlesen der XML Daten
            #region einlesen XML DAten
            //Einlesen der XML Daten

            //Einlesen der zu sichernden Festplatten und der Sicherungsfestplatten
            if (File.Exists(xmlUserdataDrives))
            {
                XmlSerializer xs   = new XmlSerializer(typeof(XML_Drives));
                FileStream    read = new FileStream(xmlUserdataDrives, FileMode.Open, FileAccess.Read, FileShare.Read);

                XML_Drives datenDrives = (XML_Drives)xs.Deserialize(read);

                string systemDrives = "";
                string backupDrive  = "";
                double neededSpace  = 0.00;
                double freeSpace    = 0.00;

                //Ermittlung der zu sichernden Festplatten

                foreach (string serialNumber in datenDrives.systemDrivesSerialnumbers)
                {
                    try
                    {
                        DriveInformation driveInformation = new DriveInformation();
                        driveInformation = driveInformation.GetDriveInformation(serialNumber);
                        neededSpace     += driveInformation.UsedSpace;

                        string message = $"Zu sicherndes Laufwerk gefunden: {driveInformation}";
                        Console.WriteLine(message);

                        systemDrives += $"{driveInformation.DeviceID},";
                        WriteLog(logFile, message, true);

                        //Sicherungsfestplatte suchen
                    }
                    catch (DriveNotFoundException)
                    {
                        string message = $"Zu sicherndes Laufwerk mit Seriennummer: {serialNumber} nicht gefunden.";
                        WriteLog(logFile, message, false);
                        Console.WriteLine(message);
                    }
                }

                foreach (string backupDriveSerialNumber in datenDrives.backupDrives)
                {
                    try
                    {
                        DriveInformation backupDriveInformation = new DriveInformation();
                        backupDriveInformation = backupDriveInformation.GetDriveInformation(backupDriveSerialNumber);

                        freeSpace = backupDriveInformation.FreeSpace;
                        string message = $"Sicherungslaufwerk gefunden: {backupDriveInformation}";
                        WriteLog(logFile, message, true);
                        Console.WriteLine(message);

                        if (freeSpace > neededSpace)
                        {
                            backupDrive += backupDriveInformation.DeviceID;

                            //Beenden da ein Sicherungslaufwerk gefunden wurde.
                            break;
                        }
                        else
                        {
                            throw new System.IO.IOException();
                        }
                    }
                    catch (DriveNotFoundException)
                    {
                        string message = $"Sicherungslaufwerk mit der Seriennummer {backupDriveSerialNumber} nicht gefunden.";

                        WriteLog(logFile, message, false);
                        Console.WriteLine(message);
                    }
                    catch (System.IO.IOException)
                    {
                        DriveInformation drive = new DriveInformation();
                        drive = drive.GetDriveInformation(backupDriveSerialNumber);
                        string message = $"Nicht genug Speicherplatz auf {drive.DeviceID} mit Seriennummer {drive.VolumeSerialNumber}.";

                        WriteLog(logFile, message, false);
                        Console.WriteLine(message);
                    }
                }

                //Starten der Sicherung

                //Anlegen der Ordner

                DirectoryInfo destination = new DirectoryInfo($"{backupDrive}\\WindowsBackupManager\\" + DateTime.Today.ToShortDateString().Replace(".", ""));
                DirectoryInfo source      = new DirectoryInfo($"{backupDrive}\\WindowsImageBackup");
                if (!destination.Exists)
                {
                    destination.Create();
                }

                if (systemDrives != "" && backupDrive != "")
                {
                    //Letztes Komma von Sytemdrives entfernen
                    systemDrives = systemDrives.Substring(0, systemDrives.Length - 1);

                    //Benötigen Festplattenspeicher berechnen

                    try
                    {
                        string message = "Starten der Sicherung";
                        WriteLog(logFile, message, true);
                        Console.WriteLine(message);

                        StartWindowsBackup(systemDrives, backupDrive);

                        //Überprüfen der Backup Log Dateien von WBAdmin

                        //Überprüfen ob WindowsBackupOrdner existiert

                        DirectoryInfo logFolder = new DirectoryInfo(backupLogFolder);

                        if (logFolder.Exists == true)
                        {
                            List <FileInfo> backupLogs = new List <FileInfo>();

                            foreach (FileInfo file in logFolder.GetFiles())
                            {
                                if (file.CreationTime.ToShortDateString() == DateTime.Today.ToShortDateString())
                                {
                                    string[] logFileText = File.ReadAllText(file.FullName).Split('\n');
                                    string   ergLog      = "";
                                    foreach (string text in logFileText)
                                    {
                                        if (text.Length > 1)
                                        {
                                            ergLog += $"{text}\n";

                                            //Überprüfen ob Sicherung erfolgreich

                                            if (text.Contains("wurde erfolgreich gesichert.") == false)
                                            {
                                                isBackupSuccess = false;
                                            }
                                        }
                                    }

                                    WriteLog(logFile, ergLog.Trim(), isBackupSuccess);
                                    Console.WriteLine(ergLog.Trim());
                                }
                            }

                            //Inhalt der Logdateien auswerten.
                        }
                        else
                        {
                            message = $"Der Ordner{backupLogFolder} konnte nicht gefunden werden.";

                            WriteLog(logFile, message, false);
                            Console.WriteLine(message);
                        }

                        //Verschieben der Sicherung in Ordner WindowsBackupManager

                        Directory.Move(source.FullName, destination.FullName + "\\WindowsImageBackup");


                        BackupSuccess(backupSuccessLog, isBackupSuccess);



                        WriteLog(logFile, $"Backup in Ordner {destination.FullName} verschoben", true);
                    }

                    catch (System.IO.IOException)
                    {
                        string message = $"Der Zugriff auf den Pfad {backupDrive}\\WindowsImageBackup wurde verweigert.";

                        isBackupSuccess = false;

                        BackupSuccess(backupSuccessLog, isBackupSuccess);

                        WriteLog(logFile, message, false);
                        Console.WriteLine(message);
                    }
                    catch (Exception)
                    {
                        string message = "Es ist ein Fehler aufgetreten :( Möglicherweise wurde das Programm ohne Adminrechte gestartet";
                        WriteLog(logFile, message, false);
                        Console.WriteLine(logFile, message);
                    }
                }
                else
                {
                    if (systemDrives == "")
                    {
                        isBackupSuccess = false;
                        Console.WriteLine("Es wurde kein zu sicherndes Laufwerk gefunden.");
                        WriteLog(logFile, "Es wurde kein zu sicherndes Laufwerk gefunden.", false);
                        BackupSuccess(backupSuccessLog, isBackupSuccess);
                    }
                    else if (backupDrive == "")
                    {
                        isBackupSuccess = false;
                        Console.WriteLine("Es wurde kein passendes Sicherungslaufwerk gefunden.");
                        WriteLog(logFile, "Es wurde kein passendes Sicherungslaufwerk gefunden.", false);
                        BackupSuccess(backupSuccessLog, isBackupSuccess);
                    }
                }

                //Mail Einstellungen Einlesen

                if (File.Exists(xmlUserdataMail))
                {
                    XmlSerializer xml       = new XmlSerializer(typeof(XML_Mail));
                    FileStream    xmlReader = new FileStream(xmlUserdataMail, FileMode.Open, FileAccess.Read, FileShare.Read);

                    XML_Mail datenMail = (XML_Mail)xml.Deserialize(xmlReader);


                    try
                    {
                        NetworkCredential login = new NetworkCredential(datenMail.Username, datenMail.Password);

                        foreach (string empfaenger in datenMail.empfaenger)
                        {
                            //LogFile verschieben

                            string   newLogFilePath = $"{backupDrive}\\WindowsBackupManager\\" + DateTime.Today.ToShortDateString().Replace(".", "") + "\\log.txt";
                            FileInfo logFileInfo    = new FileInfo(logFile);

                            if (File.Exists(newLogFilePath))
                            {
                                File.AppendAllText(newLogFilePath, File.ReadAllText(logFile));

                                File.Delete(logFile);

                                logFile = newLogFilePath;
                            }
                            else
                            {
                                logFileInfo.MoveTo(newLogFilePath);
                            }

                            logFile = newLogFilePath;

                            string message = $"Logfile nach {logFileInfo.FullName} verschoben";
                            WriteLog(logFile, message, true);
                            Console.WriteLine();

                            MailMessage msg = new MailMessage(datenMail.Absender, empfaenger, "Windows Backup Manager " + Environment.MachineName, File.ReadAllText(logFile));
                            msg.BodyEncoding    = Encoding.UTF8;
                            msg.SubjectEncoding = Encoding.UTF8;
                            msg.IsBodyHtml      = false;

                            SmtpClient client = new SmtpClient(datenMail.Smtp);
                            client.Credentials = login;
                            client.EnableSsl   = true;
                            client.Send(msg);

                            message = "E-Mail wurde versandt";

                            Console.WriteLine(message);
                        }
                    }
                    catch (Exception)
                    {
                        string message = "Fehler beim versenden der E-Mail";
                        WriteLog(logFile, message, false);
                        Console.WriteLine(message);
                    }
                }
            }

            #endregion
            //Nach Sicherung evtl herunterfahren
            try
            {
                if (File.Exists(xmlUserdataSchedule))
                {
                    XmlSerializer xs   = new XmlSerializer(typeof(XML_Schedule));
                    FileStream    read = new FileStream(xmlUserdataSchedule, FileMode.Open, FileAccess.Read, FileShare.Read);

                    XML_Schedule datenSchedule = (XML_Schedule)xs.Deserialize(read);

                    if (datenSchedule.IsShutdown)
                    {
                        string message = $"PC herunterfahren";
                        Console.WriteLine(message);

                        Process.Start("shutdown.exe", "-s -t 60");

                        WriteLog(logFile, message, true);
                    }
                }
            }
            catch (Exception)
            {
                string message = $"Pc konnte nicht heruntergefahren werden";
                Console.WriteLine(message);

                WriteLog(logFile, message, false);
            }

            Console.WriteLine("PROGRAMM ENDE");


            //Konsole offen lassen.
            System.Threading.Thread.Sleep(5000);
        }
Exemplo n.º 22
0
 public IPayload <DriveInformation> CreateServerBitLockerLockRequest(DriveInformation drive) => new ServerBitLockerLockRequest(drive);
Exemplo n.º 23
0
 public BitLockerControlEventArgs(IDevice device, DriveInformation drive, bool @lock, string password) : this(device, drive, @lock)
 {
     Password = password;
 }
Exemplo n.º 24
0
 public BitLockerControlEventArgs(IDevice device, DriveInformation drive, bool @lock)
 {
     Device = device;
     Drive  = drive;
     Lock   = @lock;
 }
Exemplo n.º 25
0
        public List <DriveInformation> GetDriveInformation()
        {
            var wdSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

            // extract model and interface information
            var iDriveIndex = 0;
            var driveList   = new List <DriveInformation>();
            var di          = DriveInfo.GetDrives();

            foreach (var o in wdSearcher.Get())
            {
                var driveInfo = new DriveInformation();
                var drive     = (ManagementObject)o;
                var type      = drive["InterfaceType"].ToString().Trim();
                var model     = drive["Model"].ToString().Trim();
                if (type.Equals("IDE"))
                {
                    Console.WriteLine(model);
                    var driveData = di[iDriveIndex];
                    driveInfo.Model         = model;
                    driveInfo.Name          = driveData.Name;
                    driveInfo.FreeSpace     = driveData.TotalFreeSpace;
                    driveInfo.TotalSize     = driveData.TotalSize;
                    driveInfo.DriveType     = driveData.DriveType.ToString();
                    driveInfo.DriveFormat   = driveData.DriveFormat;
                    driveInfo.VolumeLabel   = driveData.VolumeLabel;
                    driveInfo.RootDirectory = driveData.RootDirectory.ToString();
                    driveInfo.IsReady       = driveData.IsReady;
                    driveInfo.SmartInfo     = new Disk
                    {
                        Model = driveInfo.Model,
                        Type  = type
                    };
                    driveList.Add(driveInfo);
                    iDriveIndex++;
                }
            }
            var pmsearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");

            // retrieve hdd serial number
            iDriveIndex = 0;
            foreach (var o in pmsearcher.Get())
            {
                var drive = (ManagementObject)o;
                // because all physical media will be returned we need to exit
                // after the hard drives serial info is extracted
                if (iDriveIndex >= driveList.Count)
                {
                    break;
                }
                driveList[iDriveIndex].SmartInfo.Serial = drive["SerialNumber"]?.ToString().Trim() ?? "None";
                iDriveIndex++;
            }
            var searcher = new ManagementObjectSearcher("Select * from Win32_DiskDrive")
            {
                Scope = new ManagementScope(@"\root\wmi"),
                Query = new ObjectQuery("Select * from MSStorageDriver_FailurePredictStatus")
            };

            // check if SMART reports the drive is failing
            iDriveIndex = 0;
            foreach (var o in searcher.Get())
            {
                var drive = (ManagementObject)o;
                driveList[iDriveIndex].SmartInfo.IsOk = (bool)drive.Properties["PredictFailure"].Value == false;
                iDriveIndex++;
            }
            searcher.Query = new ObjectQuery("Select * from MSStorageDriver_FailurePredictData");
            iDriveIndex    = 0;
            foreach (var o in searcher.Get())
            {
                var data  = (ManagementObject)o;
                var bytes = (byte[])data.Properties["VendorSpecific"].Value;
                for (var i = 0; i < 30; ++i)
                {
                    try
                    {
                        int id = bytes[i * 12 + 2];

                        int flags           = bytes[i * 12 + 4];
                        var failureImminent = (flags & 0x1) == 0x1;
                        int value           = bytes[i * 12 + 5];
                        int worst           = bytes[i * 12 + 6];
                        var vendordata      = BitConverter.ToInt32(bytes, i * 12 + 7);
                        if (id == 0)
                        {
                            continue;
                        }

                        var attr = driveList[iDriveIndex].SmartInfo.Attributes[id];
                        attr.Current = value;
                        attr.Worst   = worst;
                        attr.Data    = vendordata;
                        attr.IsOk    = failureImminent == false;
                    }
                    catch
                    {
                        // ignored
                    }
                }
                iDriveIndex++;
            }
            searcher.Query = new ObjectQuery("Select * from MSStorageDriver_FailurePredictThresholds");
            iDriveIndex    = 0;
            foreach (var o in searcher.Get())
            {
                var data  = (ManagementObject)o;
                var bytes = (byte[])data.Properties["VendorSpecific"].Value;
                for (var i = 0; i < 30; ++i)
                {
                    try
                    {
                        int id     = bytes[i * 12 + 2];
                        int thresh = bytes[i * 12 + 3];
                        if (id == 0)
                        {
                            continue;
                        }

                        var attr = driveList[iDriveIndex].SmartInfo.Attributes[id];
                        attr.Threshold = thresh;
                    }
                    catch
                    {
                        // ignored
                    }
                }

                iDriveIndex++;
            }
            return(driveList);
        }
Exemplo n.º 26
0
 public ServerBitLockerUnlockRequest(DriveInformation drive, string password, CryptoProvider cryptor) : base(PacketType.ServerBitLockerUnlockRequest)
 {
     Payload      = new ServerBitLockerUnlock(drive, password, cryptor);
     this.cryptor = cryptor;
 }