protected bool IsFileLocked(string file)
 {
     //check that problem is not in destination file
     if (File.Exists(file) == true)
     {
         FileStream stream = null;
         try
         {
             stream = new FileInfo(file).Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
             //stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
         }
         catch (Exception ex2)
         {
             //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
             int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
             if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
             {
                 return true;
             }
         }
         finally
         {
             if (stream != null)
                 stream.Close();
         }
     }
     return false;
 }
示例#2
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;
        }
        public void WriteLine_Nothing()
        {
            csvReaderWriter.Open(TestOutputFile, CSVReaderWriter.Mode.Write);
            csvReaderWriter.WriteLine();
            csvReaderWriter.Close();

            StreamReader reader = new FileInfo(TestOutputFile).OpenText();
            Assert.That(reader.ReadToEnd(), Is.EqualTo("\r\n"));
            reader.Close();
        }
示例#4
0
 public string ReadFileUTF8(string filePath)
 {
     string ret;
     using (var stream = new FileInfo(filePath).OpenText())
     {
         ret = stream.ReadToEnd();
         stream.Close();
     }
     return ret;
 }
 /// <summary>
 /// 新建
 /// </summary>
 public void create()
 {
     FileStream fs = new FileInfo(file).Create();
     fs.Close();
     StreamWriter sw = new StreamWriter(file);
     sw.Write("{");
     sw.Write("}");
     sw.Flush();
     sw.Close();
 }
示例#6
0
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            if (openFileDialog1.CheckFileExists)
            {
                this.Activate();
                FileStream fileStream = new FileInfo(openFileDialog1.FileName).OpenRead();
                previewPictureBox.Image = Bitmap.FromStream(fileStream);
                fileStream.Close();
                trixelButton.Enabled = true;
                trackBar1.Enabled = true;
                trackBar1.Minimum = 1;
                trackBar1.Maximum = previewPictureBox.Image.Width > previewPictureBox.Image.Height ? previewPictureBox.Image.Width : previewPictureBox.Image.Height;
                sizeLabel.Text = "" + trackBar1.Value;
            }

        }
 internal static void FileStreamTest()
 {
     Console.WriteLine("文件流读写测试:\n");
     //不同的方式打开文件流
     FileStream testFile = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite);
     //FileStream testFile2 = new FileInfo("text2.txt").Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);
     //写文件
     testFile.WriteByte(50);
     testFile.Write(new byte[] { 10, 20, 30, 40 }, 0, 4);
     testFile.Close();
     //读文件
     testFile = new FileInfo("test.txt").OpenRead();
     byte[] buffer = new byte[testFile.Length];
     testFile.Read(buffer, 0, buffer.Length);
     new List<byte>(buffer).ForEach((e) => Console.Write(e));
     Console.WriteLine();
     testFile.Close();
 }
        public BundleStorageManager(string storagePath, string bundleId)
        {
            _storagePath = storagePath;
            _bundleId = bundleId;
            _dataFolderPath = Path.Combine(storagePath, StorageFolderName);

            Directory.CreateDirectory(_storagePath); // create if necessary
            Directory.CreateDirectory(_dataFolderPath); // create if necessary

            CleanUpExpiredData();

            TransactionId = GetTransactionId();
            BundlePath = Path.Combine(_dataFolderPath, String.Format("{0}.bundle", TransactionId));
            if (!File.Exists(BundlePath))
            {
                var fs = new FileInfo(BundlePath).Create();
                fs.Close();
            }
        }
    public VideoViewHandler()
    {
      if (!File.Exists(customVideoViews))
      {
        File.Copy(defaultVideoViews, customVideoViews);
      }

      try
      {
        using (FileStream fileStream = new FileInfo(customVideoViews).OpenRead())
        {
          SoapFormatter formatter = new SoapFormatter();
          ArrayList viewlist = (ArrayList)formatter.Deserialize(fileStream);
          foreach (ViewDefinition view in viewlist)
          {
            views.Add(view);
          }
          fileStream.Close();
        }
      }
      catch (Exception) {}
    }
示例#10
0
 private void cmdSave_Click(object sender, EventArgs e)
 {
     StreamWriter sw = new FileInfo(_installPath+"\\"+cboFile.Text).CreateText();
     sw.Write(txtLST.Text);
     sw.Close();
 }
示例#11
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();
 }
示例#12
0
 //文件系统
 int loadUsers()
 {
     try
     {
         StreamReader lsr = File.OpenText(".\\users.txt");
         int n = 2;
         int i;
         //label1.Text = "Find " + n.ToString() + " Users";
         for (i = 0; i < n; i++)
         {
             string temp = lsr.ReadLine();
             userName.Add(temp);
             int m = Convert.ToInt16(lsr.ReadLine());
             int j;
             for (j = 0; j < m; j++)
             {
                 string tfilepath = lsr.ReadLine();
                 FileStream stream = new FileInfo(tfilepath).OpenRead();
                 Byte[] buffer = new Byte[stream.Length];
                 //从流中读取字节块并将该数据写入给定缓冲区buffer中
                 stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                 FaceTemplate ftem;
                 ftem.templateData = buffer;
                 faceTemplates.Add(ftem);
                 stream.Close();
             }
             List<FaceTemplate> atemp = new List<FaceTemplate>(faceTemplates.ToArray());
             UserTemplates.Add(atemp);
             faceTemplates.Clear();
         }
         lsr.Close();
         Console.WriteLine("Load OK");
         Console.WriteLine(UserTemplates.Count.ToString());
         Console.WriteLine(userName.Count.ToString());
         return 0;
     }
     catch
     {
         Console.WriteLine("No user Stored");
         return 1;
     }
 }
示例#13
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);
        }
示例#14
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();
        }
示例#15
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();
        }
示例#16
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);
        }
示例#17
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;
        }
示例#18
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;
        }
示例#19
0
        private void AssertFailMyXls(string message, string expectedFile, string actualFile)
        {
            Ole2Document n2doc = new Ole2Document();
            FileStream fs = new FileInfo(actualFile).Open(FileMode.Open, FileAccess.Read);
            n2doc.Load(fs);
            fs.Close();
            Bytes actualWorksheet = n2doc.Streams[n2doc.Streams.GetIndex(Directory.Biff8Workbook)].Bytes;
            n2doc = new Ole2Document();
            fs = new FileInfo(expectedFile).Open(FileMode.Open, FileAccess.Read);
            n2doc.Load(fs);
            fs.Close();
            Bytes expectedWorksheet = n2doc.Streams[n2doc.Streams.GetIndex(Directory.Biff8Workbook)].Bytes;
            string expectedWorksheetFile = "ExpectedWorksheet.records";
            string actualWorksheetFile = "ActualWorksheet.records";
            WriteRecordsToFile(actualWorksheet, actualWorksheetFile);
            WriteRecordsToFile(expectedWorksheet, expectedWorksheetFile);

            Process ueProc = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "uedit32";
            startInfo.Arguments =
                string.Format("/a \"{0}\" \"{1}\" \"{2}\" \"{3}\"", expectedFile, actualFile, expectedWorksheetFile,
                              actualWorksheetFile);
            ueProc.StartInfo = startInfo;
            ueProc.Start();
            Assert.Fail(message);
        }
示例#20
0
    private void createFile(String fileName) 
    {
      String desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
      DirectoryInfo d = new DirectoryInfo(desktop);
      bool isExists = false;

      foreach (FileInfo f in d.GetFiles())
      {
        if (f.Name == fileName)
        {
          isExists = true;
          break;
        }
      }

      if (!isExists)
      {
        FileStream fs = new FileInfo(@Path.Combine(desktop, fileName)).Create();
        fs.Close();
      }
    }
示例#21
0
        public Scene(string inputFilename)
        {
            triangles = new List<Triangle>();
            quads = new List<Quad>();
            bullets = new List<Bullet>();
            hud = new HUD();

            StreamReader reader = new FileInfo(inputFilename).OpenText();
            string line;

            Dictionary<string, Vector> loadedVertices = new Dictionary<string, Vector>();
            Dictionary<string, int> loadedTextures = new Dictionary<string, int>();
            Dictionary<string, float> values = new Dictionary<string,float>();

            int texturesCount = 0;
            textures = new uint[texturesCount];

            int lineCounter = 0;

            while (true)
            {
                line = reader.ReadLine();

                if (line == null)
                    break;

                line = System.Text.RegularExpressions.Regex.Replace(line, "#.*", "", System.Text.RegularExpressions.RegexOptions.Compiled);

                lineCounter++;

                if (line == "")
                    continue;

                if (line.IndexOf("clear vertices") == 0)
                    loadedVertices = new Dictionary<string, Vector>();

                else if (line.IndexOf("start") == 0)
                {
                    #region start
                    string[] parts = line.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length != 6)
                    {
                        throw new Exception("line.split for start did not make the right length array. line " + lineCounter.ToString());
                    }

                    cameraPosition.x = GetFloat(parts[1], values);
                    cameraPosition.y = GetFloat(parts[2], values);
                    cameraPosition.z = GetFloat(parts[3], values);

                    lookAngleX = GetFloat(parts[4], values);
                    lookAngleY = GetFloat(parts[5], values);
                    #endregion
                }
                else if (line.Contains("vertex"))
                {
                    #region vertex
                    try
                    {
                        string[] parts = line.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

                        if (parts.Length != 5)
                            throw new Exception("line.Split for Vector did not make the right length array. line " + lineCounter.ToString());

                        string name = parts[1];
                        float x = GetFloat(parts[2], values);
                        float y = GetFloat(parts[3], values);
                        float z = GetFloat(parts[4], values);

                        loadedVertices.Add(name, new Vector(x, y, z));
                    }
                    catch (Exception e)
                    {
                        throw new Exception("error parsing input file. line " + lineCounter.ToString() + " . message: " + e.Message);
                    }
                    #endregion
                }
                else if (line.Contains("quad"))
                {
                    #region quad
                    string[] parts;
                    parts = line.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

                    if (parts.Length > 10)
                    {
                        throw new Exception("line.split for quad was not the right length. line: " + lineCounter.ToString());
                    }

                    if (parts[5] == "color")
                    {
                        float red = GetFloat(parts[6], values);
                        float green = GetFloat(parts[7], values);
                        float blue = GetFloat(parts[8], values);

                        MyColor color = new MyColor(red, green, blue);

                        string name = parts[9];

                        Vector v1 = loadedVertices[parts[1]];
                        Vector v2 = loadedVertices[parts[2]];
                        Vector v3 = loadedVertices[parts[3]];
                        Vector v4 = loadedVertices[parts[4]];

                        Quad quad = new Quad(v1, v2, v3, v4, color, name);
                        quads.Add(quad);
                    }
                    else if (parts[5] == "tex")
                    {
                        Vector v1 = loadedVertices[parts[1]];
                        Vector v2 = loadedVertices[parts[2]];
                        Vector v3 = loadedVertices[parts[3]];
                        Vector v4 = loadedVertices[parts[4]];

                        string textureName = parts[6];
                        string name = parts[7];

                        Quad quad = new Quad(v1, v2, v3, v4, name, (uint)loadedTextures[textureName]);
                        quads.Add(quad);
                    }
                    #endregion
                }
                else if (line.Contains("triangle"))
                {
                    #region triangle
                    string[] parts;
                    try
                    {
                        parts = line.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

                        if (parts.Length < 6)
                            throw new Exception("line.split for triangle did not make the right length array. line " + lineCounter.ToString());
                    }
                    catch (Exception e)
                    {
                        throw new Exception("error splitting triangle line in input file. line " + lineCounter.ToString() + " . message: " + e.Message);
                    }

                    try
                    {
                        if (parts[4] == "color")
                        {
                            float red = GetFloat(parts[5], values);
                            float green = GetFloat(parts[6], values);
                            float blue = GetFloat(parts[7], values);

                            MyColor color = new MyColor(red, green, blue);

                            Vector v1 = loadedVertices[parts[1]];
                            Vector v2 = loadedVertices[parts[2]];
                            Vector v3 = loadedVertices[parts[3]];

                            Triangle tri = new Triangle(v1, v2, v3, color);
                            triangles.Add(tri);
                        }
                        else if (parts[4] == "texture")
                        {
                            Vector v1 = loadedVertices[parts[1]];
                            Vector v2 = loadedVertices[parts[2]];
                            Vector v3 = loadedVertices[parts[3]];

                            string textureName = parts[5];

                            Triangle tri = new Triangle(v1, v2, v3, (uint)loadedTextures[textureName]);
                            triangles.Add(tri);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("error creating triangle in input file. line: " + lineCounter.ToString() + " . message: " + e.Message);
                    }
                    #endregion
                }
                else if (line.Contains("texture"))
                {
                    #region texture
                    string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    string file = parts[1];
                    string name = parts[2];

                    texturesCount++;
                    loadedTextures[name] = texturesCount;
                    LoadTexture(file, texturesCount);
                    #endregion
                }
                else if (line.Contains("value"))
                {
                    #region value
                    string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    string name = parts[1];
                    float value = float.Parse(parts[2]);

                    values[name] = value;
                    #endregion
                }
                else if(line.Contains("clearValues"))
                {
                    values = new Dictionary<string,float>();
                }
                else
                {
                    throw new Exception("line " + lineCounter.ToString() + " not understood");
                }

            }

            reader.Close();

            lastMouseX = Cursor.Position.X;
            lastMouseY = Cursor.Position.Y;
        }
        public void SaveBlowingSchema(string schemaName, comBlowingSchemaEvent[] schemas)
        {
            StoredScheme str = new StoredScheme();
            str.BlowingSchemas = schemas;
            if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\dat"))
                Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + "\\dat");

            using (FileStream fs = new FileInfo(
                string.Format("{0}\\dat\\{1}.heatScript", System.AppDomain.CurrentDomain.BaseDirectory, schemaName)).Create())
            {
                new BinaryFormatter().Serialize(fs, str);
                fs.Close();
            }
        }
 public comBlowingSchemaEvent[] LoadBlowingSchema(string schemaName)
 {
     StoredScheme result = new StoredScheme();
     try
     {
         using (FileStream fs = new FileInfo(
             string.Format("{0}dat\\{1}.heatScript", System.AppDomain.CurrentDomain.BaseDirectory, schemaName)).OpenRead())
         {
             BinaryFormatter formatter = new BinaryFormatter();
             formatter.AssemblyFormat  = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
             formatter.Binder = new PreMergeToMergedDeserializationBinder();
             result = (StoredScheme)formatter.Deserialize(fs);
             fs.Close();
         }
     }
     catch { };
     return result.BlowingSchemas;
 }
示例#24
0
        private static void Main(string[] args)
        {
            string llo = "LampLightOnlineSharp";
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\";

            /*


            var projs = new[]
                { 
                    llo+@"\LampLightOnlineClient\",
                    llo+@"\LampLightOnlineServer\",
                };

            foreach (var proj in projs)
            {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                if (File.Exists(to)) File.Delete(to);
                File.Copy(from, to);
            }
*/

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application> {
                                                                      /*{
                        llo+@"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string>
                            {
                                @"./CommonLibraries.js",
                                @"./CommonServerLibraries.js",
                                @"./Models.js",
                            })
                    }*/
                                                                      {
                                                                              "MM.ChatServer", new Application(true,
                                                                                                               new List<string> {
                                                                                                                                        @"./CommonAPI.js",
                                                                                                                                        @"./ServerAPI.js",
                                                                                                                                        @"./CommonLibraries.js",
                                                                                                                                        @"./CommonServerLibraries.js",
                                                                                                                                        @"./Models.js",
                                                                                                                                })
                                                                      }, {
                                                                                 "MM.GameServer", new Application(true,
                                                                                                                  new List<string> {
                                                                                                                                           @"./CommonAPI.js",
                                                                                                                                           @"./MMServerAPI.js",
                                                                                                                                           @"./CommonLibraries.js",
                                                                                                                                           @"./CommonServerLibraries.js",
                                                                                                                                           @"./CommonClientLibraries.js",
                                                                                                                                           @"./MMServer.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                           @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                           @"./Models.js",
                                                                                                                                           @"./RawDeflate.js",
                                                                                                                                   }) {}
                                                                         }, {
                                                                                    "MM.GatewayServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./MMServerAPI.js",
                                                                                                                                                 @"./MMServer.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Common.js",
                                                                                                                                                 @"./Games/ZombieGame/ZombieGame.Server.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                            }, {
                                                                                       "MM.HeadServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonAPI.js",
                                                                                                                                                 @"./ServerAPI.js",
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                               }, {
                                                                                          "SiteServer", new Application(true,
                                                                                                                        new List<string> {
                                                                                                                                                 @"./CommonLibraries.js",
                                                                                                                                                 @"./CommonServerLibraries.js",
                                                                                                                                                 @"./Models.js",
                                                                                                                                         })
                                                                                  },
                                                                      {"Client", new Application(false, new List<string> {})},
                                                                      {"CommonWebLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonClientLibraries", new Application(false, new List<string> {})},
                                                                      {"CommonServerLibraries", new Application(false, new List<string> {})},
                                                                      {"MMServer", new Application(false, new List<string> {})},
                                                                      {"MMServerAPI", new Application(false, new List<string> {})},
                                                                      {"ClientAPI", new Application(false, new List<string> {})},
                                                                      {"ServerAPI", new Application(false, new List<string> {})},
                                                                      {"CommonAPI", new Application(false, new List<string> {})},
                                                              };

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) => {
                                   var left = Console.CursorLeft;
                                   var top = Console.CursorTop;

                                   Console.SetCursorPosition(65, 5);
                                   Console.Write("|");

                                   for (int i = 0; i < c.Percentage / 10; i++) {
                                       Console.Write("=");
                                   }
                                   for (int i = (int) ( c.Percentage / 10 ); i < 10; i++) {
                                       Console.Write("-");
                                   }
                                   Console.Write("|");

                                   Console.Write(c.Percentage + "  %  ");
                                   Console.WriteLine();
                                   Console.SetCursorPosition(left, top);
                               };

            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
            client.Connect();

            Console.WriteLine("server connected");

#endif

            foreach (var depend in depends) {
                var to = pre + "\\" + llo + @"\output\" + depend.Key + ".js";
                var output = "";

                if (depend.Value.Node)
                    output += "require('./mscorlib.debug.js');\r\n";
                else {
                    //output += "require('./mscorlib.debug.js');";
                }

                foreach (var depe in depend.Value.IncludesAfter) {
                    output += string.Format("require('{0}');\r\n", depe);
                }

                if (depend.Value.Postpend != null) output += depend.Value.Postpend + "\r\n";
                var lines = new List<string>();
                lines.Add(output);
                lines.AddRange(File.ReadAllLines(to).After(1)); //mscorlib

                string text = lines.Aggregate("", (a, b) => a + b + "\n");
                File.WriteAllText(to, text);

                //     lines.Add(depend.Value.After); 

                var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();
                //   File.WriteAllText(to, text);

#if FTP

                long length = new FileInfo(to).Length;
                if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) {
                    Console.WriteLine("ftp start " + length.ToString("N0"));
                    webftp.Upload(loc + name, to);
                    Console.WriteLine("ftp complete " + to);
                }

                if (!client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
                if (!client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
#endif
            }

            string[] games = {"ZombieGame" /*, "TowerD", "ZakGame" */};

            foreach (var depend in games) {
                var to = pre + llo + @"\output\Games\" + depend + @"\";

                string[] exts = {"Client", "Common", "Server"};

                foreach (var ext in exts) {
                    //     lines.Add(depend.Value.After); 
                    string fm = to + depend + "." + ext + ".js";

                    string text = File.ReadAllText(fm);
                    File.WriteAllText(fm, text);

#if FTP
                    Console.WriteLine("ftp start " + text.Length.ToString("N0"));
                    webftp.Upload(loc + "Games/" + depend + "/" + depend + "." + ext + ".js", fm);
                    Console.WriteLine("ftp complete " + fm);

                    Console.WriteLine("server ftp start " + text.Length.ToString("N0"));

                    var fileStream = new FileInfo(fm).OpenRead();
                    client.UploadFile(fileStream, serverloc + "Games/" + depend + "/" + depend + "." + ext + ".js", true);
                    fileStream.Close();
                    fileStream = new FileInfo(fm).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + "Games/" + depend + "/" + depend + "." + ext + ".js", true);
                    fileStream.Close();

                    Console.WriteLine("server ftp complete " + fm);
#endif
                }
            }
        }
        /* Metodo para crear las tablas en la base de datos seleccionada*/
        private bool createDatabase()
        {
            NpgsqlConnection connection;
            NpgsqlCommand command;

            try
            {
                connection = new NpgsqlConnection(connectionString.ToString());

                StreamReader fsSQL = new FileInfo(myNode.Addin.GetFilePath("subscription.sql")).OpenText();
                string SQL_Script = fsSQL.ReadToEnd();
                fsSQL.Close();
                command = new NpgsqlCommand(SQL_Script, connection);

                connection.Open();

                if(command.ExecuteNonQuery() == 0)
                {
                    connection.Close();
                    MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Error connection");
               		md.Run();
               		md.Destroy();
                    connection.Close();
                    return false;
                }
            }
            catch(NpgsqlException ex)
            {
                MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Error connection: " + ex.Message);
               	md.Run();
               	md.Destroy();
                connection.Close();
            }

            return true;
        }
        /* 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;
            }
        }
        public void WriteWholeFile()
        {
            var data = new List<string[]>();
            data.Add(new string[] { "column1line1", "column2line1" });
            data.Add(new string[] { "column1line2", "column2line2" });
            csvReaderWriter.Open(TestOutputFile, CSVReaderWriter.Mode.Write);
            csvReaderWriter.WriteWholeFile(data);
            csvReaderWriter.Close();

            StreamReader reader = new FileInfo(TestOutputFile).OpenText();
            Assert.That(reader.ReadLine(), Is.EqualTo("column1line1" + "\t" + "column2line1"));
            Assert.That(reader.ReadLine(), Is.EqualTo("column1line2" + "\t" + "column2line2"));
            reader.Close();
        }
示例#28
0
        private void AssertFilesBinaryEqual(string expectedFileName, string actualFileName)
        {
            int row = 0;
            FileStream expectedStream = new FileInfo(expectedFileName).Open(FileMode.Open, FileAccess.Read);
            FileStream actualStream = new FileInfo(actualFileName).Open(FileMode.Open, FileAccess.Read);

            string failMessage = string.Empty;

            try
            {
                while (!IsEOF(expectedStream) && !IsEOF(actualStream))
                {
                    byte[] bufferExpected = new byte[16];
                    byte[] bufferActual = new byte[16];

                    expectedStream.Read(bufferExpected, 0, 16);
                    actualStream.Read(bufferActual, 0, 16);

                    int i = 0;
                    for (; i < 16; i++)
                        if (bufferExpected[i] != bufferActual[i]) break;

                    if (i < 16)
                    {
                        int diffPosition = row * 16 + i;
                        failMessage = string.Format("files differ at byte {0}", diffPosition);
                        break;
                    }

                    row++;
                }

                if (failMessage == string.Empty)
                {
                    if (!IsEOF(expectedStream))
                        Assert.Fail("expected is longer");
                    else if (!IsEOF(actualStream))
                        Assert.Fail("actual is longer");
                }
            }
            finally
            {
                expectedStream.Close();
                expectedStream.Dispose();
                actualStream.Close();
                actualStream.Dispose();
            }

            if (failMessage != string.Empty)
            {
                Console.WriteLine("AssertBinaryFilesEqual failed expected file {0} actual file {1}: {2}",
                    expectedFileName, actualFileName, failMessage);
                AssertFailMyXls(failMessage, expectedFileName, actualFileName);
            }
        }
        // TOOD: xml spreadsheet での出力
        void ExportSummary()
        {
            SaveFileDialog dialog = new SaveFileDialog()
            {
                Filter = "CSV File|*.csv",
            };
            if (dialog.ShowDialog() == DialogResult.Cancel) return;

            StreamWriter fs = null;
            try
            {
                fs = new FileInfo(dialog.FileName).CreateText();
                foreach (DataGridViewRow row in dataGridViewImages.SelectedRows)
                {
                    DataRowView row_view = row.DataBoundItem as DataRowView;
                    if (row_view == null) continue;
                    SignatureCounterDataSet.ImageFileRow row_image = row_view.Row as SignatureCounterDataSet.ImageFileRow;
                    if (row_image == null) continue;

                    var query_image_detail =
                        from matching in tables.MatchingTableAdapter.GetData()
                        join signature in tables.SignatureTableAdapter.GetData() on matching.SignatureID equals signature.ID
                        join signatory in tables.SignatoryTableAdapter.GetData() on matching.SignatoryID equals signatory.ID
                        where !signature.IsConclusiveMatchingIDNull() && signature.ConclusiveMatchingID == matching.ID
                        select new { Signature = signature, Matching = matching, Signatory = signatory };
                    foreach (var matchings in query_image_detail)
                    {
                        //TODO: ,のエスケープ
                        //TODO: UTF-8を出力するとExcelで開けない
                        fs.WriteLine(String.Format("{0},{1},{2}", row_image.FullPath, matchings.Signatory.ID, matchings.Signatory.Name));
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBox.Show(String.Format("Unable to open file:\n{0}", e.Message));
            }
            catch (DirectoryNotFoundException e)
            {
                MessageBox.Show(String.Format("Directory name is wrong:\n{0}", e.Message));
            }
            catch (IOException e)
            {
                MessageBox.Show(String.Format("IO error:\n{0}", e.Message));
            }
            catch (InvalidOperationException e)
            {
                MessageBox.Show(String.Format("Operation error:\n{0}", e.Message));
            }
            catch (Exception e)
            {
                MessageBox.Show("Exporting file is failed:\n" + e.Message);
            }
            finally
            {
                if (fs!=null) fs.Close();
            }
        }
示例#30
0
        private static void Main(string[] args)
        {
            string shufSharp = "ShufflySharp";

            var projs = new[] {
                                      shufSharp + @"\Libraries\CommonLibraries\",
                                      shufSharp + @"\Libraries\CommonShuffleLibrary\",
                                      shufSharp + @"\Libraries\ShuffleGameLibrary\",
                                      shufSharp + @"\Libraries\NodeLibraries\",
                                      shufSharp + @"\Servers\ServerManager\", 
                                      shufSharp + @"\Models\",
                                      shufSharp + @"\Client\",
                                      shufSharp + @"\ClientLibs\",
                                      shufSharp + @"\ServerSlammer\",
                              };
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\";

            foreach (var proj in projs) {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + shufSharp + @"\output\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";

                if (File.Exists(to)) tryDelete(to);
                tryCopy(from, to);
            }

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application>(); 
            depends.Add(shufSharp + @"\Servers\ServerManager\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./CommonLibraries.js",
                                                                 @"./CommonShuffleLibrary.js",
                                                                 @"./ShuffleGameLibrary.js",
                                                                 @"./Models.js",
                                                                 @"./RawDeflate.js",
                                                         })); 


            depends.Add(shufSharp + @"\Libraries\CommonShuffleLibrary\",
                        new Application(false,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                         }));
            depends.Add(shufSharp + @"\Libraries\NodeLibraries\", new Application(true, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\CommonLibraries\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ClientLibs\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ServerSlammer\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./Models.js",
                                                                 @"./ClientLibs.js",
                                                         }));
            depends.Add(shufSharp + @"\Models\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\ShuffleGameLibrary\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Client\",
                        new Application(false,
                                        new List<string> {}));

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            /*   Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) =>
            {
                var left = Console.CursorLeft;
                var top = Console.CursorTop;

                Console.SetCursorPosition(65, 5);
                Console.Write("|");

                for (int i = 0; i < c.Percentage / 10; i++)
                {
                    Console.Write("=");
                }
                for (int i = (int)(c.Percentage / 10); i < 10; i++)
                {
                    Console.Write("-");
                }
                Console.Write("|");

                Console.Write(c.Percentage + "  %  ");
                Console.WriteLine();
                Console.SetCursorPosition(left, top);
            };
*/
            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
            client.Connect();

            Console.WriteLine("server connected");

#endif

            foreach (var depend in depends) {
                var to = pre + shufSharp + @"\output\" + depend.Key.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                var output = "";

                Application application = depend.Value;

                if (application.Node) {
                    output += "require('./mscorlib.js');";
                    output += "EventEmitter= require('events.js').EventEmitter;";
                } else {
                    //output += "require('./mscorlib.debug.js');";
                }

                foreach (var depe in application.IncludesAfter) {
                    output += string.Format("require('{0}');", depe);
                }

                var lines = new List<string>();
                lines.Add(output);
                lines.AddRange(File.ReadAllLines(to));

                //      lines.Add(application.After);

                File.WriteAllLines(to, lines);
                var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();

#if FTP

                long length = new FileInfo(to).Length;
                /*       if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length)
                {
                    Console.WriteLine("ftp start " + length.ToString("N0"));
                    webftp.Upload(loc + name, to);
                    Console.WriteLine("ftp complete " + to);
                }
*/
                if (true || !client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
                if (true || !client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
#endif
                if (File.Exists(@"C:\code\node\" + name) && /*new FileInfo(@"C:\code\node\" + name).Length != new FileInfo(to).Length*/ true) {
                    tryDelete(@"C:\code\node\" + name);
                    tryCopy(to, @"C:\code\node\" + name);
                }
            }

            foreach (var d in Directory.GetDirectories(pre + shufSharp + @"\ShuffleGames\")) {
                string game = d.Split('\\').Last();
                var to = pre + shufSharp + @"\output\Games\" + game;
                if (!Directory.Exists(to))

                    Directory.CreateDirectory(to);
                if (d.EndsWith("bin") || d.EndsWith("obj"))
                    continue;
                File.WriteAllText(to + @"\app.js", File.ReadAllText(d + @"\app.js"));

#if FTP

                Console.WriteLine("server ftp start ");

                var fileStream = new FileInfo(to + @"\app.js").OpenRead();
                if (!client.Exists(serverloc + string.Format("Games/{0}", game)))
                    client.CreateDirectory(serverloc + string.Format("Games/{0}", game));
                client.UploadFile(fileStream, serverloc + string.Format("Games/{0}/app.js", game), true);
                fileStream.Close();

                Console.WriteLine("server ftp complete " + to);
#endif
            }
        }