Esempio n. 1
0
        //private:
        void Connect()
        {
            const int BUFFER_SIZE = 4096;

            if (m_dpCount == 0)
            {
                bool connected = false;

                try
                {
                    m_dataFile = new System.IO.FileStream(FilePath,
                                                          System.IO.FileMode.Open,
                                                          System.IO.FileAccess.ReadWrite,
                                                          System.IO.FileShare.Read,
                                                          BUFFER_SIZE,
                                                          System.IO.FileOptions.RandomAccess);

                    Reader = new SeekableReader(m_dataFile);
                    Writer = new SeekableWriter(m_dataFile);
                    Header.Read(Reader);

                    Init();
                    connected = true;
                }
                catch (System.IO.FileNotFoundException)
                {
                    System.Diagnostics.Debug.WriteLine("Try to create the file {0}.", FilePath);

                    m_dataFile = new System.IO.FileStream(FilePath,
                                                          System.IO.FileMode.CreateNew,
                                                          System.IO.FileAccess.ReadWrite,
                                                          System.IO.FileShare.Read,
                                                          BUFFER_SIZE,
                                                          System.IO.FileOptions.RandomAccess);

                    Header.Reset();
                    Header.CreationTime = DateTime.Now;

                    Writer = new SeekableWriter(m_dataFile);
                    Reader = new SeekableReader(m_dataFile);
                    Header.Write(Writer);

                    Init();
                    connected = true;
                }
                finally
                {
                    if (!connected)
                    {
                        m_dataFile?.Dispose();
                        m_dataFile = null;
                        Reader     = null;
                        Writer     = null;
                    }
                }
            }

            ++m_dpCount;
            Assert(IsConnected);
        }
Esempio n. 2
0
        private void OnAsyncCompressed(object Sender, Archive.ArchiveEventArgs e)
        {
            this.Logger?.WriteLine("Compress end event.");

            // 圧縮に成功したならアップロードします。
            if (!this.m_Zipper.IsCompressed)
            {
                return;
            }

            System.IO.FileStream Data = null;

            try {
                // アーカイブをファイルストリームで開きます。
                Data = new System.IO.FileStream(e.Destnation, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // オブジェクトストレージの指定コンテナにアーカイブをアップロードします。
                OpenStack.CreateObject(Options.UseContainerName, System.IO.Path.GetFileName(e.Destnation), Data, eContentType.CONTENTS_ARCHIVE_ZIP);

                this.Logger?.WriteLine("Archive file uploaded.");
            } catch (System.Exception ex) {
                this.Logger?.WriteLine(ex.Message, eLogLevel.ERROR);
            } finally{
                // ストリームを必ず閉じます。
                Data?.Close();
                Data?.Dispose();

                // 圧縮したファイルとテンポラリディレクトリを片付けます。
                System.IO.File.Delete(this.TemporaryPath + "/" + e.Destnation);
                System.IO.Directory.Delete(this.TemporaryPath, true);
            }
        }
Esempio n. 3
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return _Buffer;
        }
        async private void ImportButton_Click(object sender, RoutedEventArgs e)
        {
            System.IO.FileStream stream = null;
            try
            {
                var selectedJournal = lookupJournal.SelectedItem as GLDailyJournalClient;
                if (selectedJournal == null)
                {
                    UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("RecordNotSelected"), Uniconta.ClientTools.Localization.lookup("Error"));
                    return;
                }

                var importDateV = new ImportDATEV(api, selectedJournal);

                stream = new System.IO.FileStream(browseFile.FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                var journalLines = await importDateV.CreateJournalLines(stream);

                stream.Dispose();
                stream = null;

                if (importDateV.faultyAccounts.Count != 0)
                {
                    journalLines = null;
                    var sb = StringBuilderReuse.Create();
                    sb.Append(string.Format(Uniconta.ClientTools.Localization.lookup("MissingOBJ"), Uniconta.ClientTools.Localization.lookup("Account"))).AppendLine(':');
                    foreach (var s in importDateV.faultyAccounts)
                    {
                        sb.AppendLine(s);
                    }

                    UnicontaMessageBox.Show(sb.ToStringAndRelease(), "", MessageBoxButton.OK);
                    return;
                }

                if (journalLines != null && journalLines.Count > 0)
                {
                    var result = await api.Insert(journalLines);

                    if (result == ErrorCodes.Succes)
                    {
                        UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("Succes"), Uniconta.ClientTools.Localization.lookup("Message"));
                        DialogResult = true;
                    }
                }
                else
                {
                    UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("NoJournalLinesCreated"), Uniconta.ClientTools.Localization.lookup("Error"));
                    return;
                }
            }
            catch (Exception ex)
            {
                stream?.Dispose();
                UnicontaMessageBox.Show(ex);
                DialogResult = false;
            }
        }
        public override void Test()
        {
            OpenDMS.Storage.Providers.EngineRequest request = new OpenDMS.Storage.Providers.EngineRequest();
            request.Engine = _engine;
            request.Database = _db;
            request.OnActionChanged += new EngineBase.ActionDelegate(EngineAction);
            request.OnProgress += new EngineBase.ProgressDelegate(Progress);
            request.OnComplete += new EngineBase.CompletionDelegate(Complete);
            request.OnTimeout += new EngineBase.TimeoutDelegate(Timeout);
            request.OnError += new EngineBase.ErrorDelegate(Error);
            request.AuthToken = _window.Session.AuthToken;
            request.RequestingPartyType = OpenDMS.Storage.Security.RequestingPartyType.User;

            Clear();

            OpenDMS.Storage.Providers.CreateResourceArgs resourceArgs = new CreateResourceArgs()
            {
                VersionArgs = new CreateVersionArgs()
            };

            resourceArgs.Metadata = new OpenDMS.Storage.Data.Metadata();
            resourceArgs.Tags = new List<string>();
            resourceArgs.Tags.Add("Tag1");
            resourceArgs.Tags.Add("Tag2");
            resourceArgs.Title = "Test resource";
            resourceArgs.VersionArgs.Extension = "txt";
            resourceArgs.VersionArgs.Metadata = new OpenDMS.Storage.Data.Metadata();

            System.IO.FileStream fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, 8192, System.IO.FileOptions.None);
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes("This is a test content file.");
            fs.Write(bytes, 0, bytes.Length);
            fs.Flush();
            fs.Close();
            fs.Dispose();

            fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, 8192, System.IO.FileOptions.None);
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(fs);
            string output = "";
            fs.Close();
            md5.Dispose();
            fs.Dispose();

            for (int i = 0; i < data.Length; i++)
                output += data[i].ToString("x2");

            resourceArgs.VersionArgs.Md5 = output;
            resourceArgs.VersionArgs.Content = new OpenDMS.Storage.Data.Content(bytes.Length, new OpenDMS.Storage.Data.ContentType("text/plain"), "testdoc.txt");

            WriteLine("Starting CreateNewResource test...");
            _start = DateTime.Now;

            _engine.CreateNewResource(request, resourceArgs);
        }
        public ConfigurationServer()
        {
            this.WorkflowData = null;
            InitializeComponent();

            XmlSerializer mySerializer = new XmlSerializer(typeof(WorkflowData));
            // To read the file, create a FileStream.
            System.IO.FileStream myFileStream = new System.IO.FileStream("workflowdata.xml", System.IO.FileMode.Open);
            // Call the Deserialize method and cast to the object type.
            this.WorkflowData = (WorkflowData)mySerializer.Deserialize(myFileStream);
            myFileStream.Close();
            myFileStream.Dispose();
        }
Esempio n. 7
0
        public static byte[] GetBytesFromFile(string file)
        {
            try
            {

                // check if this is a file name;
                if (file == null)
                    return null;

                if (file.Trim().Length == 0)
                    return null;

                // get the size of the buffer
                int bufferSize = (int)(new System.IO.FileInfo(file).Length);

                // check if the file has anything.
                if (bufferSize == 0)
                    return null;

                // create the buffer with the proper size
                byte[] buffer = new byte[bufferSize];

                // create the stream
                System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open);

                // create the reader of the stream
                System.IO.BinaryReader reader = new System.IO.BinaryReader(fs);

                // populate the buffer
                buffer = reader.ReadBytes(bufferSize);

                // Close the stream
                fs.Close();
                fs.Dispose();

                // close the reader
                reader.Close();
                fs.Dispose();

                return buffer;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Please Make sure that the file is valid or is not in use. Details:\r\n" + ex.Message);
                return null;
            }
        }
 //***********************************WriteFile***********************************
 public void WriteFile(IEnumerable <DataRecords> records)
 {
     // Stream file
     using (var fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
     {
         // Read stream as write.
         using (var sw = new System.IO.StreamWriter(fs))
         {
             CsvWriter csvW = new CsvWriter(sw);
             // write updated records to database csv
             csvW.WriteRecords(records);
             sw.Dispose();
         }
         // close
         fs.Dispose();
         fs.Close();
     }
 }
Esempio n. 9
0
 public void Dispose()
 {
     if (_reader != null)
     {
         _reader.Dispose();
         _reader = null;
     }
     if (_streamReader != null)
     {
         _streamReader.Dispose();
         _streamReader = null;
     }
     if (_fstream != null)
     {
         _fstream.Dispose();
         _fstream = null;
     }
 }
Esempio n. 10
0
        #pragma warning restore 1591

        //******************************************************************************
        //
        // Method: Dispose
        //
        //******************************************************************************
        /// <summary>
        /// Provides a method to free unmanaged resources used by this class.
        /// </summary>
        /// <param name="disposing">Whether the method is being called as part of an explicit Dispose routine, and hence whether managed resources should also be freed.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Free other state (managed objects).
                }
                // Free your own state (unmanaged objects).
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
                // Set large fields to null.
                path     = null;
                disposed = true;
            }
        }
Esempio n. 11
0
 public static string GetTxt(string path)
 {
     try
     {
         System.IO.FileStream   fsr = System.IO.File.OpenRead(path);
         System.IO.StreamReader sr  = new System.IO.StreamReader(fsr);
         string record = sr.ReadLine();
         sr.Close();
         sr.Dispose();
         fsr.Close();
         fsr.Dispose();
         return(record);
     }
     catch
     {
         return("");
     }
 }
        private void LoadTodoTaskFile(object obj)
        {
            TodoTaskItems.Clear();

            System.IO.FileStream   file   = System.IO.File.Open("mytasks.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
            System.IO.StreamReader reader = new System.IO.StreamReader(file);

            while (reader.EndOfStream == false)
            {
                TodoTask todoTask = new TodoTask();
                todoTask.Description = reader.ReadLine();

                TodoTaskItems.Add(new TodoTaskViewModel(todoTask));
            }

            reader.Dispose();
            file.Dispose();
        }
Esempio n. 13
0
        public virtual void SerializationTest()
        {
            int TEST_SET_LENGTH = 10;
            int[] indicies = SetGenerator.GetRandomArray(TEST_SET_LENGTH);

            RLEBitset actual = (RLEBitset)CreateSetFromIndices(indicies, TEST_SET_LENGTH);
            System.IO.FileStream fileWriter = new System.IO.FileStream(@"C:\Development\RLE.bin", System.IO.FileMode.Create);
            actual.Serialize(fileWriter);
            fileWriter.Close();
            fileWriter.Dispose();

            System.IO.FileStream fileReader = new System.IO.FileStream(@"C:\Development\RLE.bin", System.IO.FileMode.Open);
            RLEBitset expected = RLEBitset.Deserialize(fileReader);
            fileReader.Close();
            fileReader.Dispose();

            Assert.AreEqual(actual, expected);
        }
Esempio n. 14
0
 /// <summary>
 /// Creates a Mini-dump in the file specified.
 /// </summary>
 public static void MiniDumpToFile(string fileToDump)
 {
     System.IO.FileStream fsToDump = null;
     if (System.IO.File.Exists(fileToDump))
     {
         fsToDump = System.IO.File.Open(fileToDump, System.IO.FileMode.Append);
     }
     else
     {
         fsToDump = System.IO.File.Create(fileToDump);
     }
     System.Diagnostics.Process thisProcess = System.Diagnostics.Process.GetCurrentProcess();
     SafeNativeMethods.MiniDumpWriteDump(thisProcess.Handle, thisProcess.Id,
                                         fsToDump.SafeFileHandle.DangerousGetHandle(), Enums.MINIDUMP_TYPE.MiniDumpNormal,
                                         System.IntPtr.Zero, System.IntPtr.Zero, System.IntPtr.Zero);
     thisProcess.Dispose();
     fsToDump.Dispose();
 }
Esempio n. 15
0
        public void Save()
        {
            string cfgPath = "config.txt";

            if (System.IO.File.Exists(cfgPath))
            {
                System.IO.File.Delete(cfgPath);
            }
            System.IO.FileStream f = System.IO.File.Create(cfgPath);
            f.Close();
            f.Dispose();
            string cfg = this.ToJson();

            System.IO.StreamWriter f2 = new System.IO.StreamWriter(cfgPath, true, System.Text.Encoding.UTF8);
            f2.WriteLine(cfg);
            f2.Close();
            f2.Dispose();
        }
Esempio n. 16
0
        public static void GenerateMul()
        {
            try
            {
                string path    = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                string pathMul = path + @"\decimalsMul.php";

                System.IO.FileStream streamMul = System.IO.File.Create(pathMul);
                streamMul.Close();
                streamMul.Dispose();

                System.IO.StreamWriter writterMul = System.IO.File.AppendText(pathMul);
                writterMul.WriteLine("<?php");
                writterMul.WriteLine("$return = array(");

                for (decimal left = 1; left <= 10; left++)
                {
                    for (decimal right = 0.1m; right < 1; right += 0.1m)
                    {
                        decimal resultMul = decimal.Round(left * right, 2, MidpointRounding.AwayFromZero);
                        string  msgMul    =
                            String.Format("{0:0.##############}", left)
                            + ";" + String.Format("{0:0.##############}", right)
                            + ";" + String.Format("{0:0.##############}", resultMul)
                            + ";" + String.Format("{0:0.##############}", 2)
                            + ";" + String.Format("{0:0.##############}", 2);

                        //System.Console.WriteLine("array("+msg.Replace(",",".").Replace(";",",") + "),");
                        writterMul.WriteLine("array(" + msgMul.Replace(",", ".").Replace(";", ",") + "),");
                        writterMul.Flush();
                    }
                }

                writterMul.WriteLine(");");
                writterMul.WriteLine("");
                writterMul.Flush();
                writterMul.Close();
                writterMul.Dispose();
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
Esempio n. 17
0
        void OpenProjectClick(object sender, EventArgs e)
        {
            if (!Saved)
            {
                DialogResult r = MessageBox.Show("Project has been changed. \nSave changes?"
                                                 , "MyProject", MessageBoxButtons.YesNoCancel,
                                                 MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                switch (r)
                {
                case DialogResult.Yes:
                    tsbSaveProject.PerformClick();
                    break;

                case DialogResult.Cancel:
                    return;
                }
            }
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.DefaultExt = ".prj";
            dlg.Filter     = "MyProject files|*.prj|All files|*";
            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            try
            {
                System.Xml.Serialization.XmlSerializer srl = new System.Xml.Serialization.XmlSerializer(typeof(List <Task>));
                System.IO.FileStream file = System.IO.File.OpenRead(dlg.FileName);
                this.model.projects = (List <Task>)srl.Deserialize(file);
                file.Close();
                file.Dispose();
                this.tree.Model = this.model;
                SetNodeState();
                RefreshTree();
                fileName  = System.IO.Path.GetFileName(dlg.FileName);
                filePath  = System.IO.Path.GetDirectoryName(dlg.FileName);
                this.Text = string.Format("MyProject - {0} ({1})", fileName, filePath);
                Saved     = true;
                recentList.AddItem(System.IO.Path.GetFullPath(fileName));
            }
            catch (Exception ex)
            { MessageBox.Show(ex.ToString()); }
        }
Esempio n. 18
0
 /// <summary>
 /// Saves the underlying XML file if it changed.
 /// </summary>
 /// <exception cref="System.ObjectDisposedException">XMLOblect is disposed.</exception>
 public void Save()
 {
     lock (objLock)
     {
         if (disposedValue)
         {
             throw new System.ObjectDisposedException("XMLOblect is disposed.");
         }
         System.IO.MemoryStream outxmlData = new System.IO.MemoryStream();
         doc.Save(outxmlData);
         byte[] OutXmlBytes = outxmlData.ToArray();
         if (Has_changed())
         {
             System.IO.FileStream fstream = System.IO.File.Create(cached_xmlfilename);
             fstream.Write(OutXmlBytes, 0, OutXmlBytes.Length);
             fstream.Dispose();
         }
     }
 }
Esempio n. 19
0
        private long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力

        public void ProcessRequest(HttpContext context)
        {
            //\SMT\OA\考勤管理\2010121702324784503941.JPG
            //string fileName = "123.jpg";//客户端保存的文件名
            if (context.Request.QueryString["filename"] == null)
            {
                return;
            }
            String fileurl = HttpUtility.UrlDecode(context.Request.QueryString["filename"]);
            // string filePath = string.Format(SavePath, fileName.Split('|')[0], fileName.Split('|')[1],  fileName.Split('|')[2]+"\\"+fileName.Split('|')[3]); //context.Server.MapPath("Bubble.jpg");
            string filePath = string.Format(FileConfig.GetCompanyItem(fileurl.Split('\\')[1]).SavePath, fileurl.Split('\\')[1], fileurl.Split('\\')[2], fileurl.Split('\\')[3] + "\\" + fileurl.Split('\\')[4]);

            string saveFileName = fileurl.Split('\\')[5];//保存文件名

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            if (fileInfo.Exists == true)
            {
                byte[] buffer = new byte[ChunkSize];
                context.Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead        = iStream.Length;//获得下载文件的总大小
                context.Response.ContentType = "application/octet-stream";
                //通知浏览器下载文件而不是打开
                context.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8));
                while (dataLengthToRead > 0 && context.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
                    context.Response.OutputStream.Write(buffer, 0, lengthRead);
                    context.Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                iStream.Dispose();
                iStream.Close();
                context.Response.Close();
                context.Response.End();
            }
            else
            {
                System.Web.HttpContext.Current.Response.Write("<script>alert('该文件不存在!');</script>");
            }
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
        }
Esempio n. 20
0
        public void B2SHA1()
        {
            var destHash = "eeea523c2b2dd9415c657556e45f73be993d7979";
            var hash     = BUCommon.Hash.FromString("SHA1", destHash);

            var fe = new BackupLib.FileEncrypt(null);

            BUCommon.Hash filehash  = null;
            byte[]        filebytes = null;
            {
                var strm = new System.IO.FileStream(@"C:\tmp\b2test\cont1\2016\1231-newyears\DSC06560.ARW", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                filehash = fe.hashContents("SHA1", strm);

                strm.Seek(0, System.IO.SeekOrigin.Begin);
                var    mstr = new System.IO.MemoryStream();
                byte[] buff = new byte[8192];
                int    len  = 0;
                while (true)
                {
                    len = strm.Read(buff, 0, buff.Length);
                    if (len > 0)
                    {
                        mstr.Write(buff, 0, len);
                    }
                    if (len == 0)
                    {
                        break;
                    }
                }

                strm.Dispose();
                strm = null;

                filebytes = mstr.ToArray();
                mstr.Dispose();
                mstr = null;
            }

            string b2nethash = B2Net.Utilities.GetSHA1Hash(filebytes);


            Assert.That(hash.base64, Is.EqualTo(filehash.base64));
        }
        public static void LoadStopWords(string path)
        {
            var _filestream = new System.IO.FileStream(path,
                                                       System.IO.FileMode.Open,
                                                       System.IO.FileAccess.Read,
                                                       System.IO.FileShare.ReadWrite);
            var _file = new System.IO.StreamReader(_filestream, System.Text.Encoding.UTF8, true, 128);

            string _word = null;

            while ((_word = _file.ReadLine()) != null)
            {
                m_stopWords.Add(_word);

                int _countSyllable = CountSyllable(_word);

                switch (_countSyllable)
                {
                case 1:
                    m_words1.Remove(_word);
                    break;

                case 2:
                    m_words2.Remove(_word);
                    break;

                case 3:
                    m_words3.Remove(_word);
                    break;

                case 4:
                    m_words4.Remove(_word);
                    break;

                default:
                    m_words4.Remove(_word);
                    break;
                }
            }

            _file.Dispose();
            _filestream.Dispose();
        }
Esempio n. 22
0
 public string FileRead(string sFile)
 {
     try
     {
         string ret = "";
         System.IO.FileStream fs = new System.IO.FileStream(sFile, System.IO.FileMode.Open);
         for (int a = 0; a < fs.Length; a++)
         {
             ret += (char)fs.ReadByte();
         }
         fs.Close(); fs.Dispose();
         while ((ret.Substring(ret.Length - 1) == "\r") || (ret.Substring(ret.Length - 1) == "\n"))
         {
             ret = ret.Substring(0, ret.Length - 1);
         }
         return(ret);
     }
     catch { return(""); }
 }
Esempio n. 23
0
File: Logger.cs Progetto: DevSNP/AAA
 private static void WriteFinal(string strMessage, string strPath)
 {
     try
     {
         if (System.IO.File.Exists(strPath) == false)
         {
             System.IO.FileStream create = System.IO.File.Create(strPath);
             create.Close();
             create.Dispose();
         }
         System.IO.StreamWriter stream = new System.IO.StreamWriter(new System.IO.FileStream(strPath, System.IO.FileMode.Append, System.IO.FileAccess.Write));
         stream.WriteLine(System.DateTime.Now.ToString() + " : " + strMessage);
         stream.Close();
         stream.Dispose();
     }
     catch (Exception)
     {
     }
 }
Esempio n. 24
0
        public void CopyFileToClient(string filePath, string clientFilePath, System.Net.IPAddress clientAddress, string networkName, int networkPort)
        {
            System.IO.FileStream serverFile    = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            SystemUtility        clientUtility = (SystemUtility)System.Runtime.Remoting.RemotingServices.Connect(typeof(SystemUtility), string.Format("tcp://{0}:{1}/{2}", clientAddress.GetString(), networkPort, networkName));

            System.IO.FileStream clientFile = clientUtility.CreateFile(clientFilePath);
            byte[] buffer = new byte[1 * 1024 * 1024];
            int    readcount;

            do
            {
                readcount = serverFile.Read(buffer, 0, buffer.Length);
                clientFile.Write(buffer, 0, readcount);
            }while (readcount > 0);
            serverFile.Close();
            clientFile.Close();
            serverFile.Dispose();
            clientFile.Dispose();
        }
Esempio n. 25
0
        private static string PutFile(string remotefile, string localfile)
        {
            string sReturn = "";

            try
            {
                System.IO.FileStream InputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
                try
                {
                    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile);
                    request.Method        = "PUT";
                    request.ContentType   = "application/octet-stream";
                    request.ContentLength = InputBin.Length;
                    System.IO.Stream dataStream = request.GetRequestStream();
                    byte[]           buffer     = new byte[32768];
                    int read;
                    while ((read = InputBin.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        dataStream.Write(buffer, 0, read);
                    }
                    dataStream.Close();
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                    sReturn = response.StatusCode.ToString();
                    if (sReturn != response.StatusDescription)
                    {
                        sReturn += " " + response.StatusDescription;
                    }
                    response.Close();
                }
                catch (Exception ex1)
                {
                    sReturn = ex1.Message;
                }
                InputBin.Close();
                InputBin.Dispose();
            }
            catch (Exception ex2)
            {
                sReturn = ex2.Message;
            }
            return(sReturn);
        }
Esempio n. 26
0
 public static byte[] FileToByteArray(string _FileName)
 {
     byte[] _Buffer = null;
     try
     {
         // Open file for reading
         System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
         System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
         long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
         _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
         _FileStream.Close();
         _FileStream.Dispose();
         _BinaryReader.Close();
     }
     catch
     {
         //
     }
     return _Buffer;
 }
Esempio n. 27
0
        public void Dispose()
        {
            if (IsConnected)
            {
                Debug.Assert(IsConnected == IsDisposed);

                Flush();

                lock (m_rwLock)
                {
                    DoDispose();

                    RowInserted = RowReplaced = RowReplacing = null;
                    RowDeleting = RowDeleted = null;

                    m_dataFile.Dispose();
                    m_dataFile = null;
                }
            }
        }
Esempio n. 28
0
 public static NeuralNetwork Load(string filepath)
 {
     try {
         System.IO.FileStream stream = System.IO.File.Open(filepath, System.IO.FileMode.Open);
         BinaryFormatter      binfs  = new BinaryFormatter();
         NeuralNetwork        nn     = (NeuralNetwork)binfs.Deserialize(stream);
         nn.listeners = new List <NeuralNetworkEventListener>();
         if (nn.learningRule != null)
         {
             nn.learningRule.listeners = new List <LearningEventListener>();
         }
         stream.Flush();
         stream.Close();
         stream.Dispose();
         return(nn);
     } catch (System.Exception e) {
         System.Console.WriteLine(e.Message);
         return(null);
     }
 }
Esempio n. 29
0
File: Log.cs Progetto: sky-tc/U8
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {
            string Dir = Path.Remove(Path.LastIndexOf("\\"), Path.Length - Path.LastIndexOf("\\"));

            if (!System.IO.Directory.Exists(Dir))
            {
                System.IO.Directory.CreateDirectory(Dir);
            }

            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }
Esempio n. 30
0
 void SaveProject()
 {
     SaveNodesState();
     if (!DefineSavePath() && (string.IsNullOrEmpty(fileFullName) || fileFullName.Length < 4))
     {
         return;
     }
     try
     {
         System.Xml.Serialization.XmlSerializer srl = new System.Xml.Serialization.XmlSerializer(typeof(List <Task>));
         System.IO.File.Delete(fileFullName);
         System.IO.FileStream file = System.IO.File.OpenWrite(fileFullName);
         srl.Serialize(file, this.model.projects);
         Saved = true;
         file.Close(); file.Dispose();
         recentList.AddItem(System.IO.Path.GetFullPath(fileFullName));
     }
     catch (Exception ex)
     { MessageBox.Show(ex.ToString()); }
 }
Esempio n. 31
0
        internal async Task <bool> downloadAndSaveAddon(IProgress <taskProgressMsg> progressMessages, HttpClient webConnector)
        {
            try {
                // Download file, save it, create addon directory.
                progressMessages.Report(new taskProgressMsg {
                    currentMsg = "Connecting to Repo..."
                });
                HttpResponseMessage webConnectorRespoonse = await webConnector.GetAsync($"https://github.com/{addonData.authorRepo}/releases/download/{addonData.ReleaseTag}/{addonData.File}-{addonData.FileVersion}.{addonData.Extension}");

                System.IO.FileStream fs = new System.IO.FileStream($"{rootDir}/data/_{addonData.File}-{addonData.Unicode}-{addonData.FileVersion}.{addonData.Extension}", System.IO.FileMode.Create);
                progressMessages.Report(new taskProgressMsg {
                    currentMsg = "Saving addon..."
                });
                await webConnectorRespoonse.Content.CopyToAsync(fs); fs.Close(); fs.Dispose();
                webConnectorRespoonse.Dispose();
                progressMessages.Report(new taskProgressMsg {
                    currentMsg = "Addon saved..."
                });

                string localAddonDataDir             = addonData.File;
                addonInstallerOverride addonOverride = addonInstallerOverrides.FirstOrDefault(x => x.filename == addonData.File && x.fileVersion == addonData.FileVersion && x.whichRepo == addonData.whichRepo);
                if (addonOverride != null)
                {
                    if (!string.IsNullOrEmpty(addonOverride.addonDirectoryOverride))
                    {
                        localAddonDataDir = addonOverride.addonDirectoryOverride;
                    }                                                                                                                              // Currently, only have a directory override
                }

                if (!System.IO.Directory.Exists($"{rootDir}/addons/{localAddonDataDir}"))
                {
                    System.IO.Directory.CreateDirectory($"{rootDir}/addons/{localAddonDataDir}");
                }
                return(true);
            } catch (Exception ex) {
                progressMessages.Report(new taskProgressMsg {
                    currentMsg = "Download and Save Addon Error", exceptionContent = ex, showAsPopup = true
                });
                return(false);
            }
        } // end downloadAndSaveAddon
Esempio n. 32
0
 private static IResult NewMethod(string path, ref System.IO.FileStream fileStream)
 {
     try
     {
         fileStream = System.IO.File.Open(path,
                                          System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
         return(new ComparisonResult(ComparisonResultIndicate.not_equal));
     }
     catch (System.IO.IOException)
     {
         return(new ComparisonResult(ComparisonResultIndicate.equal));
     }
     finally
     {
         if (fileStream != null)
         {
             fileStream.Close();
             fileStream.Dispose();
         }
     }
 }
Esempio n. 33
0
 /// <summary>
 /// 保存备注日志
 /// </summary>
 public void SaveLog()
 {
     if (noLogFile)
     {
         return;
     }
     try
     {
         using (System.IO.FileStream fs = new System.IO.FileStream(GetFileName(), System.IO.FileMode.Create))
         {
             byte[] bs = Encoding.UTF8.GetBytes(_sbLog.ToString().ToCharArray());
             fs.Write(bs, 0, bs.Length);
             fs.Flush();
             fs.Close();
             fs.Dispose();
         }
     }
     catch
     {
     }
 }
Esempio n. 34
0
        private static void SaveRtToFile(string fileName, RenderTexture target)
        {
            var oldActive = RenderTexture.active;

            RenderTexture.active = target;

            Texture2D png = new Texture2D(target.width, target.height, cSaveFormat, false, false);

            png.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0);
            byte[] bytes = png.EncodeToPNG();

            System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            try {
                stream.Write(bytes, 0, bytes.Length);
            } finally {
                stream.Dispose();
            }

            RenderTexture.active = oldActive;
            GameObject.DestroyImmediate(png);
        }
Esempio n. 35
0
 /// <summary>
 /// Copy a file from a remote directory to a local directory
 /// </summary>
 /// <param name="SourceFilefullName">The remote file name</param>
 /// <param name="DestinationFileFullName">The destination local directory</param>
 public void Read(String SourceFileFullName, String DestinationFileFullName)
 {
     System.IO.Stream fs = null;
     try
     {
         if (System.IO.File.Exists(DestinationFileFullName))
         {
             System.IO.File.Delete(DestinationFileFullName);
         }
         fs = new System.IO.FileStream(DestinationFileFullName, System.IO.FileMode.CreateNew);
         Read(SourceFileFullName, ref fs);
     }
     finally
     {
         if (fs != null)
         {
             fs.Close();
             fs.Dispose();
         }
     }
 }
Esempio n. 36
0
        public MainWindow()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            InitializeComponent();
            context          = new DataContext();
            this.DataContext = context;


            string path = System.IO.Path.GetDirectoryName(AppSettings.Default.CoupleFile);

            if (!System.IO.Directory.Exists(path))
            {
                System.Windows.MessageBox.Show(String.Format("The path '{0}' does not exists.\nThis is where the offline couple data will be saved.\nPlease create it or change the configuration.", path), "Configuration error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            string tempFile = System.IO.Path.Combine(path, System.IO.Path.GetTempFileName());

            try
            {
                System.IO.FileStream temp = System.IO.File.Open(tempFile, System.IO.FileMode.Create);
                temp.Dispose();
                System.IO.File.Delete(tempFile);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(String.Format("The path '{0}' could not be written to.\nThis is where the offline couple data will be saved.\nPlease allow write access to it or change the configuration.", path), "Configuration error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            LoadWDSFCouples();
            context.LoadParticipants(AppSettings.Default.ParticipantsFile);
            var thread = new System.Threading.Thread(SocketReceiveThread);

            thread.IsBackground = true;
            thread.Start();

            Next_Click(null, null);
            // Let's show some statistics
            Statistics.Content = String.Format("Downloaded: {0}, {1} couples in the local database", context.DownloadDate.ToShortDateString(), context.WDSF_Couples.Count());
        }
 private static string PutFile(string remotefile,string localfile)
 {
     string sReturn = "";
     try
     {
         System.IO.FileStream InputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
         try
         {
             System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile);
             request.Method = "PUT";
             request.ContentType = "application/octet-stream";
             request.ContentLength = InputBin.Length;
             System.IO.Stream dataStream = request.GetRequestStream();
             byte[] buffer = new byte[32768];
             int read;
             while ((read = InputBin.Read(buffer, 0, buffer.Length)) > 0)
             {
                 dataStream.Write(buffer, 0, read);
             }
             dataStream.Close();
             System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
             sReturn = response.StatusCode.ToString();
             if (sReturn != response.StatusDescription)
                 sReturn += " " + response.StatusDescription;
             response.Close();
         }
         catch (Exception ex1)
         {
             sReturn = ex1.Message;
         }
         InputBin.Close();
         InputBin.Dispose();
     }
     catch (Exception ex2)
     {
         sReturn = ex2.Message;
     }
     return sReturn;
 }
Esempio n. 38
0
            /// <summary>
            /// Function to get byte array from a file
            /// </summary>
            /// <param name="fileName">File name to get byte array</param>
            /// <returns>Byte Array</returns>
            public static byte[] FileToByteArray(string fileName)
            {
                byte[] buffer;

                // Open file for reading
                var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                using (var binaryReader = new System.IO.BinaryReader(fileStream))
                {
                    var totalBytes = new System.IO.FileInfo(fileName).Length;

                    // read entire file into buffer
                    buffer = binaryReader.ReadBytes((Int32)totalBytes);

                    // close file reader
                    fileStream.Close();
                    fileStream.Dispose();
                    binaryReader.Close();
                }

                return buffer;
            }
Esempio n. 39
0
		public static BplusTreeBytes Initialize(string treefileName, string blockfileName, int KeyLength) 
		{
			System.IO.Stream treefile = null;
			System.IO.Stream blockfile = null;

			try
			{
				treefile = new System.IO.FileStream(treefileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);
				blockfile = new System.IO.FileStream(blockfileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);

				return Initialize(treefile, blockfile, KeyLength);
			}
			catch(Exception ex)
			{
				if(treefile != null)
					treefile.Dispose();

				if(blockfile != null)
					blockfile.Dispose();

				throw ex;
			}
		}
Esempio n. 40
0
 void context_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
 {
     if (e.ClickedItem.Name == "Settings") // если имя пункта меню равно...
     {
         Setting set = new Setting();
         set.Show();
     }
     if (e.ClickedItem.Name == "Exit")
     {
         if (vars.VARS.ExitVK)
         {
             WebBrowser web = new WebBrowser();
             web.Navigate("http://m.vkontakte.ru/logout");
             string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
             foreach (string currentFile in theCookies) // удаляем cookies с данными авторизации
             {
                 try
                 {
                     if (currentFile.IndexOf("login.vk") != -1 || currentFile.IndexOf("vkontakte") != -1)
                         System.IO.File.Delete(currentFile);
                 }
                 catch (Exception exe)
                 {
                     GeneralMethods.WriteError(exe.Source, exe.Message, exe.TargetSite);
                 }
             }
         }
         if (vars.VARS.SaveSettings) // если надо, то сохраняем настройки
         {
             if (vars.VARS.Frequency) // если включена настройка сортировки по частоте
             {
                 try
                 {
                     System.IO.FileStream stream = new System.IO.FileStream(vars.VARS.Directory + "frequency.dat", System.IO.FileMode.Create, System.IO.FileAccess.Write); // Открываем файл с частотой исользования контактов
                     System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, Encoding.UTF8);
                     foreach (uint id in vars.VARS.FrequencyUse.Keys)
                     {
                         writer.Write(id);
                         writer.Write(":");
                         writer.WriteLine(vars.VARS.FrequencyUse[id]);
                         writer.Flush();
                     }
                     writer.Close();
                     writer.Dispose();
                     stream.Dispose();
                 }
                 catch (Exception exe)
                 {
                     GeneralMethods.WriteError(exe.Source, exe.Message, exe.TargetSite);
                 }
             }
         }
         else // если не сохраняем настройки, то удаляем ранее созданный файл
         {
             try
             {
                 System.IO.File.Delete(vars.VARS.Directory + "settings.cfg");
             }
             catch
             {
             }
         }
         Application.Exit();
     }
 }
Esempio n. 41
0
		public static BplusTreeBytes ReOpen(string treefileName, string blockfileName, System.IO.FileAccess access) 
		{
			System.IO.Stream treefile = null;
			System.IO.Stream blockfile = null;

			try
			{
				treefile = new System.IO.FileStream(treefileName, System.IO.FileMode.Open, access);
				blockfile = new System.IO.FileStream(blockfileName, System.IO.FileMode.Open, access);

				return ReOpen(treefile, blockfile);
			}
			catch (System.Exception ex)
			{
				if(treefile != null)
					treefile.Dispose();

				if(blockfile != null)
					blockfile.Dispose();

				throw ex;
			}
		}
Esempio n. 42
0
 /// <summary>
 /// Loads a quadtree from a file
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public static QuadTree FromFile(string filename)
 {
     System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open,System.IO.FileAccess.Read);
     System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
     if (br.ReadDouble() != INDEXFILEVERSION) //Check fileindex version
     {
         fs.Close();
         fs.Dispose();
         throw new ObsoleteFileFormatException("Invalid index file version. Please rebuild the spatial index by either deleting the index");
     }
     QuadTree node = ReadNode(0, ref br);
     br.Close();
     fs.Close();
     return node;
 }
Esempio n. 43
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (vars.VARS.ExitOnCloser)
     {
         if (vars.VARS.ExitVK)
         {
             WebBrowser web = new WebBrowser();
             web.Navigate("http://m.vkontakte.ru/logout");
             string[] theCookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
             foreach (string currentFile in theCookies) // удаляем cookies с данными авторизации
             {
                 try
                 {
                     if (currentFile.IndexOf("login.vk") != -1 || currentFile.IndexOf("vkontakte") != -1)
                         System.IO.File.Delete(currentFile);
                 }
                 catch (Exception exe)
                 {
                     GeneralMethods.WriteError(exe.Source, exe.Message, exe.TargetSite);
                 }
             }
         }
         if (vars.VARS.SaveSettings) // если сохраняем настройки
         {
             if (vars.VARS.Frequency) // если надо, то записываем частоту использования
             {
                 try
                 {
                     System.IO.FileStream stream = new System.IO.FileStream(vars.VARS.Directory + "frequency.dat", System.IO.FileMode.Create, System.IO.FileAccess.Write);
                     System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, Encoding.UTF8);
                     foreach (uint id in vars.VARS.FrequencyUse.Keys)
                     {
                         writer.Write(id);
                         writer.Write(":");
                         writer.WriteLine(vars.VARS.FrequencyUse[id]);
                         writer.Flush();
                     }
                     writer.Close();
                     writer.Dispose();
                     stream.Dispose();
                 }
                 catch (Exception exe)
                 {
                     GeneralMethods.WriteError(exe.Source, exe.Message, exe.TargetSite);
                 }
             }
         }
         else // иначе....
         {
             try
             { // удаляем файл настроек
                 System.IO.File.Delete(vars.VARS.Directory + "settings.cfg");
             }
             catch (Exception exe)
             {
                 GeneralMethods.WriteError(exe.Source, exe.Message, exe.TargetSite);
             }
         }
     }
     else // если на крестик указано в настройках сворачивать в трей
     {
         if (e.CloseReason != CloseReason.ApplicationExitCall &&
             e.CloseReason != CloseReason.FormOwnerClosing &&
             e.CloseReason != CloseReason.TaskManagerClosing &&
             e.CloseReason != CloseReason.WindowsShutDown)
         {
             e.Cancel = true;
             this.Hide();
             //this.ShowInTaskbar = false;
             notifyIcon1.Visible = true;
         }
     }
 }
Esempio n. 44
0
 private void CreateXMLDocument(string filePath)
 {
     //XmlTextWriter xtw = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
     System.IO.FileStream fs = new System.IO.FileStream(configFile, System.IO.FileMode.Create);
     XmlTextWriter xtw = new XmlTextWriter(fs, System.Text.Encoding.UTF8);
     xtw.WriteStartDocument();
     xtw.WriteStartElement("files");
     xtw.WriteEndDocument();
     xtw.Close();
     fs.Close();
     fs.Dispose();
 }
        private void ParseFile(string filename, uint depth, ref System.Collections.Generic.List<string> outputfiles)
        {
            SFWorkflow.WFFileType.FileType type = SFWorkflow.WFFileType.GetFileType(filename);
            if (type == SFWorkflow.WFFileType.FileType.OlePowerPoint)
            {
                uint fileidx = 0;

                System.Collections.Generic.List<string> pptfiles = new System.Collections.Generic.List<string>();
                DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader ssr = new DIaLOGIKa.b2xtranslator.StructuredStorage.Reader.StructuredStorageReader(filename);
                DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument ppt = new DIaLOGIKa.b2xtranslator.PptFileFormat.PowerpointDocument(ssr);
                foreach (uint persistId in ppt.PersistObjectDirectory.Keys)
                {
                    UInt32 offset = ppt.PersistObjectDirectory[persistId];
                    ppt.PowerpointDocumentStream.Seek(offset, System.IO.SeekOrigin.Begin);
                    DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom obj = DIaLOGIKa.b2xtranslator.OfficeDrawing.Record.ReadRecord(ppt.PowerpointDocumentStream) as DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleObjStgAtom;
                    if (obj != null)
                    {
                        string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName));
                        if (!System.IO.Directory.Exists(filedir))
                            System.IO.Directory.CreateDirectory(filedir);
                        if (System.IO.Directory.Exists(filedir))
                        {
                            byte[] data = obj.DecompressData();
                            System.IO.MemoryStream ms = new System.IO.MemoryStream(data);

                            SFWorkflow.WFFileType.FileType oletype = SFWorkflow.WFFileType.GetOleFileType(data);
                            if (oletype == WFFileType.FileType.OlePackage || oletype == WFFileType.FileType.OleContents)
                            {
                                using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(ms))
                                {
                                    WriteStorage(cf.RootStorage, filedir, depth, ref pptfiles);
                                }
                            }
                            else
                            {
                                string filenm = String.Format("{0}\\pptembed{1}", filedir, fileidx);
                                using (System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                                {
                                    byte[] buffer = new byte[1024];
                                    int len;
                                    while ((len = ms.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fs.Write(buffer, 0, len);
                                    }
                                    pptfiles.Add(filenm);
                                }
                                fileidx++;
                                ms.Close();
                                ms.Dispose();
                            }
                        }
                    }
                }
            #if false
                foreach (DIaLOGIKa.b2xtranslator.PptFileFormat.ExOleEmbedContainer ole in ppt.OleObjects.Values)
                {
                    string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, diridx++);
                    if (!System.IO.Directory.Exists(filedir))
                        System.IO.Directory.CreateDirectory(filedir);
                    if (System.IO.Directory.Exists(filedir))
                    {
                        string filenm = String.Format("{0}\\pptembed{1}", filedir, ole.SiblingIdx);
                        try
                        {
                            System.IO.FileStream fss = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            byte[] data = ole.stgAtom.DecompressData();
                            fss.Write(data, 0, data.Length);
                            fss.Flush();
                            fss.Close();
                            fss.Dispose();

                            pptfiles.Add(filenm);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            #endif
                foreach (DIaLOGIKa.b2xtranslator.OfficeDrawing.Record record in ppt.PicturesContainer._pictures.Values) //.Where(x => x.TypeCode == 0xF01C || x.TypeCode == 0xF01D || x.TypeCode == 0xF01E || x.TypeCode == 0xF01F || x.TypeCode == 0xF029 || x.TypeCode == 0xF02A))
                {
                    string filedir = string.Format("{0}\\{1}", System.IO.Directory.GetParent(filename).FullName, "PPTPictures"); //, SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(filename).FullName));
                    if (!System.IO.Directory.Exists(filedir))
                        System.IO.Directory.CreateDirectory(filedir);
                    if (System.IO.Directory.Exists(filedir))
                    {
                        string extension = string.Empty;
                        int skip = 0;
                        switch (record.TypeCode)
                        {
                            case 0xF01A:
                                extension = ".emf";
                                break;

                            case 0xF01B:
                                extension = ".wmf";
                                break;

                            case 0xF01C:
                                extension = ".pict";
                                break;

                            case 0xF01D:
                            case 0xF02A:
                                extension = ".jpg";
                                skip = 17;
                                break;

                            case 0xF01E:
                                extension = ".png";
                                skip = 17;
                                break;

                            case 0xF01F:
                                extension = ".dib";
                                break;

                            case 0xF029:
                                extension = ".tiff";
                                break;
                        }
                        string filenm = String.Format("{0}\\pptembed{1}{2}", filedir, fileidx++, extension);
                        using(System.IO.FileStream fs = new System.IO.FileStream(filenm, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                        {
                            // need to skip 17 byte header in raw data stream
                            byte[] data = ((extension == ".emf" || extension == ".wmf")) ? ((DIaLOGIKa.b2xtranslator.OfficeDrawing.MetafilePictBlip)record).Decrompress() : record.RawData.Skip(skip).ToArray();
                            fs.Write(data, 0, data.Length);
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();

                            pptfiles.Add(filenm);
                        }
                    }
                }
                ssr.Close();
                ssr.Dispose();
                outputfiles.AddRange(pptfiles);
                depth--;
                if (depth > 0)
                {
                    foreach(string fn in pptfiles)
                        ParseFile(fn, depth, ref outputfiles);
                }
            }
            else
            {
                using (OpenMcdf.CompoundFile cf = new OpenMcdf.CompoundFile(filename))
                {
                    WriteStorage(cf.RootStorage, System.IO.Directory.GetParent(filename).FullName, depth, ref outputfiles);
                }
            }
        }
Esempio n. 46
0
 public void SaveFile(UploadFileModel UploadFile, out string strFilePath)
 {
     // Store File to File System
     //string strVirtualPath = System.Configuration.ConfigurationManager.AppSettings["FileUploadLocation"].ToString();//权限系统没有文件路径配置
     string strNewFileName = string.Empty;
     string strVirtualPath = "/UploadedFiles/";
     if (!string.IsNullOrWhiteSpace(UploadFile.FileName))
     {
         strNewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + UploadFile.FileName.Substring(UploadFile.FileName.LastIndexOf("."));
     }
     string strPath = System.Web.HttpContext.Current.Server.MapPath(strVirtualPath) + strNewFileName;
     if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(strVirtualPath)) == false)
     {
         System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(strVirtualPath));
     }
     System.IO.FileStream FileStream = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
     FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);
     FileStream.Close();
     FileStream.Dispose();
     strFilePath = strVirtualPath + strNewFileName;
 }
Esempio n. 47
0
        // GET /api/music/5
        public HttpResponseMessage Get(Guid id, string play)
        {
            string musicPath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3";
            if (System.IO.File.Exists(musicPath))
            {
                HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                System.IO.FileStream stream = new System.IO.FileStream(musicPath, System.IO.FileMode.Open);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                ms.SetLength(stream.Length);
                stream.Read(ms.GetBuffer(), 0, (int)stream.Length);
                ms.Flush();
                stream.Close();
                stream.Dispose();
                result.Content = new StreamContent(ms);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("audio/mpeg");
                return result;
            }
            else
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
            }
        }
Esempio n. 48
0
        private void button2_Click(object sender, EventArgs e)
        {
            string url = "http://stream11.qqmusic.qq.com/30462600.mp3";
            //stream18.qqmusic.qq.com /30668288.mp3

            ///30668288.mp3
            ///http://stream11.qqmusic.qq.com/30668288.mp3


            string filename = @"c:\a.mp3";
            System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            Myrq.Referer = "";
            Myrq.Headers.Add("Cache-Control: no-cache");
            Myrq.Headers.Add("Down-Param: uin=1234567&qqkey=&downkey=&&");
            Myrq.Headers.Add("Cookie: qqmusic_uin=1234567; qqmusic_key=; qqmusic_privatekey=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA; qqmusic_fromtag=11;  ");
            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
            long totalBytes = myrp.ContentLength;
            int Maximum = (int)totalBytes;
            int starttime = System.DateTime.Now.Second;
            System.IO.Stream st = myrp.GetResponseStream();
            System.IO.Stream so = new System.IO.FileStream(@filename, System.IO.FileMode.Create);
            long totalDownloadedByte = 0;
            long lasttotalDownloadedByte = 0;
            byte[] by = new byte[4096];
            int osize = st.Read(by, 0, (int)by.Length);
            while (osize > 0)
            {

                totalDownloadedByte = osize + totalDownloadedByte;
                //System.Windows.Forms.Application.DoEvents(); //不加多线程用这个临时调试
                int endtime = System.DateTime.Now.Second;

                if ((endtime - starttime) >= 1)
                {
                    Console.Write("AAA");
                }
                so.Write(by, 0, osize);
                if (Maximum != 0)
                {

                }
                osize = st.Read(by, 0, (int)by.Length);


            }
            so.Close();
            so.Dispose();
            st.Close();
            st.Dispose();

        }
Esempio n. 49
0
        public virtual void OnHandleInput()
        {
            if (_input.KeysPressed.Count != 0)
            {
                switch (_input.KeysPressed[0])
                {
                    case Keys.Escape:
                    case Keys.Q:
                        Graphics.Form.Close();
                        return;
                    case Keys.F3:
                        IsDebugDrawEnabled = !IsDebugDrawEnabled;
                        break;
                    case Keys.F8:
                        Input.ClearKeyCache();
                        LibraryManager.ExitWithReload = true;
                        Graphics.Form.Close();
                        break;
                    case Keys.F11:
                        Graphics.IsFullScreen = !Graphics.IsFullScreen;
                        break;
                    case (Keys.Control | Keys.F):
                        const int maxSerializeBufferSize = 1024 * 1024 * 5;
                        DefaultSerializer serializer = new DefaultSerializer(maxSerializeBufferSize);
                        World.Serialize(serializer);

                        byte[] dataBytes = new byte[serializer.CurrentBufferSize];
                        System.Runtime.InteropServices.Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length);

                        System.IO.FileStream file = new System.IO.FileStream("world.bullet", System.IO.FileMode.Create);
                        file.Write(dataBytes, 0, dataBytes.Length);
                        file.Dispose();
                        break;
                    case Keys.G:
                        //shadowsEnabled = !shadowsEnabled;
                        break;
                    case Keys.Space:
                        ShootBox(_freelook.Eye, GetRayTo(_input.MousePoint, _freelook.Eye, _freelook.Target, Graphics.FieldOfView));
                        break;
                    case Keys.Return:
                        ClientResetScene();
                        break;
                }
            }

            if (_input.MousePressed != MouseButtons.None)
            {
                Vector3 rayTo = GetRayTo(_input.MousePoint, _freelook.Eye, _freelook.Target, Graphics.FieldOfView);

                if (_input.MousePressed == MouseButtons.Right)
                {
                    if (_world != null)
                    {
                        Vector3 rayFrom = _freelook.Eye;

                        ClosestRayResultCallback rayCallback = new ClosestRayResultCallback(ref rayFrom, ref rayTo);
                        _world.RayTestRef(ref rayFrom, ref rayTo, rayCallback);
                        if (rayCallback.HasHit)
                        {
                            RigidBody body = rayCallback.CollisionObject as RigidBody;
                            if (body != null)
                            {
                                if (!(body.IsStaticObject || body.IsKinematicObject))
                                {
                                    pickedBody = body;
                                    pickedBody.ActivationState = ActivationState.DisableDeactivation;

                                    Vector3 pickPos = rayCallback.HitPointWorld;
                                    Vector3 localPivot = Vector3.TransformCoordinate(pickPos, Matrix.Invert(body.CenterOfMassTransform));

                                    if (_input.KeysDown.Contains(Keys.ShiftKey))
                                    {
                                        Generic6DofConstraint dof6 = new Generic6DofConstraint(body, Matrix.Translation(localPivot), false)
                                        {
                                            LinearLowerLimit = Vector3.Zero,
                                            LinearUpperLimit = Vector3.Zero,
                                            AngularLowerLimit = Vector3.Zero,
                                            AngularUpperLimit = Vector3.Zero
                                        };

                                        _world.AddConstraint(dof6);
                                        pickConstraint = dof6;

                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 0);
                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 1);
                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 2);
                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 3);
                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 4);
                                        dof6.SetParam(ConstraintParam.StopCfm, 0.8f, 5);

                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 0);
                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 1);
                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 2);
                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 3);
                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 4);
                                        dof6.SetParam(ConstraintParam.StopErp, 0.1f, 5);
                                    }
                                    else
                                    {
                                        Point2PointConstraint p2p = new Point2PointConstraint(body, localPivot);
                                        _world.AddConstraint(p2p);
                                        pickConstraint = p2p;
                                        p2p.Setting.ImpulseClamp = 30;
                                        //very weak constraint for picking
                                        p2p.Setting.Tau = 0.001f;
                                        /*
                                        p2p.SetParam(ConstraintParams.Cfm, 0.8f, 0);
                                        p2p.SetParam(ConstraintParams.Cfm, 0.8f, 1);
                                        p2p.SetParam(ConstraintParams.Cfm, 0.8f, 2);
                                        p2p.SetParam(ConstraintParams.Erp, 0.1f, 0);
                                        p2p.SetParam(ConstraintParams.Erp, 0.1f, 1);
                                        p2p.SetParam(ConstraintParams.Erp, 0.1f, 2);
                                        */
                                    }

                                    oldPickingDist = (pickPos - rayFrom).Length;
                                }
                            }
                        }
                        rayCallback.Dispose();
                    }
                }
            }
            else if (_input.MouseReleased == MouseButtons.Right)
            {
                RemovePickingConstraint();
            }

            // Mouse movement
            if (_input.MouseDown == MouseButtons.Right)
            {
                if (pickConstraint != null)
                {
                    Vector3 newRayTo = GetRayTo(_input.MousePoint, _freelook.Eye, _freelook.Target, Graphics.FieldOfView);

                    if (pickConstraint.ConstraintType == TypedConstraintType.D6)
                    {
                        Generic6DofConstraint pickCon = pickConstraint as Generic6DofConstraint;

                        //keep it at the same picking distance
                        Vector3 rayFrom = _freelook.Eye;
                        Vector3 dir = newRayTo - rayFrom;
                        dir.Normalize();
                        dir *= oldPickingDist;
                        Vector3 newPivotB = rayFrom + dir;

                        Matrix tempFrameOffsetA = pickCon.FrameOffsetA;
                        tempFrameOffsetA.M41 = newPivotB.X;
                        tempFrameOffsetA.M42 = newPivotB.Y;
                        tempFrameOffsetA.M43 = newPivotB.Z;
                        pickCon.SetFrames(tempFrameOffsetA, pickCon.FrameOffsetB);
                    }
                    else
                    {
                        Point2PointConstraint pickCon = pickConstraint as Point2PointConstraint;

                        //keep it at the same picking distance
                        Vector3 rayFrom = _freelook.Eye;
                        Vector3 dir = newRayTo - rayFrom;
                        dir.Normalize();
                        dir *= oldPickingDist;
                        pickCon.PivotInB = rayFrom + dir;
                    }
                }
            }
        }
Esempio n. 50
0
        public static void OpenFileWithDefaultApplication(string fullfileLocationAndName, byte[] data)
        {
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(fullfileLocationAndName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
                fs.Write(data, 0, data.Length - 1);
                fs.Close();
                fs.Dispose();

                System.Diagnostics.Process.Start(fullfileLocationAndName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error opening the file: " + fullfileLocationAndName +
                    "\r\n\r\n The following is the error message: " + ex.Message);
            }
        }
Esempio n. 51
0
        private void UpdateTzToDB()
        {
            bool successToLoadData = false;

                System.Collections.Generic.List<string> Parameters = new List<string>();
                System.Collections.Generic.List<string> DataFromTextBox = new List<string>();

                string cmdName = "UPDATE USP_TZ_DATA SET ";

                try
                {
                    for (int i = 0; i < this.tabPage1.Controls.Count; i++)
                    {
                        if (this.tabPage1.Controls[i].Controls.Count == 0)
                        {

                            if ((this.tabPage1.Controls[i].GetType() == typeof(ComboBox)))
                            {
                                cmdName += " " + this.tabPage1.Controls[i].Name + " = :" + this.tabPage1.Controls[i].Name + ",";
                                Parameters.Add(this.tabPage1.Controls[i].Name);
                                DataFromTextBox.Add(PriemSpisanie.IsNullParametr((ComboBox)this.tabPage1.Controls[i]));

                            }
                            else if ((this.tabPage1.Controls[i].GetType() == typeof(TextBox)))
                            {
                                cmdName += " " + this.tabPage1.Controls[i].Name + " = :" + this.tabPage1.Controls[i].Name + ",";
                                Parameters.Add(this.tabPage1.Controls[i].Name);
                                DataFromTextBox.Add(PriemSpisanie.IsNullParametr((TextBox)this.tabPage1.Controls[i]));

                            }
                            else if (this.tabPage1.Controls[i].GetType() == typeof(DateTimePicker))
                            {
                                cmdName += " " + this.tabPage1.Controls[i].Name + " = to_date(:" + this.tabPage1.Controls[i].Name + ",'DD.MM.YYYY hh24:mi:ss'),";
                                Parameters.Add(this.tabPage1.Controls[i].Name);
                                DataFromTextBox.Add(((DateTimePicker)(this.tabPage1.Controls[i])).Value.ToString());
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else if (this.tabPage1.Controls[i].Controls.Count > 0)
                        {
                            UpdateDBCycle(this.tabPage1.Controls[i], ref cmdName, ref  Parameters, ref  DataFromTextBox);
                        }
                    }

                    for (int i = 0; i < this.tabPage2.Controls.Count; i++)
                    {
                        if (this.tabPage2.Controls[i].Controls.Count == 0)
                        {

                            if ((this.tabPage2.Controls[i].GetType() == typeof(ComboBox)))
                            {

                                cmdName += " " + this.tabPage2.Controls[i].Name + " = :" + this.tabPage2.Controls[i].Name + ",";
                                Parameters.Add(this.tabPage2.Controls[i].Name);
                                DataFromTextBox.Add(PriemSpisanie.IsNullParametr((ComboBox)this.tabPage2.Controls[i]));
                            }
                            else if ((this.tabPage2.Controls[i].GetType() == typeof(TextBox)))
                            {
                                cmdName += " " + this.tabPage2.Controls[i].Name + " = :" + this.tabPage2.Controls[i].Name + ",";
                                Parameters.Add(this.tabPage2.Controls[i].Name);
                                DataFromTextBox.Add(PriemSpisanie.IsNullParametr((TextBox)this.tabPage2.Controls[i]));

                            }
                            else if (this.tabPage2.Controls[i].GetType() == typeof(DateTimePicker))
                            {
                                cmdName += " " + this.tabPage2.Controls[i].Name + " = to_date(:" + this.tabPage2.Controls[i].Name + ",'DD.MM.YYYY hh24:mi:ss'),";
                                Parameters.Add(this.tabPage2.Controls[i].Name);
                                DataFromTextBox.Add(((DateTimePicker)(this.tabPage2.Controls[i])).Value.ToString());
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else if ((this.tabPage2.Controls[i].Controls.Count > 0) && ((String.Compare(this.tabPage2.Controls[i].Name, "panel45")) != 0))
                        {
                            UpdateDBCycle(this.tabPage2.Controls[i], ref cmdName, ref  Parameters, ref  DataFromTextBox);
                        }
                    }
                    cmdName = cmdName.Remove(cmdName.Length - 1);

                    cmdName += " WHERE ID_DOC = '" + number + "'";

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");

                }

                successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);

                Parameters.Clear();
                DataFromTextBox.Clear();

                for (int i = 1; i < 10; i++)
                {
                    if (successToLoadData == true)
                    {
                        cmdName = "UPDATE USP_TZ_DATA_TP SET NAIM_KOMP = :NAIM_KOMP,OBOZN_KOMP = :OBOZN_KOMP, KOL = :KOL WHERE NUM_PANEL = '" + i.ToString() + "' AND ID_DOC = '" + number +"'";

                        Parameters.Add("NAIM_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel33.Controls.Find(("NAIM_KOMP0" + i.ToString()), true)[0]))));
                        Parameters.Add("OBOZN_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel32.Controls.Find(("OBOZN_KOMP0" + i.ToString()), true)[0]))));
                        Parameters.Add("KOL"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel34.Controls.Find(("KOL0" + i.ToString()), true)[0]))));

                        successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);

                        Parameters.Clear();
                        DataFromTextBox.Clear();
                    }
                }

                for (int i = 10; i < 21; i++)
                {
                    if (successToLoadData == true)
                    {
                        cmdName = "UPDATE USP_TZ_DATA_TP SET NAIM_KOMP = :NAIM_KOMP,OBOZN_KOMP = :OBOZN_KOMP, KOL = :KOL WHERE NUM_PANEL = '" + i.ToString() + "' AND ID_DOC = '" + number + "'";

                        Parameters.Add("NAIM_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel33.Controls.Find(("NAIM_KOMP" + i.ToString()), true)[0]))));
                        Parameters.Add("OBOZN_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel32.Controls.Find(("OBOZN_KOMP" + i.ToString()), true)[0]))));
                        Parameters.Add("KOL"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel34.Controls.Find(("KOL" + i.ToString()), true)[0]))));

                        successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);

                        Parameters.Clear();
                        DataFromTextBox.Clear();
                    }
                }

                if ((BMPIsLoad == 1)||(BMPIsLoad == 3))
                    if ((this.SCETCH1.Image != null) && (successToLoadData == true))
                        using (TemporaryFile tempFile = new TemporaryFile())
                        {

                            this.SCETCH1.Image.Save(tempFile.FilePath.ToString());

                            System.IO.FileStream FileStreamSCETCH1 = new System.IO.FileStream(tempFile.FilePath.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            byte[] SCETCH1InByte = new Byte[FileStreamSCETCH1.Length];
                            FileStreamSCETCH1.Read(SCETCH1InByte, 0, SCETCH1InByte.Length);
                            FileStreamSCETCH1.Close();
                            IDisposable disp = (IDisposable)FileStreamSCETCH1;
                            disp.Dispose();

                            successToLoadData = SQLOracle.BLOBUpdateQuery(("UPDATE USP_TZ_DATA SET SCETCH1 = :SCETCH1 WHERE ID_DOC = '" + number + "'"), "SCETCH1", SCETCH1InByte);
                            FileStreamSCETCH1.Dispose();

                        }
                if ((BMPIsLoad == 2) || (BMPIsLoad == 3))
                    if ((this.SCETCH2.Image != null) && (successToLoadData == true))
                        using (TemporaryFile tempFile = new TemporaryFile())
                        {
                            this.SCETCH2.Image.Save(tempFile.FilePath.ToString());

                            System.IO.FileStream FileStreamBMP = new System.IO.FileStream(tempFile.FilePath.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read);
                            byte[] BMPInByte = new Byte[FileStreamBMP.Length];
                            FileStreamBMP.Read(BMPInByte, 0, BMPInByte.Length);
                            FileStreamBMP.Close();
                            IDisposable disp = (IDisposable)FileStreamBMP;
                            disp.Dispose();

                            successToLoadData = SQLOracle.BLOBUpdateQuery(("UPDATE USP_TZ_DATA SET SCETCH2 = :SCETCH2 WHERE ID_DOC = '" + number + "'"), "SCETCH2", BMPInByte);
                            FileStreamBMP.Dispose();
                        }

                if (successToLoadData == true)
                {
                    MessageBox.Show("Загрузка прошла успешно!");
                }
                else
                {
                    MessageBox.Show("Загрузка прошла неудачно!");
                }
        }
Esempio n. 52
0
        public string UploadFile(string formItemName, string filePath, Dictionary<string, string> othData)
        {
            byte[] beginBuff = Encoding.UTF8.GetBytes("------WebKitFormBoundaryQiOnR7KX03DvV4iK\r\n");
            byte[] endBuff = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundaryQiOnR7KX03DvV4iK--\r\n");
            byte[] centerEndBuff = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundaryQiOnR7KX03DvV4iK\r\n");
            this.Method = Methods.POST;
            InitWebRequest();
            this.webRequest.ContentType = "multipart/form-data; boundary=----WebKitFormBoundaryQiOnR7KX03DvV4iK";
            //this.webRequest.ContentLength = fs.Length + startBuff.Length + endBuff.Length;
            System.IO.Stream stream = webRequest.GetRequestStream();
            stream.Write(beginBuff, 0, beginBuff.Length);//Start

            foreach (var item in othData)
            {
                byte[] textStartBuff = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", item.Key));
                stream.Write(textStartBuff, 0, textStartBuff.Length);
                byte[] text = Encoding.UTF8.GetBytes(item.Value);
                stream.Write(text, 0, text.Length);
                stream.Write(centerEndBuff, 0, centerEndBuff.Length);
            }
            byte[] fileStartBuff = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"" + formItemName + "\"; filename=\"" + System.IO.Path.GetFileName(filePath) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n");

            stream.Write(fileStartBuff, 0, fileStartBuff.Length);
            byte[] readBuff = new byte[1024];
            int len = 0;
            System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
            while ((len = fs.Read(readBuff, 0, readBuff.Length)) > 0)
            {
                stream.Write(readBuff, 0, len);
            }
            fs.Close();
            fs.Dispose();
            stream.Write(endBuff, 0, endBuff.Length);
            System.IO.StreamReader reader = new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream());
            return reader.ReadToEnd();
        }
Esempio n. 53
0
        /// <summary>
        /// Convert a file from source codepage to destination codepage
        /// </summary>
        /// <param name="filename">filename</param>
        /// <param name="destDir">output directory</param>
        /// <param name="sourceCP">source codepage</param>
        /// <param name="destCP">destination codepage</param>
        /// <param name="specialType">SpecialTypes</param>
        /// <param name="outputMetaTag">True=output meta tag</param>
        /// <returns></returns>
        public static bool ConvertFile(string filename, string destDir, int sourceCP, int destCP, SpecialTypes specialType, bool outputMetaTag, byte[] BOM)
        {
            //source file data
            string fileData = "";
            //get the encodings
            Encoding sourceEnc = Encoding.GetEncoding(sourceCP);
            Encoding destEnc   = Encoding.GetEncoding(destCP);
            System.IO.FileStream fw = null;

            //get the output filename
            //john church 05/10/2008 use directory separator char instead of backslash for linux support
            string outputFilename = filename.Substring(filename.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);
            //check if the file exists
            if (!System.IO.File.Exists(filename))
            {
                throw new System.IO.FileNotFoundException(filename);
            }

            try
            {
                //check or create the output directory
                if (!System.IO.Directory.Exists(destDir))
                {
                    System.IO.Directory.CreateDirectory(destDir);
                }

                //check if we need to output meta tags
                if (outputMetaTag)
                {
                    fileData = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + destEnc.WebName + "\" />";
                }

                //check we've got a backslash at the end of the pathname
                //john church 05/10/2008 use directory separator char instead of backslash for linux support
                if (destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) == false)
                    destDir += System.IO.Path.DirectorySeparatorChar;

                //read in the source file
                //john church 09/02/2011 add source encoding parameter to ReadAllText call
                fileData += System.IO.File.ReadAllText(filename, sourceEnc);
                //check for any special cases
                switch (specialType)
                {
                    case SpecialTypes.UnicodeAsDecimal:
                        fileData = ConvertDecimals(fileData);
                        break;
                    case SpecialTypes.None:
                        //do nothing
                        break;
                }
                //put the data into an array
                byte[] bSource = sourceEnc.GetBytes(fileData);
                //do the conversion
                byte[] bDest = System.Text.Encoding.Convert(sourceEnc, destEnc, bSource);
                //write out the file
                fw = new System.IO.FileStream(destDir + outputFilename, System.IO.FileMode.Create);

                if (BOM.Length > 0)
                {
                    fw.Write(BOM, 0, BOM.Length);
                }
                fw.Write(bDest, 0, bDest.Length);
                return true;
            }
            catch (Exception ex)
            {
                //just throw the exception back up
                throw ex;
            }
            finally
            {
                //clean up the stream
                if (fw != null)
                {
                    fw.Close();
                }
                fw.Dispose();
            }
        }
Esempio n. 54
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                if (_TotalBytes % 16 != 0)
                    _bufferReal = new byte[_TotalBytes + 16 - (_TotalBytes % 16)];
                else
                    _bufferReal = new byte[_TotalBytes];

                _Buffer.CopyTo(_bufferReal,0);
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            int toPad;
            if ((_Buffer.Length % 16) != 0)
            {
                toPad = 16 - (_Buffer.Length % 16);
                for (int i = 0; i < toPad; i++)
                {
                    _bufferReal[_Buffer.Length+i] = Convert.ToByte(toPad);

                }
            }
            return _bufferReal;
        }
Esempio n. 55
0
        private void openConfigFile(string FileName)
        {
            System.IO.FileStream fs = null;

            try
            {
                fs = new System.IO.FileStream(FileName, System.IO.FileMode.Open);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                this.settings = (QueryStressSettings)bf.Deserialize(fs);
            }
            catch
            {
                MessageBox.Show("Error loading settings.");
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }

            query_textBox.Text = settings.mainQuery;
            threads_numericUpDown.Value = settings.numThreads;
            iterations_numericUpDown.Value = settings.numIterations;
        }
Esempio n. 56
0
        public void RunNantWhenFailureUsersHaveQuoutesInTheirNames()
        {
            const string ProjectName1 = "NantTest02";

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string CCNetConfigFile = System.IO.Path.Combine("IntegrationScenarios", "NantFailureUsersWithQuote.xml");
            string ProjectStateFile = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

            IntegrationCompleted = new System.Collections.Generic.Dictionary<string, bool>();

            string workingDirectory = "Nant02";

            var ios = new CCNet.Core.Util.IoService();
            ios.DeleteIncludingReadOnlyObjects(workingDirectory);
            System.IO.Directory.CreateDirectory(workingDirectory);

            System.IO.File.Delete(ProjectStateFile);

            string NantBuildFile = @"IntegrationScenarios\Nant.Build";
            var NantExeLocation = "";

#if DEBUG
            NantExeLocation = @"..\..\..\..\Tools\Nant\nant.exe";
#else
            NantExeLocation = @"..\..\Tools\Nant\nant.exe";
#endif
            var configFileData = System.IO.File.ReadAllText(CCNetConfigFile);
            configFileData = configFileData.Replace("WillBeReplacedViaTheTest", NantExeLocation);
            System.IO.File.WriteAllText(CCNetConfigFile, configFileData);

            System.IO.File.Copy(NantBuildFile, System.IO.Path.Combine(workingDirectory, new System.IO.FileInfo(NantBuildFile).Name));



            IntegrationCompleted.Add(ProjectName1, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder)) System.IO.Directory.Delete(IntegrationFolder, true);

            string FailureFileLocation =  System.IO.Path.Combine(workingDirectory, "FailBuild.txt");

            Log("Creating failure file so the build will fail the nant task");
            var ff = new System.IO.FileStream(FailureFileLocation, System.IO.FileMode.CreateNew);
            ff.Close();
            ff.Dispose();


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {

                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.Threading.Thread.Sleep(250); // give time to start

                Log("Forcing build to fail the build");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++) System.Threading.Thread.Sleep(250);
                    Log(" waiting ...");
                }


                Log("Forcing build so it will pass now");

                IntegrationCompleted[ProjectName1] = false;
                System.IO.File.Delete(FailureFileLocation);
                CheckResponse(cruiseServer.ForceBuild(pr1));


                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++) System.Threading.Thread.Sleep(250);
                    Log(" waiting ...");
                }



                // un-subscribe to integration complete 
                cruiseServer.IntegrationCompleted -= new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");

            }

            Log("Checking the data");
            CCNet.Remote.ProjectStatus ps = null;

            // checking data of project 1
            foreach (var p in psr.Projects)
            {
                if (p.Name == ProjectName1) ps = p;
            }

            Assert.AreEqual(ProjectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Success, ps.BuildStatus, "wrong build state for project " + ProjectName1);

        }
        /// <summary>
        /// Reads from ScenDat -> go to a zone and load the floors and walls onto cOuter 
        /// </summary>
        /// <param name="num"></param>
        public void LoadZone(int num)
        {
            System.IO.FileStream fsScenData = new System.IO.FileStream(@"a:\agf5ScenData.dat",System.IO.FileMode.Open);
            fsScenData.Seek(2592,System.IO.SeekOrigin.Begin); // Pacification Fields
            int iFloorByte;
            int iCell=0;
            double dStartX=2500, dStartY=0; // where the West edge starts drawing on the canvas

            double i = dStartX;
            double j = dStartY;
            while(iCell<4096)
            {
                iFloorByte = (short)fsScenData.ReadByte();

                //usByte2 = System.Net.IPAddress.NetworkToHostOrder(usByte2);
                //get which floor this int represents
                //create image with source defined floor and place on screen
                Image imgCell = new Image();
                //if(usByte2<50)
                CroppedBitmap cbReturnedBitmap = GetFloor(iFloorByte);
                if (cbReturnedBitmap == null)
                {
                    imgCell.Visibility = Visibility.Collapsed;
                    i -= 41;
                    j += 28;
                    iCell++;
                    continue;
                }
                imgCell.Tag = (string)iCell.ToString() +" ; "+ i +" ; "+ j;
                imgCell.MouseDown+=iCell2_MouseDown;
                imgCell.Source = cbReturnedBitmap;
                imgCell.Width = 82;
                imgCell.Height = 56;
                MakeTransparent(ref imgCell);
                imgCell.SetValue(Canvas.LeftProperty, i);
                imgCell.SetValue(Canvas.TopProperty,  j);
                cOuter.Children.Add(imgCell);
                i -= 41;
                j += 28;
               iCell++;

                if(iCell%64==0) // if is the beginning of a new column
                {
                    int iWhichCol = iCell / 64;
                    i = dStartX + 41 * iWhichCol;
                    j = dStartY + 28 * iWhichCol;
                }
            }
            //usByte2 = brScenData.ReadUInt16();
            //usByte2 = brScenData.ReadUInt16();
            //MessageBox.Show(usByte2.ToString());
            //brScenData.Dispose();
            fsScenData.Dispose();
        }
Esempio n. 58
0
        private void saveFileDialog1_FileOk(object sender, EventArgs e)
        {
            System.IO.FileStream fs = null;

            try
            {
                fs = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                bf.Serialize(fs, this.settings);
            }
            catch
            {
                MessageBox.Show("Error saving settings.");
            }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }
        }
Esempio n. 59
0
        //================== Сортировки ====================
        /// <summary>
        /// Слияние двух участков одной ячейки первого (он в младшей индексной части) и второго, следующего за ним.
        /// Результирующий массив начинается с начала первого участка. Слияние производится сравнением объектных значений
        /// элементов посредством функции сравнения ComparePO
        /// </summary>
        /// <param name="tel">Тип элемента последовательности</param>
        /// <param name="off1">offset начала первого участка</param>
        /// <param name="number1">длина первого участка</param>
        /// <param name="off2">offset начала второго участка</param>
        /// <param name="number2">длина второго участка</param>
        /// <param name="comparePO">Функция сравнения объектных представлений элементов</param>
        internal void CombineParts(PType tel, long off1, long number1, long off2, long number2, Func<object, object, int> comparePO)
        {
            long pointer_out = off1;
            long pointer_in = off2;
            int size = tel.HeadSize;

            // Используем временный файл
            string tmp_fname = MachineInfo.pathForTmp + "tmp_merge.pac";
            System.IO.FileStream tmp_fs = new System.IO.FileStream(tmp_fname, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
            System.IO.BinaryReader tmp_br = new System.IO.BinaryReader(tmp_fs);

            // Перепишем number1 * size байтов от начальной точки во временный файл (Первую часть)
            this.SetOffset(pointer_out);
            long bytestocopy = number1 * size;
            int buffLen = 8192;
            byte[] buff = new byte[buffLen * size];
            while (bytestocopy > 0)
            {
                int nb = bytestocopy < buff.Length ? (int)bytestocopy : buff.Length;
                this.fs.Read(buff, 0, nb);
                tmp_fs.Write(buff, 0, nb);
                bytestocopy -= nb;
            }
            tmp_fs.Flush();

            // теперь будем сливать массивы
            long cnt1 = 0; // число переписанных элементов первой подпоследовательности
            long cnt2 = 0; // число переписанных элементов второй подпоследовательности
            tmp_fs.Position = 0L; // Установка начальной позиции в файле
            this.SetOffset(pointer_in); // Установка на начало второй части последовательности в ячейке

            System.IO.Stream fs1 = tmp_fs; // Первый поток
            System.IO.Stream fs2 = this.fs; // Второй поток

            // Микробуфера для элементов
            byte[] m_buf1 = new byte[size];
            byte[] m_buf2 = new byte[size];

            // Заполнение микробуферов
            fs1.Read(m_buf1, 0, size);
            fs2.Read(m_buf2, 0, size);
            pointer_in += size;
            // Это чтобы читать P-значения
            System.IO.BinaryReader m_reader1 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf1));
            System.IO.BinaryReader m_reader2 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf2));
            // Текущие объекты
            object val1 = PaCell.GetPO(tel, m_reader1);
            object val2 = PaCell.GetPO(tel, m_reader2);
            // Писать будем в тот же буффер buff, текущее место записи:
            int ind_buff = 0;

            // Слияние!!!
            while (cnt1 < number1 && cnt2 < number2)
            {
                if (comparePO(val1, val2) < 0)
                { // Продвигаем первую подпоследовательность
                    Buffer.BlockCopy(m_buf1, 0, buff, ind_buff, size);
                    cnt1++;
                    if (cnt1 < number1) // Возможен конец
                    {
                        fs1.Read(m_buf1, 0, size);
                        m_reader1.BaseStream.Position = 0;
                        val1 = PaCell.GetPO(tel, m_reader1);
                    }
                }
                else
                { // Продвигаем вторую последовательность
                    Buffer.BlockCopy(m_buf2, 0, buff, ind_buff, size);
                    cnt2++;
                    if (cnt2 < number2) // Возможен конец
                    {
                        this.SetOffset(pointer_in); // Установка на текущее место чтения !!!!!!!!!
                        fs2.Read(m_buf2, 0, size);
                        pointer_in += size;
                        m_reader2.BaseStream.Position = 0;
                        val2 = PaCell.GetPO(tel, m_reader2);
                    }
                }
                ind_buff += size;
                // Если буфер заполнился, его надо сбросить
                if (ind_buff == buff.Length)
                {
                    this.SetOffset(pointer_out);
                    int volume = ind_buff;
                    this.fs.Write(buff, 0, volume);
                    pointer_out += volume;
                    ind_buff = 0;
                }
            }
            // Если в буфере остались данные, их надо сбросить
            if (ind_buff > 0)
            {
                this.SetOffset(pointer_out);
                int volume = ind_buff;
                this.fs.Write(buff, 0, volume);
                pointer_out += volume;
            }
            // Теперь надо переписать остатки
            if (cnt1 < number1)
            {
                this.SetOffset(pointer_out); // Здесь запись ведется подряд, без перемещений головки чтения/записи
                // Сначала запишем уже прочитанную запись
                this.fs.Write(m_buf1, 0, size);
                // а теперь - остальное
                bytestocopy = (number1 - cnt1 - 1) * size;
                while (bytestocopy > 0)
                {
                    int nbytes = buff.Length;
                    if (bytestocopy < nbytes) nbytes = (int)bytestocopy;
                    fs1.Read(buff, 0, nbytes);
                    this.fs.Write(buff, 0, nbytes);
                    bytestocopy -= nbytes;
                }
            }
            else if (cnt2 < number2)
            { // Поскольку в тот же массив, то надо переписать только прочитанный, а остатки массива уже на своем месте
                //this.cell.SetOffset(pointer_out);
                //this.cell.fs.Write(m_buf2, 0, size);
            }
            this.fs.Flush();
            // Закрываем временный файл
            tmp_fs.Dispose();
            // Убираем временный файл
            //File.Delete(tmp_fname); // не убираем, а то он помещается в мусорную корзину, а так - будет переиспользоваться
        }
        public async Task DownloadFileAsync(DriveService service, File f, string path)
        {
            var downloader = new MediaDownloader(service);
            System.IO.FileStream fileStream = null;
            downloader.ChunkSize = DownloadChunkSize;

            try
            {
                fileStream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                var progress = await downloader.DownloadAsync(f.SelfLink, fileStream);

                // updating the modified date
                await service.Files.Touch(f.Id).ExecuteAsync();

                if (progress.Status == DownloadStatus.Completed)
                {
                    Console.WriteLine(path + " was downloaded successfully");
                }
                else
                {
                    Console.WriteLine(Environment.NewLine + "Download {0} was interpreted in the middle. Only {1} were downloaded. ",
                        path, progress.BytesDownloaded);
                }
            }
            catch (GoogleApiException e)
            {
                if (e.HttpStatusCode == HttpStatusCode.Unauthorized)
                {
                    //GoogleWebAuthorizationBroker.Folder = "Drive.Sample";

                    //credential.RefreshTokenAsync(CancellationToken.None).Wait();

                    /*using (var stream = new System.IO.FileStream("client_secrets.json",
                        System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None).Wait();

                    }

                    // Create the service.
                    service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "CloudManagerGD",
                    });*/
                    /*if(retries <= 4)
                    {
                        Thread.Sleep(retries * 1000);
                        this.DownloadFileAsync(service, f, path).Wait();
                        retries++;
                    }
                    else
                    {
                        retries = 0;
                        return;
                    }*/
                    
                }
            }
            catch (System.IO.IOException e)
            {
                if (retries <= 4)
                {
                    Thread.Sleep(retries * 1000);
                    this.DownloadFileAsync(service, f, path).Wait();
                    retries++;
                }
                else
                {
                    retries = 0;
                    return;
                }
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }
        }