Пример #1
0
        public static bool DownloadFromFtp(string fileName)
        {
            bool ret = true;
            var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string path = Path.Combine(dirName, fileName);
            try
            {

                var wc = new WebClient { Credentials = new NetworkCredential("solidk", "KSolid") };
                var fileStream = new FileInfo(path).Create();
                //string downloadPath = Path.Combine("ftp://194.84.146.5/ForDealers",fileName);
                string downloadPath = Path.Combine(Furniture.Helpers.FtpAccess.resultFtp+"ForDealers", fileName);
                var str = wc.OpenRead(downloadPath);

                const int bufferSize = 1024;
                var buffer = new byte[bufferSize];
                int readCount = str.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    fileStream.Write(buffer, 0, readCount);
                    readCount = str.Read(buffer, 0, bufferSize);
                }
                str.Close();
                fileStream.Close();
                wc.Dispose();
            }
            catch
            {
                ret = false;
            }
            return ret;
        }
Пример #2
0
        public IList<ISubtitleResult> Find(ISubtitleRequest request)
        {
            var url = _urlBuilder.BuildUrl(request.MovieName);
            var resultPage = _webpageDownloader.Download(url);

            var possibleResults = _resultExtractor.ExtractResultUrl(resultPage);

            // At the moment, if we don't have exactly one result, we give up (we'll improve that later)
            if (possibleResults.Count != 1)
                return new List<ISubtitleResult>();

            var secondResultPageUrl = "http://www.addic7ed.com/" + possibleResults[0];
            var secondResultPage = _webpageDownloader.Download(secondResultPageUrl);

            var results = _resultExtractor.ExtractSubtitleRecords(secondResultPage);

            foreach (var addictedSubtitle in results)
            {
                WebClient client = new WebClient();
                client.Headers.Add("Referer", secondResultPageUrl);

                var subtitle = client.DownloadString("http://www.addic7ed.com" + addictedSubtitle.DownloadLink);
                //var subtitle = _webpageDownloader.Download();

                using (var writer = new FileInfo(string.Format("c:\\out\\{0}.{1}.srt", request.MovieName, addictedSubtitle.Language)).CreateText())
                {
                    writer.Write(subtitle);
                }
            }

            return new List<ISubtitleResult>();
        }
Пример #3
0
		public static void Create ( string fullPath, string data )
		{
			MakeDirectory (fullPath);

			using (FileStream fs = new FileInfo(fullPath).Open(FileMode.Create, FileAccess.ReadWrite)) 
			{

				byte[] byteData = System.Text.Encoding.ASCII.GetBytes(data);

				fs.Write(byteData, 0, byteData.Length);

			}
		}
        /// <summary>
        /// Saves this instance.
        /// </summary>
        public void Save()
        {
            Plugins.ForEach(x => x.Save());
            string FileLocation = HttpContext.Current != null?HttpContext.Current.Server.MapPath("~/App_Data/PluginList.txt") : AppDomain.CurrentDomain.BaseDirectory + "/App_Data/PluginList.txt";

            string DirectoryLocation = HttpContext.Current != null?HttpContext.Current.Server.MapPath("~/App_Data/") : AppDomain.CurrentDomain.BaseDirectory + "/App_Data/";

            new System.IO.DirectoryInfo(DirectoryLocation).Create();
            using (FileStream Writer = new System.IO.FileInfo(FileLocation).Open(FileMode.Create, FileAccess.Write))
            {
                byte[] Content = Serialize(this).ToByteArray();
                Writer.Write(Content, 0, Content.Length);
            }
        }
Пример #5
0
 private void cmdSave_Click(object sender, EventArgs e)
 {
     StreamWriter sw = new FileInfo(_installPath+"\\"+cboFile.Text).CreateText();
     sw.Write(txtLST.Text);
     sw.Close();
 }
Пример #6
0
 private void saveMsgtolocal()
 {
     FileStream stream = new FileInfo(this.sMsgFile).Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
     string s = DateTime.Now.ToString() + " " + base.txtCarNo.Text.Trim() + " : " + this.txtMsgValue.Text.Trim() + "\r\n";
     byte[] bytes = Encoding.Default.GetBytes(s);
     stream.Write(bytes, 0, bytes.Length);
     stream.Flush();
     stream.Close();
 }
        /* Metodo que se encarga de la creacion del Web.Config */
        private bool createWebConfig()
        {
            try
            {
                /* Variable para almacenar el nombre del archivo de configuracion */
                string fileNameConfig = String.Empty;

                /* Verifica si un archivo existe en el proyecyo y con que nombre aparece */
                if(startupProject.IsFileInProject(projectPath + Path.DirectorySeparatorChar + "web.config"))
                    fileNameConfig = "web.config";
                else if(startupProject.IsFileInProject(projectPath + Path.DirectorySeparatorChar + "Web.config"))
                    fileNameConfig = "Web.config";
                /* El archivo no existe y por lo tanto lo creamos */
                else
                {
                    fileNameConfig = "web.config";
                    MonoDevelop.Projects.Text.TextFile.WriteFile(projectPath + Path.DirectorySeparatorChar + fileNameConfig, "", "UTF-8", true);
                    startupProject.AddFile(projectPath + Path.DirectorySeparatorChar + fileNameConfig);

                    FileInfo fiTemplate = new FileInfo(myNode.Addin.GetFilePath("web.config.template"));
                    byte [] arrayByte = new byte[fiTemplate.Length];

                    FileStream fsTemplate = fiTemplate.OpenRead();
                    FileStream fsWebConfig = new FileInfo(projectPath + Path.DirectorySeparatorChar + fileNameConfig).OpenWrite();

                    int byteLeidos = fsTemplate.Read(arrayByte, 0, arrayByte.Length);
                    fsWebConfig.Write(arrayByte, 0, byteLeidos);

                    fsTemplate.Close();
                    fsWebConfig.Close();

                    startupProject.Save(null);
                }

                webConfigPath = projectPath + Path.DirectorySeparatorChar + fileNameConfig;
                return true;
            }
            catch(Exception ex)
            {
                MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Error: " + ex.Message);
               	md.Run();
               	md.Destroy();
                return false;
            }
        }
Пример #8
0
        static unsafe void ConvertPOM( FileInfo _Source, FileInfo _Target, bool _sRGB, bool _GenerateMipMaps )
        {
            int	Width, Height;
            int	MipLevelsCount = 1;
            byte[][]	RAWImages = null;
            using ( Bitmap B = Image.FromFile( _Source.FullName ) as Bitmap )
            {
                if ( _GenerateMipMaps )
                {
                    double	Mips = Math.Log( 1+Math.Max( B.Width, B.Height ) ) / Math.Log( 2.0 );
                    MipLevelsCount = (int) Math.Ceiling( Mips );
                }

                RAWImages = new byte[MipLevelsCount][];

                Width = B.Width;
                Height = B.Height;

                // Build mip #0
                byte[]	RAWImage = new byte[4*Width*Height];
                RAWImages[0] = RAWImage;

                BitmapData	LockedBitmap = B.LockBits( new Rectangle( 0, 0, Width, Height ), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb );

                int			ByteIndex = 0;
                for ( int Y=0; Y < Height; Y++ )
                {
                    byte*	pScanline = (byte*) LockedBitmap.Scan0.ToPointer() + Y * LockedBitmap.Stride;
                    for ( int X=0; X < Width; X++ )
                    {
                        RAWImage[ByteIndex+2] = *pScanline++;
                        RAWImage[ByteIndex+1] = *pScanline++;
                        RAWImage[ByteIndex+0] = *pScanline++;
                        RAWImage[ByteIndex+3] = *pScanline++;
                        ByteIndex += 4;
                    }
                }

                B.UnlockBits( LockedBitmap );
            }

            // Generate other mips
            int	W = Width;
            int	H = Height;

            for ( int MipLevelIndex=1; MipLevelIndex < MipLevelsCount; MipLevelIndex++ )
            {
                int	PW = W;
                int	PH = W;
                W = Math.Max( 1, W >> 1 );
                H = Math.Max( 1, H >> 1 );

                byte[]	PreviousMip = RAWImages[MipLevelIndex-1];
                byte[]	CurrentMip = new byte[4*W*H];
                RAWImages[MipLevelIndex] = CurrentMip;

                byte	R, G, B, A;
                for ( int Y=0; Y < H; Y++ )
                {
                    int	PY0 = PH * Y / H;
                    int	PY1 = Math.Min( PY0+1, PH-1 );
                    for ( int X=0; X < W; X++ )
                    {
                        int	PX0 = PW * X / W;
                        int	PX1 = Math.Min( PX0+1, PW-1 );

                        if ( _sRGB )
                        {
                            R = Lin2sRGB( 0.25f * (sRGB2Lin( PreviousMip[4*(PW*PY0+PX0)+0] ) + sRGB2Lin( PreviousMip[4*(PW*PY0+PX1)+0] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX0)+0] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX1)+0]) ) );
                            G = Lin2sRGB( 0.25f * (sRGB2Lin( PreviousMip[4*(PW*PY0+PX0)+1] ) + sRGB2Lin( PreviousMip[4*(PW*PY0+PX1)+1] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX0)+1] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX1)+1]) ) );
                            B = Lin2sRGB( 0.25f * (sRGB2Lin( PreviousMip[4*(PW*PY0+PX0)+2] ) + sRGB2Lin( PreviousMip[4*(PW*PY0+PX1)+2] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX0)+2] ) + sRGB2Lin( PreviousMip[4*(PW*PY1+PX1)+2]) ) );
                        }
                        else
                        {	// Simple average will do. I should handle normal maps mip-mapping more seriously but I just don't care...
                            R = (byte) ((PreviousMip[4*(PW*PY0+PX0)+0] + PreviousMip[4*(PW*PY0+PX1)+0] + PreviousMip[4*(PW*PY1+PX0)+0] + PreviousMip[4*(PW*PY1+PX1)+0]) >> 2);
                            G = (byte) ((PreviousMip[4*(PW*PY0+PX0)+1] + PreviousMip[4*(PW*PY0+PX1)+1] + PreviousMip[4*(PW*PY1+PX0)+1] + PreviousMip[4*(PW*PY1+PX1)+1]) >> 2);
                            B = (byte) ((PreviousMip[4*(PW*PY0+PX0)+2] + PreviousMip[4*(PW*PY0+PX1)+2] + PreviousMip[4*(PW*PY1+PX0)+2] + PreviousMip[4*(PW*PY1+PX1)+2]) >> 2);
                        }

                        A = (byte) ((PreviousMip[4*(PW*PY0+PX0)+3] + PreviousMip[4*(PW*PY0+PX1)+3] + PreviousMip[4*(PW*PY1+PX0)+3] + PreviousMip[4*(PW*PY1+PX1)+3]) >> 2);

                        CurrentMip[4*(W*Y+X)+0] = R;
                        CurrentMip[4*(W*Y+X)+1] = G;
                        CurrentMip[4*(W*Y+X)+2] = B;
                        CurrentMip[4*(W*Y+X)+3] = A;
                    }
                }
            }

            // Write the file
            using ( FileStream S = new FileInfo( _Target.FullName ).Create() )
                using ( BinaryWriter BW = new BinaryWriter( S ) )
                {
                    // Write type & format
                    BW.Write( (byte) 0 );	// 2D
                    BW.Write( (byte) (28 + (_sRGB ? 1 : 0)) );		// DXGI_FORMAT_R8G8B8A8_UNORM=28, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB=29

                    // Write dimensions
                    BW.Write( (Int32) Width );
                    BW.Write( (Int32) Height );
                    BW.Write( (Int32) 1 );				// ArraySize = 1
                    BW.Write( (Int32) MipLevelsCount );

                    W = Width;
                    H = Height;

                    for ( int MipLevelIndex=0; MipLevelIndex < MipLevelsCount; MipLevelIndex++ )
                    {
                        // Write row & depth pitch
                        BW.Write( (Int32) (W * 4) );
                        BW.Write( (Int32) RAWImages[MipLevelIndex].Length );

                        // Write content
                        S.Write( RAWImages[MipLevelIndex], 0, RAWImages[MipLevelIndex].Length );

                        W = Math.Max( 1, W >> 1 );
                        H = Math.Max( 1, H >> 1 );
                    }
                }
        }
Пример #9
0
 public bool SaveScript()
 {
     if (CurrentScript != null) {
         CurrentScript.Write(scriptBox1.Editor.Document.Text);
     }
     else {
         saveFileDialog1.FileName = string.Empty;
         saveFileDialog1.InitialDirectory = Path.Combine(Application.StartupPath, "MyScripts");
         saveFileDialog1.ShowDialog();
         if (saveFileDialog1.FileName != string.Empty) {
             CurrentScript = new FileInfo(saveFileDialog1.FileName);
             CurrentScript.Write(scriptBox1.Editor.Document.Text);
         }
         else { SetStatusText("Save operation canceled by user!"); return false; }
     }
     this.Text = string.Concat("CaveBot - ", CurrentScript.Name);
     btnSave.Enabled = false;
     SetStatusText("Script saved!");
     scriptBox1.Editor.Document.SaveRevisionMark();
     scriptBox1.Editor.Update();
     return true;
 }
Пример #10
0
 /// <summary>
 /// Saves the address.
 /// </summary>
 /// <param name="address">The address.</param>
 public static void SaveAddress(AddressDTOCollection address)
 {
     var fi = new FileInfo(AddressFilePath);
     if (fi.Exists) { fi.Delete(); }
     fi.Write(address.Serialize());
 }
        /// <summary>
        /// Sets a value in the specified key of the specified section within the ini file's contents.
        /// </summary>
        /// <param name="section">Ini file section</param>
        /// <param name="key">Ini file section key</param>
        /// <param name="value">Key value to assign</param>
        /// <returns>True if value assignment has been successful otherwise false.</returns>
        public bool SetValue(string section, string key, string value)
        {
            bool _set = false;
            if (String.IsNullOrEmpty(_filecontents.RLTrim())) _filecontents = Contents();

            if (!String.IsNullOrEmpty(_filecontents.RLTrim()))
            {
                string[] _lines = _filecontents.Split("\n".ToCharArray());
                int _startline = 0; int _endline = 0;

                for (int i = 0; i <= (_lines.Length - 1); i++)
                {
                    string _line = _lines[i];
                    if (_line.RLTrim().ToUpper() == "[" + section.ToUpper() + "]")
                    {
                        _startline = i; break;
                    }
                }

                if ((_startline + 1) <= (_lines.Length - 1))
                {

                    for (int i = (_startline + 1); i <= (_lines.Length - 1); i++)
                    {
                        string _line = _lines[i];
                        if (_line.RLTrim().StartsWith("[") &&
                            _line.RLTrim().EndsWith("]")) break;
                        _endline = i;
                    }

                    for (int i = _startline; i <= _endline; i++)
                    {
                        string _line = _lines[i];
                        char[] _chars = _line.ToCharArray();
                        string _key = "";

                        foreach (char _char in _chars)
                        {
                            if (_char.ToString() != " ") _key += _char.ToString();
                            if (_key.RLTrim().ToUpper().Contains(key.ToUpper() + "="))
                            {
                                _lines[i] = key.ToUpper() + "=" + value;
                                StreamWriter _writer = new StreamWriter(_filename);
                                try
                                {
                                    for (int a = 0; a <= (_lines.Length - 1); a++)
                                    { _writer.WriteLine(_lines[a]); }
                                    _set = true;
                                }
                                catch { _set = false; }
                                finally
                                { _writer.Close(); _writer.Dispose(); Materia.RefreshAndManageCurrentProcess(); }

                                return _set;
                            }
                        }

                        StringBuilder _contents = new StringBuilder();
                        _contents.Append(_filecontents);

                        if (_endline < (_lines.Length - 1)) _filecontents.RLTrim().Replace(_lines[_endline], _lines[_endline] + "\n" + key + "=" + value);
                        else _filecontents += (_filecontents.RLTrim().EndsWith("\n") ? "" : "\n") + key + "=" + value;

                        FileInfo _file = new FileInfo(_filename);
                        _set = _file.Write(_filecontents);
                    }
                }
            }

            return _set;
        }
Пример #12
0
        private bool DownloadDll(Stream stream, FtpWebRequest reqFtp, string newVersion, string newName, out string newFileLocation)
        {
            if (Directory.Exists(Furniture.Helpers.LocalAccounts.modelPathResult.Replace("_SWLIB_", "_SWLIB_BACKUP")))
            {
                string warnMessage =
                    @"�������� ���� �������� ! � ������ ������ ��� �������������� ������� ������� ��������� ������, ��������� ������� � ��������� ����������� ������ ����� ���� ��� ! � ������ ������� �������������� ������� (���� ����\��������)�������� ����������� ������ � �� ����������� ���������,���������� � ��������� ������������ ������� �� ������������ � ��������� ������������ ������� ����������.";
                MessageBox.Show(warnMessage, "��������!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            stream.Close();
            reqFtp.Abort();
            //long size = GetSizeForFurnitureDll(Properties.Settings.Default.FurnFtpPath + newVersion);
            long size = GetSizeForFurnitureDll(Furniture.Helpers.FtpAccess.resultFtp + newVersion);
            UserProgressBar pb;
            SwApp.GetUserProgressBar(out pb);
            FileStream fileStream = null;
            try
            {
                fileStream = new FileInfo(newName).Create();
            }
            catch (Exception)
            {
                MessageBox.Show("�� �������� ������� ���� " + newName + "�������� ��-�� ���� ��� ��� ��� ���� ����� �������.");
            }

            var wc = new WebClient { Credentials = new NetworkCredential(Properties.Settings.Default.FurnFtpName, Properties.Settings.Default.FurnFtpPass) };
            var str =
                //wc.OpenRead(Properties.Settings.Default.FurnFtpPath + newVersion + "/Furniture.dll");
                wc.OpenRead(Furniture.Helpers.FtpAccess.resultFtp + newVersion + "/Furniture.dll");
            const int bufferSize = 1024;
            var z = (int)(size / bufferSize);
            var buffer = new byte[bufferSize];
            int readCount = str.Read(buffer, 0, bufferSize);
            pb.Start(0, z, "���������� ���������");
            int i = 0;
            while (readCount > 0)
            {
                fileStream.Write(buffer, 0, readCount);
                readCount = str.Read(buffer, 0, bufferSize);
                pb.UpdateProgress(i);
                i++;
            }
            pb.End();
            fileStream.Close();
            wc.Dispose();
            newFileLocation = newName;
            return true;
        }
Пример #13
0
        private static bool DownloadUpdFrn(out string path)
        {
            bool ret = true;
            path = "";
            try
            {
                path = Directory.Exists(@"D:\") ? @"D:\download_update_furniture.exe" : @"C:\download_update_furniture.exe";
                string pathUpd = Directory.Exists(@"D:\") ? @"D:\update_furniture.exe" : @"C:\update_furniture.exe";
                if (File.Exists(path) && File.Exists(pathUpd))
                    return true;
                var wc = new WebClient { Credentials = new NetworkCredential("solidk", "KSolid") };
                var fileStream = new FileInfo(path).Create();

                //var str = wc.OpenRead("ftp://194.84.146.5/download_update_furniture.exe");
                var str = wc.OpenRead(Furniture.Helpers.FtpAccess.resultFtp + "download_update_furniture.exe");

                const int bufferSize = 1024;
                var buffer = new byte[bufferSize];
                int readCount = str.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    fileStream.Write(buffer, 0, readCount);
                    readCount = str.Read(buffer, 0, bufferSize);
                }
                str.Close();
                fileStream.Close();
                fileStream = new FileInfo(pathUpd).Create();
                //str = wc.OpenRead("ftp://194.84.146.5/update_furniture.exe");
                str = wc.OpenRead(Furniture.Helpers.FtpAccess.resultFtp + "update_furniture.exe");

                readCount = str.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    fileStream.Write(buffer, 0, readCount);
                    readCount = str.Read(buffer, 0, bufferSize);
                }
                str.Close();
                fileStream.Close();
                wc.Dispose();
            }
            catch
            {
                ret = false;
            }
            return ret;
        }
Пример #14
0
 public void SaveScript()
 {
     if (CurrentScript != null) {
         CurrentScript.Write(scriptBox1.Editor.Document.Text);
     }
     else {
         saveFileDialog1.FileName = string.Empty;
         saveFileDialog1.ShowDialog();
         if (saveFileDialog1.FileName != string.Empty) {
             CurrentScript = new FileInfo(saveFileDialog1.FileName);
             CurrentScript.Write(scriptBox1.Editor.Document.Text);
         }
         else { return; }
     }
     this.Text = CurrentScript.Name;
     btnSave.Enabled = false;
     SetStatusText("Script saved!");
     scriptBox1.Editor.Document.SaveRevisionMark();
     scriptBox1.Editor.Update();
 }
Пример #15
0
        void menuTest_Click(object sender, EventArgs e)
        {
            if (_config.ConfirmTest)
            {
                DialogResult res = new TestDialog(_config).ShowDialog();
                if (res == DialogResult.Cancel) return;
            }
            // prep stuff
            menuSave_Click("menuTest_Click", new EventArgs());
            if (_config.VerifyTest && !_config.Verify) Common.RunVerify(_mission.MissionPath, _config.VerifyLocation);
            /*Version os = Environment.OSVersion.Version;
            bool isWin7 = (os.Major == 6 && os.Minor == 1);
            System.Diagnostics.Process explorer = null;
            int restart = 1;
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", true);*/

            // configure XvT/BoP
            int index = 0;
            string path = (_mission.IsBop ? _config.BopPath : _config.XvtPath);
            while (File.Exists(path + "\\test" + index + "0.plt")) index++;
            string pilot = "\\test" + index + "0.plt";
            string bopPilot = "\\test" + index + "0.pl2";
            string lst = "\\Train\\IMPERIAL.LST";
            string backup = "\\Train\\IMPERIAL_" + index + ".bak";

            File.Copy(Application.StartupPath + "\\xvttest0.plt", _config.XvtPath + pilot);
            if (_config.BopInstalled) File.Copy(Application.StartupPath + "\\xvttest0.pl2", _config.BopPath + bopPilot, true);
            // XvT pilot edit
            FileStream pilotFile = File.OpenWrite(_config.XvtPath + pilot);
            pilotFile.Position = 4;
            char[] indexBytes = index.ToString().ToCharArray();
            new BinaryWriter(pilotFile).Write(indexBytes);
            for (int i = (int)pilotFile.Position; i < 0xC; i++) pilotFile.WriteByte(0);
            pilotFile.Close();
            // BoP pilot edit
            if (_config.BopInstalled)
            {
                pilotFile = File.OpenWrite(_config.BopPath + bopPilot);
                pilotFile.Position = 4;
                indexBytes = index.ToString().ToCharArray();
                new BinaryWriter(pilotFile).Write(indexBytes);
                for (int i = (int)pilotFile.Position; i < 0xC; i++) pilotFile.WriteByte(0);
                pilotFile.Close();
            }

            // configure XvT
            System.Diagnostics.Process xvt = new System.Diagnostics.Process();
            xvt.StartInfo.FileName = path + "\\Z_XVT__.exe";
            xvt.StartInfo.Arguments = "/skipintro";
            xvt.StartInfo.UseShellExecute = false;
            xvt.StartInfo.WorkingDirectory = path;
            File.Copy(path + lst, path + backup, true);
            StreamReader sr = File.OpenText(_config.XvtPath + "\\Config.cfg");
            string contents = sr.ReadToEnd();
            sr.Close();
            int lastpilot = contents.IndexOf("lastpilot ") + 10;
            int nextline = contents.IndexOf("\r\n", lastpilot);
            string modified = contents.Substring(0, lastpilot) + "test" + index + contents.Substring(nextline);
            StreamWriter sw = new FileInfo(_config.XvtPath + "\\Config.cfg").CreateText();
            sw.Write(modified);
            sw.Close();
            if (_config.BopInstalled)
            {
                sr = File.OpenText(_config.BopPath + "\\config2.cfg");
                contents = sr.ReadToEnd();
                sr.Close();
                lastpilot = contents.IndexOf("lastpilot ") + 10;
                nextline = contents.IndexOf("\r\n", lastpilot);
                modified = contents.Substring(0, lastpilot) + "test" + index + contents.Substring(nextline);
                sw = new FileInfo(_config.BopPath + "\\config2.cfg").CreateText();
                sw.Write(modified);
                sw.Close();
            }
            sr = File.OpenText(path + lst);
            contents = sr.ReadToEnd();
            sr.Close();
            string[] expanded = contents.Replace("\r\n", "\0").Split('\0');
            expanded[4] = _mission.MissionFileName;
            expanded[5] = "YOGEME: " + expanded[4];
            modified = String.Join("\r\n", expanded);
            sw = new FileInfo(path + lst).CreateText();
            sw.Write(modified);
            sw.Close();

            /*if (isWin7)	// explorer kill so colors work right
            {
                restart = (int)key.GetValue("AutoRestartShell", 1);
                key.SetValue("AutoRestartShell", 0, Microsoft.Win32.RegistryValueKind.DWord);
                explorer = System.Diagnostics.Process.GetProcessesByName("explorer")[0];
                explorer.Kill();
                explorer.WaitForExit();
            }*/

            xvt.Start();
            System.Threading.Thread.Sleep(1000);
            System.Diagnostics.Process[] runningXvts = System.Diagnostics.Process.GetProcessesByName("Z_XVT__");
            while (runningXvts.Length > 0)
            {
                Application.DoEvents();
                System.Diagnostics.Debug.WriteLine("sleeping...");
                System.Threading.Thread.Sleep(1000);
                runningXvts = System.Diagnostics.Process.GetProcessesByName("Z_XVT__");
            }

            /*if (isWin7)	// restart
            {
                key.SetValue("AutoRestartShell", restart, Microsoft.Win32.RegistryValueKind.DWord);
                explorer.StartInfo.UseShellExecute = false;
                explorer.StartInfo.FileName = "explorer.exe";
                explorer.Start();
            }*/
            if (_config.DeleteTestPilots)
            {
                File.Delete(_config.XvtPath + pilot);
                File.Delete(_config.BopPath + bopPilot);
            }
            File.Copy(path + backup, path + lst, true);
            File.Delete(path + backup);
        }
Пример #16
0
        /// <summary>
        /// Creates a temporal executable of Skindle from the embedded resource
        /// </summary>
        /// <param name="skindleEXEStream">Skindle's stream</param>
        private void WriteTemporalSkindleExecutable(Stream skindleEXEStream)
        {
            var outputStream = new FileInfo(_skindlePath).OpenWrite();

            // read from embedded resource and write to output file
            const int size = 4096;
            byte[] bytes = new byte[4096];
            int numBytes;
            while ((numBytes = skindleEXEStream.Read(bytes, 0, size)) > 0)
            {
                outputStream.Write(bytes, 0, numBytes);
            }
            outputStream.Close();
            skindleEXEStream.Close();
        }
Пример #17
0
        private void Downloading(WebClient wc, string neededLibrary, long sz)
        {
            if (!Directory.Exists(_mainDir.Root + "MrDoors_Solid_Update"))
                Directory.CreateDirectory(_mainDir.Root + "MrDoors_Solid_Update");
            string fullDownloadingPath = _mainDir.Root + "MrDoors_Solid_Update\\" + neededLibrary;
            if (File.Exists(fullDownloadingPath))
            {
                if (new FileInfo(fullDownloadingPath).Length == sz)
                    return;
            }

            var fileStream = new FileInfo(fullDownloadingPath).Create();

            label3.Visible = true;
            DateTime dt1 = DateTime.Now;
            var str = wc.OpenRead(Properties.Settings.Default.FtpPath + "/" + neededLibrary);

            const int bufferSize = 1024;
            var z = (int)(sz / bufferSize);
            var buffer = new byte[bufferSize];
            int readCount = str.Read(buffer, 0, bufferSize);
            progressBar1.Minimum = 1;
            progressBar1.Value = 1;
            progressBar1.Maximum = z;
            int i = 0;
            int countBytePerSec = 0;
            long commonByte = 0;

            while (readCount > 0)
            {
                DateTime dt2 = DateTime.Now;
                fileStream.Write(buffer, 0, readCount);
                commonByte += readCount;
                countBytePerSec += readCount;
                readCount = str.Read(buffer, 0, bufferSize);
                var dt = dt2 - dt1;
                if (dt.TotalSeconds > i)
                {
                    long lasttime = ((sz - commonByte) / countBytePerSec) * 10000000;
                    var f = new TimeSpan(lasttime);
                    string time;
                    if (f.Hours > 0)
                    {
                        if (f.Hours == 1)
                        {
                            time = f.Hours + " час " + f.Minutes + " минуты " + f.Seconds + " секунд";
                        }
                        else
                        {
                            if (f.Hours > 1 && f.Hours < 5)
                                time = f.Hours + " часа " + f.Minutes + " минуты " + f.Seconds + " секунд";
                            else
                                time = f.Hours + " часов " + f.Minutes + " минуты " + f.Seconds + " секунд";
                        }
                    }
                    else
                        if (f.Minutes > 0)
                            time = f.Minutes + " минут " + f.Seconds + " секунд";
                        else
                            time = f.Seconds + " секунд";
                    countBytePerSec = countBytePerSec / 1024;
                    if (((countBytePerSec) / 1024) > 1)
                    {
                        countBytePerSec = countBytePerSec / 1024;
                        label3.Text = dt.Minutes + @":" + dt.Seconds + @" секунд   Скорость: " + countBytePerSec +
                                      @" Мб/с   Осталось приблизительно: " + time;
                    }
                    else
                        label3.Text = dt.Minutes + @":" + dt.Seconds + @" секунд   Скорость: " + countBytePerSec + @" Кб/с   Осталось приблизительно: " + time;
                    Application.DoEvents();
                    countBytePerSec = 0;
                    i++;
                }
                progressBar1.Increment(1);
            }
            str.Close();
            fileStream.Close();
        }
 /// <summary>
 /// Saves this instance.
 /// </summary>
 public void Save()
 {
     Plugins.ForEach(x => x.Save());
     string FileLocation = HttpContext.Current != null ? HttpContext.Current.Server.MapPath("~/App_Data/PluginList.txt") : AppDomain.CurrentDomain.BaseDirectory + "/App_Data/PluginList.txt";
     string DirectoryLocation = HttpContext.Current != null ? HttpContext.Current.Server.MapPath("~/App_Data/") : AppDomain.CurrentDomain.BaseDirectory + "/App_Data/";
     new System.IO.DirectoryInfo(DirectoryLocation).Create();
     using (FileStream Writer = new System.IO.FileInfo(FileLocation).Open(FileMode.Create, FileAccess.Write))
     {
         byte[] Content = Serialize(this).ToByteArray();
         Writer.Write(Content, 0, Content.Length);
     }
 }
Пример #19
0
        static unsafe void ConvertRAW( string _Source, string _Target )
        {
            using ( Bitmap B = Image.FromFile( _Source ) as Bitmap )
            {
                BitmapData	LockedBitmap = B.LockBits( new Rectangle( 0, 0, B.Width, B.Height ), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb );

                byte[]		RAWImage = new byte[4*B.Width*B.Height];
                int			ByteIndex = 0;
                for ( int Y=0; Y < B.Height; Y++ )
                {
                    byte*	pScanline = (byte*) LockedBitmap.Scan0.ToPointer() + Y * LockedBitmap.Stride;
                    for ( int X=0; X < B.Width; X++ )
                    {
                        RAWImage[ByteIndex+2] = *pScanline++;
                        RAWImage[ByteIndex+1] = *pScanline++;
                        RAWImage[ByteIndex+0] = *pScanline++;
                        RAWImage[ByteIndex+3] = *pScanline++;
                        ByteIndex += 4;
                    }
                }

                B.UnlockBits( LockedBitmap );

                using ( FileStream S = new FileInfo( _Target ).Create() )
                    S.Write( RAWImage, 0, RAWImage.Length );
            }
        }
Пример #20
0
        public override bool RecordData(ObjectStoreTransaction transaction, Record newRecord, Record priorRecord, Entry fileEntry)
        {
            StandardObjectStoreTransaction trans = (StandardObjectStoreTransaction)transaction;
            lock (trans)
            {
                if (trans.Inputs.Contains(GetLookup(newRecord)))
                    return true;
                string filename;
                lock (this)
                {
                    if (HasData(newRecord))
                        return true;
                    do
                    {
                        filename = Path.GetRandomFileName();
                    } while (TempFiles.Contains(filename));
                    TempFiles.Add(filename);
                }
                trans.Inputs.Add(GetLookup(newRecord));
                trans.m_PendingCount++;
                trans.m_PendingBytes += newRecord.Size;
                Printer.PrintDiagnostics("Processing {0}", fileEntry.CanonicalName);
                trans.Cleanup.Add(filename);
                long resultSize;
                string fn = Path.Combine(TempFolder.FullName, filename);
                if (priorRecord != null)
                {
                    // try to delta encode it
                    string priorLookup = GetLookup(priorRecord);
                    var priorData = ObjectDatabase.Find<FileObjectStoreData>(x => x.Lookup == priorLookup);
                    if (priorData != null)
                    {
                        if (priorData.Mode == StorageMode.Delta)
                            priorData = ObjectDatabase.Find<FileObjectStoreData>(x => x.Lookup == priorData.DeltaBase);
                        if (priorData.HasSignatureData)
                        {
                            try
                            {
                                var signature = LoadSignature(priorData);
                                long deltaSize;
                                List<ChunkedChecksum.FileBlock> blocks;
                                Printer.PrintDiagnostics(" - Trying delta encoding");
                                Printer.InteractivePrinter printer = null;
                                if (newRecord.Size > 16 * 1024 * 1024)
                                    printer = Printer.CreateSimplePrinter(" Computing Delta", (obj) => { return string.Format("{0:N1}%", (float)((long)obj / (double)newRecord.Size) * 100.0f); });
                                using (var fileInput = fileEntry.Info.OpenRead())
                                {
                                    blocks = ChunkedChecksum.ComputeDelta(fileInput, fileEntry.Length, signature, out deltaSize, (fs, ps) => { if (ps % (512 * 1024) == 0 && printer != null) printer.Update(ps); });
                                }
                                if (printer != null)
                                {
                                    printer.End(newRecord.Size);
                                    printer = null;
                                }
                                // dont encode as delta unless we get a 50% saving
                                if (deltaSize < fileEntry.Length / 2)
                                {
                                    FileObjectStoreData data = new FileObjectStoreData()
                                    {
                                        FileSize = newRecord.Size,
                                        HasSignatureData = false,
                                        Lookup = GetLookup(newRecord),
                                        Mode = StorageMode.Delta,
                                        DeltaBase = priorData.Lookup,
                                        Offset = 0
                                    };
                                    trans.Cleanup.Add(filename + ".delta");
                                    Printer.PrintDiagnostics(" - Delta encoding");
                                    using (var fileInput = fileEntry.Info.OpenRead())
                                    using (var fileOutput = new FileInfo(fn + ".delta").OpenWrite())
                                    {
                                        ChunkedChecksum.WriteDelta(fileInput, fileOutput, blocks);
                                    }
                                    Printer.PrintDiagnostics(" - Compressing data");
                                    deltaSize = new FileInfo(fn + ".delta").Length;
                                    using (var fileInput = new FileInfo(fn + ".delta").OpenRead())
                                    using (var fileOutput = new FileInfo(fn).OpenWrite())
                                    {
                                        fileOutput.Write(new byte[] { (byte)'d', (byte)'b', (byte)'l', (byte)'x' }, 0, 4);
                                        CompressionMode cmode = DefaultCompression;
                                        if (cmode != CompressionMode.None && deltaSize < 16 * 1024)
                                            cmode = CompressionMode.LZ4;
                                        if (cmode != CompressionMode.None && deltaSize < 1024)
                                            cmode = CompressionMode.None;
                                        int sig = (int)cmode;
                                        fileOutput.Write(BitConverter.GetBytes(sig), 0, 4);
                                        fileOutput.Write(BitConverter.GetBytes(newRecord.Size), 0, 8);
                                        fileOutput.Write(BitConverter.GetBytes(deltaSize), 0, 8);
                                        fileOutput.Write(BitConverter.GetBytes(priorData.Lookup.Length), 0, 4);
                                        byte[] lookupBytes = ASCIIEncoding.ASCII.GetBytes(priorData.Lookup);
                                        fileOutput.Write(lookupBytes, 0, lookupBytes.Length);
                                        if (deltaSize > 16 * 1024 * 1024)
                                        {
                                            printer = Printer.CreateProgressBarPrinter(string.Empty, string.Format(" Writing {0} ", cmode), (obj) =>
                                            {
                                                return string.Format("{0}/{1}", Misc.FormatSizeFriendly((long)obj), Misc.FormatSizeFriendly(deltaSize));
                                            },
                                            (obj) =>
                                            {
                                                return (float)((long)obj / (double)deltaSize) * 100.0f;
                                            },
                                            (obj, lol) => { return string.Empty; }, 40);
                                        }
                                        if (cmode == CompressionMode.LZHAM)
                                            LZHAMWriter.CompressToStream(deltaSize, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                                        else if (cmode == CompressionMode.LZ4)
                                            LZ4Writer.CompressToStream(deltaSize, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                                        else if (cmode == CompressionMode.LZ4HC)
                                            LZ4HCWriter.CompressToStream(deltaSize, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                                        else
                                        {
                                            resultSize = deltaSize;
                                            fileInput.CopyTo(fileOutput);
                                        }
                                        if (printer != null)
                                            printer.End(newRecord.Size);
                                    }
                                    Printer.PrintMessage(" - Compressed: {0} ({1} delta) => {2}", Misc.FormatSizeFriendly(newRecord.Size), Misc.FormatSizeFriendly(deltaSize), Misc.FormatSizeFriendly(resultSize));
                                    trans.PendingTransactions.Add(
                                        new StandardObjectStoreTransaction.PendingTransaction()
                                        {
                                            Record = newRecord,
                                            Data = data,
                                            Filename = filename
                                        }
                                    );
                                    return true;
                                }
                            }
                            catch
                            {

                            }
                        }
                    }
                }
                bool computeSignature = newRecord.Size > 1024 * 64;
                FileObjectStoreData storeData = new FileObjectStoreData()
                {
                    FileSize = newRecord.Size,
                    HasSignatureData = computeSignature,
                    Lookup = GetLookup(newRecord),
                    Mode = StorageMode.Flat,
                    Offset = 0
                };
                using (var fileInput = fileEntry.Info.OpenRead())
                using (var fileOutput = new FileInfo(fn).OpenWrite())
                {
                    fileOutput.Write(new byte[] { (byte)'d', (byte)'b', (byte)'l', (byte)'k' }, 0, 4);
                    CompressionMode cmode = DefaultCompression;
                    if (cmode != CompressionMode.None && newRecord.Size < 16 * 1024)
                        cmode = CompressionMode.LZ4;
                    if (cmode != CompressionMode.None && newRecord.Size < 1024)
                        cmode = CompressionMode.None;
                    int sig = (int)cmode;
                    if (computeSignature)
                        sig |= 0x8000;
                    fileOutput.Write(BitConverter.GetBytes(sig), 0, 4);
                    fileOutput.Write(BitConverter.GetBytes(newRecord.Size), 0, 8);
                    Printer.InteractivePrinter printer = null;
                    if (newRecord.Size > 16 * 1024 * 1024)
                        printer = Printer.CreateSimplePrinter(" Computing Signature", (obj) => { return string.Format("{0:N1}%", (float)((long)obj / (double)newRecord.Size) * 100.0f); });
                    if (computeSignature)
                    {
                        Printer.PrintDiagnostics(" - Computing signature");
                        var checksum = ChunkedChecksum.Compute(1024, fileInput, (fs, ps) => { if (ps % (512 * 1024) == 0 && printer != null) printer.Update(ps); });
                        fileInput.Position = 0;
                        ChunkedChecksum.Write(fileOutput, checksum);
                    }
                    Printer.PrintDiagnostics(" - Compressing data");
                    if (printer != null)
                    {
                        printer.End(newRecord.Size);
                        printer = Printer.CreateProgressBarPrinter(string.Empty, string.Format(" Writing {0} ", cmode), (obj) =>
                        {
                            return string.Format("{0}/{1}", Misc.FormatSizeFriendly((long)obj), Misc.FormatSizeFriendly(newRecord.Size));
                        },
                        (obj) =>
                        {
                            return (float)((long)obj / (double)newRecord.Size) * 100.0f;
                        },
                        (obj, lol) => { return string.Empty; }, 40);
                    }
                    if (cmode == CompressionMode.LZHAM)
                        LZHAMWriter.CompressToStream(newRecord.Size, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                    else if (cmode == CompressionMode.LZ4)
                        LZ4Writer.CompressToStream(newRecord.Size, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                    else if (cmode == CompressionMode.LZ4HC)
                        LZ4HCWriter.CompressToStream(newRecord.Size, 16 * 1024 * 1024, out resultSize, fileInput, fileOutput, (fs, ps, cs) => { if (printer != null) printer.Update(ps); });
                    else
                    {
                        resultSize = newRecord.Size;
                        fileInput.CopyTo(fileOutput);
                    }
                    if (printer != null)
                        printer.End(newRecord.Size);
                }
                Printer.PrintMessage(" - Compressed: {1} => {2}{3}", newRecord.CanonicalName, Misc.FormatSizeFriendly(newRecord.Size), Misc.FormatSizeFriendly(resultSize), computeSignature ? " (computed signatures)" : "");
                trans.PendingTransactions.Add(
                    new StandardObjectStoreTransaction.PendingTransaction()
                    {
                        Record = newRecord,
                        Data = storeData,
                        Filename = filename
                    }
                );
                return true;
            }
        }
Пример #21
0
        void menuText_Click(object sender, EventArgs e)
        {
            if (_config.ConfirmTest)
            {
                DialogResult res = new TestDialog(_config).ShowDialog();
                if (res == DialogResult.Cancel) return;
            }
            // prep stuff
            menuSave_Click("menuTest_Click", new EventArgs());
            if (_config.VerifyTest && !_config.Verify) Common.RunVerify(_mission.MissionPath, _config.VerifyLocation);
            int index = 0;
            while (File.Exists(_config.XwaPath + "\\test" + index + "0.plt")) index++;
            string pilot = "\\test" + index + "0.plt";
            string lst = "\\MISSIONS\\MISSION.LST";
            string backup = "\\MISSIONS\\MISSION_" + index + ".bak";

            // pilot file edit
            File.Copy(Application.StartupPath + "\\xwatest0.plt", _config.XwaPath + pilot);
            FileStream pilotFile = File.OpenWrite(_config.XwaPath + pilot);
            pilotFile.Position = 4;
            char[] indexBytes = index.ToString().ToCharArray();
            BinaryWriter bw = new BinaryWriter(pilotFile);
            bw.Write(indexBytes);
            for (int i = (int)pilotFile.Position; i < 0xC; i++) pilotFile.WriteByte(0);
            pilotFile.Position = 0x010F54;
            bw.Write(indexBytes);
            for (int i = (int)pilotFile.Position; i < 0x010F50 + 0xC; i++) pilotFile.WriteByte(0);
            pilotFile.Close();

            // configure XWA
            System.Diagnostics.Process xwa = new System.Diagnostics.Process();
            xwa.StartInfo.FileName = _config.XwaPath + "\\XWINGALLIANCE.exe";
            xwa.StartInfo.Arguments = "/skipintro";
            xwa.StartInfo.UseShellExecute = false;
            xwa.StartInfo.WorkingDirectory = _config.XwaPath;
            File.Copy(_config.XwaPath + lst, _config.XwaPath + backup, true);
            StreamReader sr = File.OpenText(_config.XwaPath + "\\CONFIG.CFG");
            string contents = sr.ReadToEnd();
            sr.Close();
            int lastpilot = contents.IndexOf("lastpilot ") + 10;
            int nextline = contents.IndexOf("\r\n", lastpilot);
            string modified = contents.Substring(0, lastpilot) + "test" + index + contents.Substring(nextline);
            StreamWriter sw = new FileInfo(_config.XwaPath + "\\CONFIG.CFG").CreateText();
            sw.Write(modified);
            sw.Close();
            sr = File.OpenText(_config.XwaPath + lst);
            contents = sr.ReadToEnd();
            sr.Close();
            string[] expanded = contents.Replace("\r\n", "\0").Split('\0');
            expanded[3] = "7";
            expanded[4] = _mission.MissionFileName;
            expanded[5] = "!MISSION_7_DESC!YOGEME: " + expanded[4];
            modified = String.Join("\r\n", expanded);
            sw = new FileInfo(_config.XwaPath + lst).CreateText();
            sw.Write(modified);
            sw.Close();

            xwa.Start();
            System.Threading.Thread.Sleep(1000);
            System.Diagnostics.Process[] runningXwas = System.Diagnostics.Process.GetProcessesByName("XWINGALLIANCE");
            while (runningXwas.Length > 0)
            {
                Application.DoEvents();
                System.Diagnostics.Debug.WriteLine("sleeping...");
                System.Threading.Thread.Sleep(1000);
                runningXwas = System.Diagnostics.Process.GetProcessesByName("XWINGALLIANCE");
            }

            if (_config.DeleteTestPilots) File.Delete(_config.XwaPath + pilot);
            File.Copy(_config.XwaPath + backup, _config.XwaPath + lst, true);
            File.Delete(_config.XwaPath + backup);
        }