Dispose() защищенный Метод

protected Dispose ( bool disposing ) : void
disposing bool
Результат void
Пример #1
1
 /// 获取token,如果存在且没过期,则直接取token
 /// <summary>
 /// 获取token,如果存在且没过期,则直接取token
 /// </summary>
 /// <returns></returns>
 public static string GetExistAccessToken()
 {
     // 读取XML文件中的数据
     string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLToken.xml");
     FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8);
     XmlDocument xml = new XmlDocument();
     xml.Load(str);
     str.Close();
     str.Dispose();
     fs.Close();
     fs.Dispose();
     string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText;
     DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText);
     //如果token过期,则重新获取token
     if (DateTime.Now >= AccessTokenExpires)
     {
         AccessToken mode = Getaccess();
         //将token存到xml文件中,全局缓存
         xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.access_token;
         DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(mode.expires_in);
         xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _AccessTokenExpires.ToString();
         xml.Save(filepath);
         Token = mode.access_token;
     }
     return Token;
 }
Пример #2
0
        public bool PutImageToCache(MemoryStream tile, MapType type, Point pos, int zoom)
        {
            FileStream fs = null;
            try
            {
                string fileName = GetFilename(type, pos, zoom, true);
                fs = new FileStream(fileName, FileMode.Create);
                tile.WriteTo(fs);
                tile.Flush();
                fs.Close();
                fs.Dispose();
                tile.Seek(0, SeekOrigin.Begin);

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error in FilePureImageCache.PutImageToCache:\r\n" + ex.ToString());
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                return false;
            }
        }
Пример #3
0
        private static long _indexcount;//索引个数

        static IpHelper() {
            string filePath = Common.GetMapPath("/App_Data/Site/ipdata.config");
            if (File.Exists(filePath)) {
                try {
                    _ipdatefile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                catch {
                    _ipdatefile.Close();
                    _ipdatefile.Dispose();
                    return;
                }
                _ipdatefile.Position = 0;
                _indexareabegin = ReadByte4();
                _indexareaend = ReadByte4();
                _indexcount = (_indexareaend - _indexareabegin) / LENGTH + 1;

                if (_indexcount > 0) {
                    _state = true;
                }
                else {
                    _ipdatefile.Close();
                    _ipdatefile.Dispose();
                }
            }
        }
Пример #4
0
 public void HandlesMultipleDispose()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
     {
         fs.Dispose();
         fs.Dispose();
     }  // disposed as we leave using
 }
Пример #5
0
        /*
         * Function: ReadFile
         * Description:XMLStrategy算法读取函数
         * Parameters:
         *      string sPath 文件路径
         *      StyleSet pStyle 绘制样式集
         * Return Value:cNet
         */
        cNet IfIOStrategy.ReadFile(string sPath)
        {
            FileStream stream = null;
            XmlDocument doc = new XmlDocument();
            XmlNodeList Nodelist;
            XmlNode xmlroot, xmltmp;
            cNet NewNet;
            int iNum;

            try
            {
                stream = new FileStream(sPath, FileMode.Open);
                doc.Load(stream);               //从流文件读入xml文档
                stream.Close();
            }
            catch (Exception ex)
            {
                if (stream != null)
                {
                    ex.ToString();
                    stream.Dispose();
                }
                return null;
            }
            stream.Dispose();
            xmlroot = doc.ChildNodes.Item(0);
            Nodelist = xmlroot.ChildNodes;                                             //获取节点列表
            xmltmp = Nodelist[0].ChildNodes[3];
            //创建网络
            NewNet = new cNet(Nodelist.Count);
            for (iNum = 0; iNum < Nodelist.Count; iNum++)
            {
                switch (xmltmp.Name)
                {//区分XML数据类型
                    case "Word"://如果包含Word标签,就是关键词网络文件,生成KNode
                        NewNet.Network.Add(new kNode(iNum));
                        break;
                    default://默认都是cNode
                        NewNet.Network.Add(new cNode(iNum));
                        break;
                } 
            }
            NewNet.XMLtoNet(doc);
            if (NewNet.intNumber == 0)
            {
                return null;
            }
            return NewNet;
        }
        /// <summary>
        /// Metoda za verifikaciju ispravnosti digitalnog potpisa dokumenta
        /// </summary>
        /// <param name="file"></param>
        public void VerifyDigitalSignature(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("javni_kljuc.txt");
            string publicKey = streamReader.ReadToEnd();
            rsa.FromXmlString(publicKey);
            streamReader.Close();
            streamReader.Dispose();

            FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read);
            BinaryReader binReader = new BinaryReader(dat);
            byte[] data = binReader.ReadBytes((int)dat.Length);
            string nameP = file + ".dp";

            TextReader streamreader = new StreamReader(nameP);
            string sign = streamreader.ReadLine();
            streamreader.Close();
            streamreader.Dispose();

            if (rsa.VerifyData(data, "SHA1", Convert.FromBase64String(sign)))
            {
                MessageBox.Show("Datoteka je ispravno potpisana", "My Application",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
                MessageBox.Show("Datoteka nije ispravno potpisana", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            binReader.Close();
            binReader.Dispose();
            dat.Close();
            dat.Dispose();
        }
		public byte[] FilenameToBytes(string filename)
		{
			byte[] data = null;

			// get the file information form the selected file
			FileInfo fInfo = new FileInfo(filename);

			// get the length of the file to see if it is possible
			// to upload it (with the standard 4 MB limit)
			long numBytes = fInfo.Length;
			double dLen = Convert.ToDouble(fInfo.Length / 1000000);

			// set up a file stream and binary reader for the
			// selected file
			FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
			BinaryReader br = new BinaryReader(fStream);

			// convert the file to a byte array
			data = br.ReadBytes((int)numBytes);
			br.Close();

			fStream.Close();
			fStream.Dispose();

			return data;
		}
Пример #8
0
        /// <summary>
        /// 设置调试
        /// </summary>
        /// <param name="isDebug"></param>
        internal static void SetDebug(bool isDebug)
        {
            string content = String.Empty;
            bool isChange = false;

            using (StreamReader fs = new StreamReader(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory)))
            {
                content = fs.ReadToEnd();
                fs.Dispose();
            }

            Regex reg = new Regex("<compilation([^(debug)])+debug=\"([^\"]+)\"", RegexOptions.IgnoreCase);
            if (reg.IsMatch(content))
            {
                Match m = reg.Match(content);
                if ((m.Groups[2].Value == "true" && !isDebug) || (m.Groups[2].Value == "false" && isDebug))
                {
                    content = reg.Replace(content, String.Format("<compilation$1debug=\"{0}\"", isDebug ? "true" : "false"));
                    isChange = true;
                }
            }

            if (isChange)
            {
                using (FileStream fs = new FileStream(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory),
                    FileMode.Truncate, FileAccess.Write,FileShare.ReadWrite))
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Dispose();
                }
            }
        }
Пример #9
0
 public TIM(string path, byte arg0 = 0, bool paramsOnly = false)
 {
     this.arg0 = arg0 != 0;
     this.path = path;
     fs = new FileStream(path, FileMode.Open, FileAccess.Read);
     br = new BinaryReader(fs);
     texture = new Texture();
     bpp = RecognizeBPP();
     if (bpp == -1 && arg0==0)
     {
         Console.WriteLine("TIM: This is not TIM texture!");
         return;
     }
     if (arg0 == 0 && !paramsOnly)
     {
         ReadParameters(bpp);
         bmp = DrawTexture();
     }
     if (arg0 == 0 && paramsOnly)
     {
         ReadParameters(bpp);
     }
     br.Dispose();
     fs.Dispose();
 }
Пример #10
0
        public static void ReadingFile()
        {
            FileStream fs = new FileStream("score", FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryFormatter bf = new BinaryFormatter();

            MainForm.Scores = (List<Doodle_Jump.Doodler.Score>)bf.Deserialize(fs);

            if (MainForm.Scores.Count < 10)
            {
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
                MainForm.Scores.Add(new Score("Doodler", 0));
            }
            fs.Dispose();
            fs.Close();

            uint z = 380;
            Gl.glColor4ub(105, 52, 20, 255);
            foreach (Doodle_Jump.Doodler.Score k in MainForm.Scores)
            {

                Texture.Texture.PrintText2DPoint(195, z, k.Name);
                Texture.Texture.PrintText2DPoint(305, z, k.uScore.ToString());
                z -= 20;
            }
        }
Пример #11
0
 public ConfigIni()
 {
     StreamReader sr = new StreamReader(Basic_HTB_Info.baseFilePath + @"\Config.txt", Encoding.Default);
     string line = null;
     while ((line = sr.ReadLine()) != null)
     {
         string[] s_ar = line.Split('=');
         if (s_ar[0] == "DB_HOST") DB_HOST = s_ar[1];
         if (s_ar[0] == "output_result_html") output_result_html = s_ar[1];
         if (s_ar[0] == "report_to_public") report_to_public = s_ar[1];
         if (s_ar[0] == "temp_dir") temp_dir = s_ar[1];
         if (s_ar[0] == "blanktable_to_public") blanktable_to_public = s_ar[1];
     }
     sr.Close();
     sr.Dispose();
     using (FileStream xmlfs = new FileStream(Basic_HTB_Info.baseFilePath + @"\tempdata.txt",FileMode.Open))
     {
         XmlTextReader xmlr = new XmlTextReader(xmlfs);
         String tempstr = null;
         while (xmlr.Read())
         {
             if (xmlr.NodeType == XmlNodeType.Element)
             {
                 if (xmlr.Name == "tempdata") continue;
                 tempstr = xmlr.Name;
             }
             else if (xmlr.NodeType == XmlNodeType.Text)
             {
                 tempdata.Add(tempstr, xmlr.Value);
             }
         }
         xmlfs.Close();
         xmlfs.Dispose();
     }
 }
Пример #12
0
 public byte[] FileToByteArray(string _FileName)
 {
     byte[] pdfBuffer = null;
     try
     {
         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 TotalNumberOfBytes = new
        System.IO.FileInfo(_FileName).Length;
         pdfBuffer =
        _BinaryReader.ReadBytes((Int32)TotalNumberOfBytes);
         _FileStream.Close();
         _FileStream.Dispose();
         _BinaryReader.Close();
     }
     catch (Exception _Exception)
     {
         Console.WriteLine("Exception caught in process: {0}",
        _Exception.ToString());
     }
     return pdfBuffer;
 }
Пример #13
0
        /// <summary>
        /// To Get the user credentials from Customer Resource file
        /// </summary>
        /// Authour: Pradeep
        /// <param name="custType">Type of the customer</param>
        /// <returns>returns an array with UserName and Password</returns>
        /// Created Date: 22-Dec-2011
        /// Modified Date: 22-Dec-2011
        /// Modification Comments
        public static string[] GetCustomerCredentials(string custType)
        {
            try
            {
                Stream stream = new System.IO.FileStream(ResFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                var resFileData = new ResXResourceReader(stream);
                IDictionaryEnumerator resFileDataDict = resFileData.GetEnumerator();
                var customerCreds = new string[2];
                while (resFileDataDict.MoveNext())
                {
                    if (custType.ToString(CultureInfo.InvariantCulture) == resFileDataDict.Key.ToString())
                    {
                        string temp = resFileDataDict.Value.ToString();
                        customerCreds = temp.Split(';');
                        break;
                    }
                }

                resFileData.Close();
                stream.Dispose();
                return customerCreds;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return null;

            }
        }
Пример #14
0
        //defaultfile is under userpath
        public static void GetImageFromFile(string filename,string defaultfile,HttpResponse response)
        {
            if (!File.Exists(filename))
            {
                string userdatapath = Functions.GetAppConfigString("UserDataPath", "");
                filename = userdatapath + "\\"+defaultfile;
            }

            System.IO.FileStream fs = null;
            System.IO.MemoryStream ms = null;
            try
            {

                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                ms = new System.IO.MemoryStream(buffer);

                response.ClearContent();
                response.BinaryWrite(ms.ToArray());
                ms.Close();

            }
            finally
            {
                fs.Dispose();
                ms.Dispose();

            }
        }
Пример #15
0
 public void Write(Exception ex)
 {
     try
     {
         string filePath = this._fileName;
         lock (obj)
         {
             using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite))
             {
                 using (StreamWriter sw = new StreamWriter(fs))
                 {
                     sw.WriteLine(DateTimeFormat.LongTimeFormat + " : " + ex);
                     //sw.Flush();
                     sw.Close();
                     fs.Close();
                     sw.Dispose();
                     fs.Dispose();
                 }
             }
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        /// <summary>
        /// Metoda za digitalno potpisivanje dokumenta
        /// </summary>
        /// <param name="file"></param>
        public void MakeDigitalSignature(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("privatni_kljuc.txt");
            string publicOnlyKeyXml = streamReader.ReadToEnd();
            rsa.FromXmlString(publicOnlyKeyXml);

            streamReader.Close();
            streamReader.Dispose();

            FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read);

            BinaryReader binReader = new BinaryReader(dat);
            byte[] data = binReader.ReadBytes((int)dat.Length);
            byte[] sign = rsa.SignData(data, "SHA1");

            binReader.Close();
            binReader.Dispose();
            dat.Close();
            dat.Dispose();

            string datName = file + ".dp";

            TextWriter tw = new StreamWriter(datName);
            tw.WriteLine(Convert.ToBase64String(sign));
            tw.Close();
            tw.Dispose();
        }
Пример #17
0
 public static bool CreateFile(string path,string fileName,byte[] bytes)
 {
     Stream stream = null;
     string fullPath = path + fileName;
     string dir = fullPath.Substring(0, fullPath.LastIndexOf("/"));
     bool isSuccess = false;
     try
     {
         DirectoryInfo dirInfo = new DirectoryInfo(dir);
         if (!dirInfo.Exists) dirInfo.Create();
         FileInfo fileInfo = new FileInfo(fullPath);
         stream = new FileStream(fileInfo.FullName, FileMode.OpenOrCreate, FileAccess.Write);
         stream.Write(bytes, 0, bytes.Length);
         stream.Flush();
         isSuccess = true;
     }
     catch(System.Exception ex)
     {
         Debug.Log("Create File ERROR:"+ex.Message);
     }
     finally
     {
         if(stream!=null)
         {
             stream.Close();
             stream.Dispose();
         }
     }
     return isSuccess;
 }
Пример #18
0
        public static IVCryptoStream Save(string path, byte[] key, byte[] iv)
        {
            FileStream file = new FileStream(path, FileMode.Create);

            RijndaelManaged crypt = new RijndaelManaged();
            crypt.Key = key;

            if (iv == null)
                crypt.GenerateIV();
            else
            {
                Debug.Assert(iv.Length == crypt.IV.Length);
                crypt.IV = iv;
            }

            try
            {
                file.Write(crypt.IV, 0, crypt.IV.Length);
            }
            catch
            {
                file.Dispose();
            }

            return new IVCryptoStream(file, crypt.CreateEncryptor(), CryptoStreamMode.Write);
        }
Пример #19
0
        public void run()
        {
            MGraph pMGraph = new MGraph();
            pMGraph.init(3, 3, 1, 1);

            List<Vertex> vertList;
            FileStream pFile = new FileStream("E:\\aaa.txt", FileMode.Create);
            string strStream = "";

            vertList = test5Stop(pMGraph);
            serializePath(vertList, ref strStream);
            pMGraph.clearAllStopPoint();
            pMGraph.clearPath();

            vertList = test4Stop(pMGraph);
            serializePath(vertList, ref strStream);
            pMGraph.clearAllStopPoint();
            pMGraph.clearPath();

            vertList = test2Stop(pMGraph);
            serializePath(vertList, ref strStream);
            pMGraph.clearAllStopPoint();
            pMGraph.clearPath();

            vertList = test2Stop(pMGraph);
            serializePath(vertList, ref strStream);
            pMGraph.clearAllStopPoint();
            pMGraph.clearPath();

            byte[] inBytes = System.Text.Encoding.UTF8.GetBytes(strStream);
            pFile.Write(inBytes, 0, inBytes.Length);
            pFile.Close();
            pFile.Dispose();
        }
		/// <summary>
		/// Provides a memory copy of an original image file
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		public static System.Drawing.Image NonLockingOpen(string filename)
		{
			try {
				System.Drawing.Image result;
				
				#region Save file to byte array
				
				long size = (new FileInfo(filename)).Length;
				FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
				byte[] data = new byte[size];
				try {
					fs.Read(data, 0, (int)size);
				} finally {
					fs.Close();
					fs.Dispose();
				}
				
				#endregion
				
				#region Convert bytes to image
				
				MemoryStream ms = new MemoryStream();
				ms.Write(data, 0, (int)size);
				result = new Bitmap(ms);
				ms.Close();
				
				#endregion
				
				return result;
				
			} catch (Exception ex) {
				throw ex;
			}
			
		}
 private void learnFormAssetBundle(string path)
 {
     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
     DataReader br = new DataReader(fs);
     SerializeBundle bundle = new SerializeBundle();
     bundle.DeSerialize(br);
     foreach (var bundleEntry in bundle.entrys) {
         int version = AssetToolUtility.GetAssetsFileVersion(bundleEntry.assetData);
         var serializeAssets = SerializeAssetFactory.CreateWithVersion(version);
         if (serializeAssets != null) {
             MemoryStream ms = new MemoryStream(bundleEntry.assetData);
             DataReader dr = new DataReader(ms);
             serializeAssets.DeSerialize(dr);
             var assetTypeTreeDB = AssetToolUtility.GenerateTypeTreeDataBase(serializeAssets);
             if (assetTypeTreeDB != null) {
                 var allType = assetTypeTreeDB.GetAllType(version);
                 foreach (var type in allType) {
                     Console.WriteLine("AddType:Version:{0},ClassID{1},Name:{2}", version, type.Key, type.Value.type);
                 }
             }
             typeTreeDatabase = assetTypeTreeDB.Merage(typeTreeDatabase);
         } else {
             Debug.LogError("can't deserialize bundle entry " + bundleEntry.name);
         }
         fs.Dispose();
     }
 }
        public FileViewModel GetFile(ListItem file)
        {
            var path = Path.Combine(ConfigurationHelper.GetTemporaryFilesFolder(), file.Id, file.Value);
            if (File.Exists(path))
            {
                FileStream fsSource = null;
                try
                {
                    fsSource = new FileStream(path, FileMode.Open, FileAccess.Read);
                    var viewModel = new FileViewModel
                    {
                        FileName = file.Value,
                        InputStream = fsSource
                    };
                    return viewModel;
                }
                catch (Exception ex)
                {
                    if (fsSource != null)
                    {
                        fsSource.Dispose();
                    }

                    throw;
                }
            }

            return null;
        }
Пример #23
0
		static void DisposeFileStream ()
		{
			FileStream fs = new FileStream("myFile.txt", FileMode.OpenOrCreate);

			fs.Close();
			fs.Dispose();
		}
Пример #24
0
 /// <summary>
 /// 反序列化XML字符串为对象
 /// </summary>
 /// <param name="xmlSource"></param>
 /// <returns></returns>
 public static object Deserialize(string filename, Type mainType, Type[] subTypes = null)
 {
     if (filename.Trim() == "") return null;
     try
     {
         if (subTypes == null)
         {
             subTypes = new Type[1];
             subTypes[0] = typeof(string);
         }
         XmlSerializer x = new XmlSerializer(mainType, subTypes);
         // Create a TextReader to read the file.
         FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
         TextReader reader = new StreamReader(fs);
         object obj = x.Deserialize(reader);
         reader.Close();
         fs.Close();
         fs.Dispose();
         return obj;
     }
     catch
     {
         return null;
     }
 }
Пример #25
0
        public bool CheckIfFileIsBeingUsed(string fileName)
        {
            try
            {
                FileStream fs;
                using(fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    fs.Dispose();
                    fs.Close();
                }
                //if (!Directory.Exists(fileName))
                //{

                //}
                //else
                //{
                //    Directory.Delete(fileName);
                //}
            }

            catch (Exception exp)
            {
                return true;
            }

            return false;
        }
Пример #26
0
        /// <summary>
        /// �ڱ���д�������־
        /// </summary>
        /// <param name="exception"></param> 
        public static void WriteLog(string debugstr)
        {
            lock (writeFile)
            {
                FileStream fs = null;
                StreamWriter sw = null;

                try
                {
                    string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                    //����������־Ŀ¼
                    string folder = HttpContext.Current.Server.MapPath("~/Log");
                    if (!Directory.Exists(folder))
                        Directory.CreateDirectory(folder);
                    fs = new FileStream(folder + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine( DateTime.Now.ToString() + "     " + debugstr + "\r\n");
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Flush();
                        sw.Dispose();
                        sw = null;
                    }
                    if (fs != null)
                    {
                        //     fs.Flush();
                        fs.Dispose();
                        fs = null;
                    }
                }
            }
        }
Пример #27
0
		/// <summary>
		/// Saves.
		/// </summary>
		/// <param name="fileName">File name</param>
		/// <param name="instance">Instance</param>
		/// <remarks>Standard deserialization method implemented using <see cref="System.Runtime.Serialization.Formatters.Soap.SoapFormatter"></see>.</remarks>
		public static void SoapSave(string fileName, object instance) {
			Trace.Assert(fileName != null);

			Stream _FileStream = null;
			string folder = Path.GetDirectoryName(fileName);
			if (!Directory.Exists(folder))
			{
				Directory.CreateDirectory(folder);
			}

			try {
				_FileStream = new FileStream(fileName, FileMode.Create);
			} catch (DirectoryNotFoundException) {
				// no such directory
				LoggingService.Error("no such directory");
			} finally {
				if (_FileStream != null) {
				    new SoapFormatter().Serialize(_FileStream, instance);
					_FileStream.Close();
					_FileStream.Dispose();
				} else {
					LoggingService.Warn("null file stream");
				}
			}
		}
        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("File Read Error: ", _Exception.ToString());
            }

            return _Buffer;
        }
Пример #29
0
        /* INPUT 1:
        ../../Faded.mp4
        ../../
        5
        INPUT 2:
        ../../text.txt
        ../../
        3

         * * * */
        private static void Slice(string sourceFile, string destinationDirectory, int parts)
        {
            FileStream reader = new FileStream(sourceFile, FileMode.Open);
            FileInfo file = new FileInfo(sourceFile);
            long chunkSize = (long)(file.Length/parts);
            BigInteger counter = -1;
            if (file.Length%2 == 1)
            {
                counter = 0;
            }
            int fileCounter = 1;
            int readBytesVariable = reader.ReadByte();
            List<byte> lsBytes = new List<byte>();
            lsBytes.Add((byte)readBytesVariable);
            while (readBytesVariable != -1)
            {

                if ((counter%chunkSize == 0 && counter != 0) || counter == file.Length)
                {
                    string fileName = destinationDirectory + "Part-" + fileCounter + "." + sourceFile.Split(new char[]{'.'},StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
                    FileStream writer = new FileStream(fileName, FileMode.Create,FileAccess.Write);
                    writer.Write(lsBytes.ToArray(), 0,lsBytes.Count);
                    writer.Flush();
                    writer.Dispose();
                    lsBytes.Clear();
                    fileCounter++;
                }

                readBytesVariable = reader.ReadByte();
                lsBytes.Add((byte)readBytesVariable);
                counter++;
            }
        }
Пример #30
0
        /// <summary>
        /// Attempt to extract a file from an archive
        /// </summary>
        /// <param name="entryName">Name of the entry to be extracted</param>
        /// <param name="outDir">Output directory for archive extraction</param>
        /// <returns>Name of the extracted file, null on error</returns>
        public override string CopyToFile(string entryName, string outDir)
        {
            // Try to extract a stream using the given information
            (MemoryStream ms, string realEntry) = CopyToStream(entryName);

            // If the memory stream and the entry name are both non-null, we write to file
            if (ms != null && realEntry != null)
            {
                realEntry = Path.Combine(outDir, realEntry);

                // Create the output subfolder now
                Directory.CreateDirectory(Path.GetDirectoryName(realEntry));

                // Now open and write the file if possible
                FileStream fs = Utilities.TryCreate(realEntry);
                if (fs != null)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    byte[] zbuffer = new byte[_bufferSize];
                    int    zlen;
                    while ((zlen = ms.Read(zbuffer, 0, _bufferSize)) > 0)
                    {
                        fs.Write(zbuffer, 0, zlen);
                        fs.Flush();
                    }

                    ms?.Dispose();
                    fs?.Dispose();
                }
                else
                {
                    ms?.Dispose();
                    fs?.Dispose();
                    realEntry = null;
                }
            }

            return(realEntry);
        }
Пример #31
0
        private string Compress(string path)
        {
            var photoUri = Android.Net.Uri.Parse(path);

            FileDescriptor fileDescriptor = null;
            Bitmap         btmp           = null;

            System.IO.FileStream stream = null;
            try
            {
                fileDescriptor = ContentResolver.OpenFileDescriptor(photoUri, "r").FileDescriptor;
                btmp           = BitmapUtils.DecodeSampledBitmapFromDescriptor(fileDescriptor, 1600, 1600);
                btmp           = BitmapUtils.RotateImageIfRequired(btmp, fileDescriptor, path);

                var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
                var directory         = new Java.IO.File(directoryPictures, Constants.Steepshot);
                if (!directory.Exists())
                {
                    directory.Mkdirs();
                }

                path   = $"{directory}/{Guid.NewGuid()}.jpeg";
                stream = new System.IO.FileStream(path, System.IO.FileMode.Create);
                btmp.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);

                return(path);
            }
            catch (Exception ex)
            {
                _postButton.Enabled = false;
                this.ShowAlert(Localization.Errors.UnknownCriticalError);
                AppSettings.Reporter.SendCrash(ex);
            }
            finally
            {
                fileDescriptor?.Dispose();
                btmp?.Recycle();
                btmp?.Dispose();
                stream?.Dispose();
            }
            return(path);
        }
Пример #32
0
    // ====================================================================================================
    /// <summary>
    /// Deserializes the XML class of type T if an xml file exists.
    /// Or creates a new() copy of the class, saves and load that if file does not exist
    /// </summary>
    public static T Deserialize <T>(string fileName) where T : class, new()
    {
        T C_Data = new T();

        System.IO.FileStream fileStream;
        XmlReader            reader;
        XmlSerializer        serializer = new XmlSerializer(typeof(T));

        // Check if file exists before opening a stream reader on it
        if (!System.IO.File.Exists(FilePaths.GetResourcePath() + fileName))
        {
            fileStream = System.IO.File.Create(FilePaths.GetResourcePath() + fileName);
            fileStream.Close();
            fileStream.Dispose();
            Serialize <T>(C_Data, fileName);
        }
        else
        {
            // Open the data file and read it so as to fill the C_Data structure
            fileStream = new System.IO.FileStream(FilePaths.GetResourcePath() + fileName, System.IO.FileMode.Open);
            reader     = new XmlTextReader(fileStream);

            try
            {
                if (serializer.CanDeserialize(reader))
                {
                    C_Data = serializer.Deserialize(reader) as T;
                }
            }
            finally
            {
                // Don't forget to close the readers and streams !
                reader.Close();
                fileStream.Close();
                fileStream.Dispose();
            }
        }

        return(C_Data);
    }
Пример #33
0
        public override void Close()
        {
            if (!IsOpen())
            {
                return;
            }

            writeStream?.Flush();
            writeStream?.Close();
            writeStream?.Dispose(); //Might want to only dispose unmanaged resources aka the file handle https://msdn.microsoft.com/en-us/library/fy2eke69(v=vs.110).aspx
            writeStream = null;

            readStream?.Flush();
            readStream?.Close();
            readStream?.Dispose();
            readStream = null;
            if (lastWriteTimeTodo != null)
            {
                SetLastWriteTime(lastWriteTimeTodo.Value);
            }
            lastWriteTimeTodo = null;
        }
Пример #34
0
    public void UploadFile(string filepath)
    {
        string filename = DateTime.Now.ToString().Replace("/", "_").Replace(":", "-") + "-" + System.IO.Path.GetFileName(filepath);

        var fileMetadata = new File()
        {
            Name     = filename,
            MimeType = "application/unknown"
        };

        System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open);

        FilesResource.CreateMediaUpload uploadrequest = service.Files.Create(fileMetadata, fs, "application/unknown");
        uploadrequest.Fields = "id";

        //this variable can be used to track an errors while uploading
        IUploadProgress uploadProgress = uploadrequest.Upload();

        error = uploadProgress.Exception.Message;

        fs.Close();
        fs.Dispose();
    }
Пример #35
0
    private string getFile(DataTable dt)
    {
        string strFilePath = string.Empty;

        NPOI.SS.UserModel.IWorkbook book1 = new ImportExcel().ImportCustomerWorkBill(dt, "客户服务记录");
        string strFile  = string.Empty;
        string filename = string.Empty;
        string strPath  = HttpContext.Current.Server.MapPath("/" + System.Configuration.ConfigurationManager.AppSettings["CustomerFiles"].ToString().Replace("\\", "/") + "/")
                          + "\\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + "\\";

        if (dt.Rows.Count > 0)
        {
            strFile  = dt.Rows[0]["客户名称"].ToString();
            filename = strPath + dt.Rows[0]["客户名称"].ToString() + ".xls";
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filename)))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename));
            }
            try
            {
                System.IO.FileStream file1 = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                book1.Write(file1);

                file1.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        else
        {
            filename = "";
        }
        return(filename);
    }
Пример #36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SMT.Foundation.Log.Tracer.Debug("开始下载文件");
            try
            {
                //\SMT\OA\考勤管理\2010121702324784503941.JPG
                //string fileName = "123.jpg";//客户端保存的文件名
                bool IsThum = false;//是否下载缩略图、不经过解密处理开关
                if (Request["filename"] == null)
                {
                    return;
                }
                if (Request["flag"] != null)
                {
                    IsThum = true;
                }
                String fileurl = HttpUtility.UrlDecode(Request["filename"]);
                SMT.Foundation.Log.Tracer.Debug("下载文件地址:" + fileurl);
                string[] arrFilePath = fileurl.Split('\\');
                // string filePath = string.Format(SavePath, fileName.Split('|')[0], fileName.Split('|')[1],  fileName.Split('|')[2]+"\\"+fileName.Split('|')[3]); //context.Server.MapPath("Bubble.jpg");
                string filePath = "";
                if (arrFilePath.Length == 6)
                {
                    filePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]);
                }
                else
                {
                    filePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]) + "\\" + arrFilePath[arrFilePath.Length - 2];
                }
                string NewfilePath = "";
                if (!IsThum)
                {
                    NewfilePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[5]);
                }
                else
                {
                    //缩略图没有进行加密操作所以还是显示原图
                    NewfilePath = string.Format(FileConfig.GetCompanyItem(arrFilePath[1]).SavePath, arrFilePath[1], arrFilePath[2], arrFilePath[3] + "\\" + arrFilePath[4]) + "\\" + arrFilePath[arrFilePath.Length - 2];
                }
                SMT.Foundation.Log.Tracer.Debug("下载真实文件地址NewfilePath:" + NewfilePath);
                string             saveFileName        = arrFilePath[arrFilePath.Length - 1];                 //获取文件名
                string             StrServicesFileName = arrFilePath[arrFilePath.Length - 2].Substring(0, 8); //取前面的作为解密字符串
                System.IO.FileInfo fileInfo            = new System.IO.FileInfo(filePath);
                if (fileInfo.Exists == true)
                {
                    string Key = StrServicesFileName;
                    if (!IsThum)
                    {
                        CryptoHelp.DecryptFile(filePath, NewfilePath, StrServicesFileName);
                    }
                    //System.IO.FileStream iStream = System.IO.File.OpenRead(NewfilePath);
                    long   dataToRead;
                    int    length;
                    byte[] buffer = new Byte[300000];
                    System.IO.FileStream iStream = new System.IO.FileStream(NewfilePath, System.IO.FileMode.Open,
                                                                            System.IO.FileAccess.Read, System.IO.FileShare.Read);

                    //   Total   bytes   to   read:
                    dataToRead = iStream.Length;

                    Response.ContentType = "application/octet-stream";

                    Response.Charset = "UTF-8";
                    Response.AddHeader("Content-Disposition", "attachment;   filename=" + System.Web.HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8));
                    Response.AddHeader("Content-Length", dataToRead.ToString());
                    //   Read   the   bytes.
                    while (dataToRead > 0)
                    {
                        //   Verify   that   the   client   is   connected.
                        if (Response.IsClientConnected)
                        {
                            //   Read   the   data   in   buffer.
                            length = iStream.Read(buffer, 0, 300000);

                            //   Write   the   data   to   the   current   output   stream.
                            Response.OutputStream.Write(buffer, 0, length);

                            //   Flush   the   data   to   the   HTML   output.
                            Response.Flush();

                            buffer     = new Byte[300000];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            //prevent   infinite   loop   if   user   disconnects
                            dataToRead = -1;
                        }
                    }
                    if (iStream != null)
                    {
                        //Close   the   file.
                        iStream.Close();
                        iStream.Dispose();
                    }
                    //删除文件
                    if (!IsThum)
                    {
                        File.Delete(NewfilePath);
                    }
                }
                else
                {
                    System.Web.HttpContext.Current.Response.Write("<script>alert('该文件不存在!');</script>");
                }
                //context.Response.ContentType = "text/plain";
                //context.Response.Write("Hello World");
            }
            catch (Exception ex)
            {
                //   Trap   the   error,   if   any.
                Response.Write("下载出现异常Error   :   " + ex.Message);
                Response.Clear();
                Response.End();
            }
            finally
            {
                Response.Clear();
                Response.End();
            }
        }
Пример #37
0
        //处理客户端请求
        private void HandleRequest(object ctx)
        {
            HttpListenerContext  context  = ctx as HttpListenerContext;
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            try
            {
                string rawUrl          = Uri.UnescapeDataString(request.RawUrl);
                int    paramStartIndex = rawUrl.IndexOf('?');
                if (paramStartIndex > 0)
                {
                    rawUrl = rawUrl.Substring(0, paramStartIndex);
                }
                else if (paramStartIndex == 0)
                {
                    rawUrl = "";
                }

                #region 文件请求

                {
                    string filePath = WebHomeDir + rawUrl;
                    //替换
                    // var platforms = BDApplication.GetSupportPlatform();
                    // foreach (var platform in platforms)
                    // {
                    //     var platformStr = BDApplication.GetPlatformPath(platform);
                    //     filePath = filePath.Replace(platformStr, platformStr + PublishPipelineTools.UPLOAD_FOLDER_SUFFIX);
                    // }

                    if (!File.Exists(filePath))
                    {
                        response.ContentLength64 = 0;
                        response.StatusCode      = 404;
                        response.Abort();
                    }
                    else
                    {
                        response.StatusCode = 200;
                        string exeName = Path.GetExtension(filePath);
                        response.ContentType = GetContentType(exeName);
                        FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                        int        byteLength = (int)fileStream.Length;
                        byte[]     fileBytes  = new byte[byteLength];
                        fileStream.Read(fileBytes, 0, byteLength);
                        fileStream.Close();
                        fileStream.Dispose();
                        response.ContentLength64 = byteLength;
                        response.OutputStream.Write(fileBytes, 0, byteLength);
                        response.OutputStream.Close();
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                response.StatusCode  = 200;
                response.ContentType = "text/plain";
                using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
                {
                    writer.WriteLine("接收完成!");
                }
            }

            try
            {
                response.Close();
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }
        }
Пример #38
0
        /// <summary>
        /// Decrypt a miniLock file using the specified Keys
        /// </summary>
        /// <param name="TheFile"></param>
        /// <param name="RecipientKeys"></param>
        /// <returns>null on any error, or a DecryptedFile object with the raw file contents, a plaintext hash,
        /// the SenderID, and the stored filename</returns>
        public static DecryptedFileDetails DecryptFile(FileStream SourceFile, string DestinationFileFullPath, bool OverWriteDestination, miniLockManaged.Keys RecipientKeys)
        {
            if (SourceFile == null)
            {
                throw new ArgumentNullException("SourceFile");
            }
            if (DestinationFileFullPath == null)
            {
                throw new ArgumentNullException("DestinationFile");
            }
            if (!SourceFile.CanRead)
            {
                throw new InvalidOperationException("Source File not readable!");
            }
            if (System.IO.File.Exists(DestinationFileFullPath) && !OverWriteDestination)
            {
                // be fault tolerant
                System.IO.FileInfo existing    = new System.IO.FileInfo(DestinationFileFullPath);
                string             newFilename = DestinationFileFullPath;
                int counter = 1;
                do
                {
                    newFilename  = DestinationFileFullPath.Replace(existing.Extension, "");
                    newFilename += '(' + counter++.ToString() + ')' + existing.Extension;
                } while (File.Exists(newFilename));
                DestinationFileFullPath = newFilename;
                // this is not fault tolerant
                //throw new InvalidOperationException("Destination File already exists!  Set OverWriteDestination true or choose a different filename.");
            }

            FullHeader fileStuff = new FullHeader();
            HeaderInfo h;

            byte[] buffer = null;

            // after this call, the source file pointer should be positioned to the end of the header
            int hLen = IngestHeader(ref SourceFile, out h);

            if (hLen < 0)
            {
                SourceFile.Close();
                SourceFile.Dispose();
                return(null);
            }
            hLen += 12;                                             // the 8 magic bytes and the 4 header length bytes and the length of the JSON header object
            long theCliff = SourceFile.Length - hLen;               // this is the ADJUSTED point where the file cursor falls off the cliff

            if (!TryDecryptHeader(h, RecipientKeys, out fileStuff)) // ciphertext hash is compared later
            {
                fileStuff.Clear();
                SourceFile.Close();
                SourceFile.Dispose();
                return(null);
            }

            Blake2sCSharp.Hasher b2sPlain  = Blake2sCSharp.Blake2S.Create(); // a nice-to-have for the user
            Blake2sCSharp.Hasher b2sCipher = Blake2sCSharp.Blake2S.Create(); // a check to make sure the ciphertext wasn't altered
            //note:  in theory, if the ciphertext doesn't decrypt at any point, there is likely something wrong with it up to and
            //  including truncation/extension
            //  BUT the hash is included in the header, and should be checked.

            DecryptedFileDetails results = new DecryptedFileDetails();

            results.ActualDecryptedFilePath = DestinationFileFullPath; // if the filename got changed, it happened before this point
            string tempFile = null;                                    // save the filename of the temp file so that the temp directory created with it is also killed

            System.IO.FileStream tempFS = GetTempFileStream(out tempFile);

            int    cursor      = 0;
            UInt64 chunkNumber = 0;

            byte[] chunkNonce = new byte[24];                                        // always a constant length
            Array.Copy(fileStuff.fileNonce, chunkNonce, fileStuff.fileNonce.Length); // copy it once and be done with it
            do
            {
                // how big is this chunk? (32bit number, little endien)
                buffer = new byte[4];
                if (SourceFile.Read(buffer, 0, buffer.Length) != buffer.Length)
                {
                    //read error
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                b2sCipher.Update(buffer);  // have to include ALL the bytes, even the chunk-length bytes
                UInt32 chunkLength = Utilities.BytesToUInt32(buffer);
                if (chunkLength > MAX_CHUNK_SIZE)
                {
                    //something went wrong!
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                cursor += 4; // move past the chunk length

                //the XSalsa20Poly1305 process, ALWAYS expands the plaintext by MacSizeInBytes
                // (authentication), so read the plaintext chunk length, add those bytes to the
                // value, then read that many bytes out of the ciphertext buffer
                byte[] chunk = new byte[chunkLength + XSalsa20Poly1305.MacSizeInBytes];
                //Array.Copy(buffer, cursor,
                //           chunk, 0,
                //           chunk.Length);
                if (SourceFile.Read(chunk, 0, chunk.Length) != chunk.Length)
                {
                    //read error
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                b2sCipher.Update(chunk); // get hash of cipher text to compare to stored File Info Object
                cursor += chunk.Length;  // move the cursor past this chunk
                if (cursor >= theCliff)  // this is the last chunk
                {
                    // set most significant bit of nonce
                    chunkNonce[23] |= 0x80;
                }
                byte[] decryptBytes = XSalsa20Poly1305.TryDecrypt(chunk, fileStuff.fileKey, chunkNonce);
                if (decryptBytes == null)
                {
                    // nonce or key incorrect, or chunk has been altered (truncated?)
                    buffer = null;
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                if (chunkNumber == 0) // first chunk is always filename '\0' padded
                {
                    results.StoredFilename = new UTF8Encoding().GetString(decryptBytes).Replace("\0", "").Trim();
                }
                else
                {
                    b2sPlain.Update(decryptBytes);                      // give the user a nice PlainText hash
                    tempFS.Write(decryptBytes, 0, decryptBytes.Length); // start building the output file
                }
                decryptBytes.Wipe();                                    // DON'T LEAK!!!
                // since the first chunkNonce is just the fileNonce and a bunch of 0x00's,
                //  it's safe to do the chunk number update as a post-process operation
                Utilities.UInt64ToBytes(++chunkNumber, chunkNonce, 16);
            } while (cursor < theCliff);
            SourceFile.Close();
            SourceFile.Dispose();
            byte[] ctActualHash = b2sCipher.Finish();
            if (!CryptoBytes.ConstantTimeEquals(ctActualHash, fileStuff.ciphertextHash))
            {
                // ciphertext was altered
                TrashTempFileStream(tempFS, tempFile);
                return(null);
            }
            results.SenderID = Keys.GetPublicIDFromKeyBytes(fileStuff.senderID);
            fileStuff.Clear(); // wipe the sensitive stuff!
            tempFS.Flush();
            tempFS.Close();
            tempFS.Dispose();
            //produce a handy hash for use by the end-user (not part of the spec)
            results.PlainTextBlake2sHash = b2sPlain.Finish().ToBase64String();

            System.IO.File.Move(tempFile, DestinationFileFullPath);
            // WARNING:  only use if the method that created the temp file also created a random subdir!
            Directory.Delete(new System.IO.FileInfo(tempFile).DirectoryName, true); // this is done since we didn't use TrashTempfileStream

            return(results);
        }
Пример #39
0
        /// <summary>
        /// Create and open an output file for writing direct from a dictionary
        /// </summary>
        /// <param name="outfile">Name of the file to write to</param>
        /// <param name="ignoreblanks">True if blank roms should be skipped on output, false otherwise (default)</param>
        /// <returns>True if the DAT was written correctly, false otherwise</returns>
        public override bool WriteToFile(string outfile, bool ignoreblanks = false)
        {
            try
            {
                Globals.Logger.User("Opening file for writing: {0}", outfile);
                FileStream fs = Utilities.TryCreate(outfile);

                // If we get back null for some reason, just log and return
                if (fs == null)
                {
                    Globals.Logger.Warning("File '{0}' could not be created for writing! Please check to see if the file is writable", outfile);
                    return(false);
                }

                StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false));

                // Write out the header
                WriteHeader(sw);

                // Get a properly sorted set of keys
                List <string> keys = Keys;
                keys.Sort(new NaturalComparer());

                foreach (string key in keys)
                {
                    List <DatItem> roms = this[key];

                    // Resolve the names in the block
                    roms = DatItem.ResolveNames(roms);

                    for (int index = 0; index < roms.Count; index++)
                    {
                        DatItem rom = roms[index];

                        // There are apparently times when a null rom can skip by, skip them
                        if (rom.Name == null || rom.MachineName == null)
                        {
                            Globals.Logger.Warning("Null rom found!");
                            continue;
                        }

                        // If we have a "null" game (created by DATFromDir or something similar), log it to file
                        if (rom.Type == ItemType.Rom &&
                            ((Rom)rom).Size == -1 &&
                            ((Rom)rom).CRC == "null")
                        {
                            Globals.Logger.Verbose("Empty folder found: {0}", rom.MachineName);
                        }

                        // Now, output the rom data
                        WriteDatItem(sw, rom, ignoreblanks);
                    }
                }

                Globals.Logger.Verbose("File written!" + Environment.NewLine);
                sw.Dispose();
                fs.Dispose();
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex.ToString());
                return(false);
            }

            return(true);
        }
Пример #40
0
        private static void TransferFiletoFTP(string serviceName, object jobDetails, string jobFile)
        {
            DateTime dtJobReleaseStart = DateTime.Now;

            DataRow drPrintJob  = jobDetails as DataRow;
            string  jobDBID     = drPrintJob["REC_SYSID"].ToString();
            string  jobFileName = drPrintJob["JOB_FILE"].ToString();

            if (!string.IsNullOrEmpty(jobFile))
            {
                jobFileName = jobFile;
            }
            string destinationFTPPath = drPrintJob["JOB_FTP_PATH"].ToString();
            string ftpUserName        = drPrintJob["JOB_FTP_ID"].ToString();
            string ftpUserPassword    = drPrintJob["JOB_FTP_PASSWORD"].ToString();
            string isDeleteFile       = drPrintJob["DELETE_AFTER_PRINT"].ToString();

            try
            {
                string message = string.Format("File Transfer to MFP started @ {0}", DateTime.Now.ToString());
                LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Detailed, message, "", "", "");
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(jobFileName);

                // Create FtpWebRequest object from the Uri provided
                System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(destinationFTPPath));

                // Provide the WebPermission Credintials
                ftpWebRequest.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpUserPassword);
                ftpWebRequest.Proxy       = null;
                //ftpWebRequest.ConnectionGroupName = jobFileName;
                // By default KeepAlive is true, where the control connection is not closed
                // after a command is executed.
                ftpWebRequest.KeepAlive = false;

                // set timeout for 20 seconds
                ftpWebRequest.Timeout = 30000;

                // Specify the command to be executed.
                ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type.
                ftpWebRequest.UseBinary = true;

                // Notify the server about the size of the uploaded file
                ftpWebRequest.ContentLength = fileInfo.Length;

                // The buffer size is set to 4MB
                int    buffLength = 4 * 1024 * 1024;
                byte[] buff       = new byte[buffLength];

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                System.IO.FileStream fileStream = fileInfo.OpenRead();

                // Stream to which the file to be upload is written
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();

                // Read from the file stream 4MB at a time
                int contentLen = fileStream.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    stream.Write(buff, 0, contentLen);
                    contentLen = fileStream.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                fileStream.Close();
                fileStream.Dispose();
                stream.Close();
                stream.Dispose();


                DateTime dtJobReleaseEnd = DateTime.Now;
                UpdateJobReleaseTimings(serviceName, drPrintJob["JOB_FILE"].ToString().Replace("_PDFinal", "_PD"), dtJobReleaseStart, dtJobReleaseEnd, jobDBID);

                if (isDeleteFile.ToLower() == "true")
                {
                    DeletePrintJobsFile(serviceName, jobFileName);
                }

                message = string.Format("File transferred to MFP, file : {0}", jobFileName);

                LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Detailed, message, "", "", "");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Exception, ex.Message, "Restart the Print Data Provider Service", ex.Message, ex.StackTrace);
            }
        }
Пример #41
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)
    {
        //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
        string outputFilename = filename.Substring(filename.LastIndexOf("\\") + 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
            if (destDir.EndsWith("\\") == false)
            {
                destDir += "\\";
            }

            //read in the source file
            fileData += System.IO.File.ReadAllText(filename);
            //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);
            //02/05/2007 need to write first to bytes when saving as unicode
            if (destEnc.CodePage == 1200)
            {
                fw.WriteByte(0xFF);
                fw.WriteByte(0xFE);
            }
            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();
        }
    }
Пример #42
0
        /// <summary>
        /// 下载核心 - 主线程
        /// </summary>
        /// <param name="p">线程负责的下载数据源的ID</param>
        private void StartDownload(Object p)
        {
            int    id  = (int)p;
            string url = /*"http://download.music.qq.com/320k/" + DownLoadList[id].TitleID + ".mp3";*/ DownLoadList[id].DownLoadURL;

            string filename = System.Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + "\\" + DownLoadList[id].SongTitle + ".mp3.!";

            filename = filename.Replace("\"", """).Replace("/", "/").Replace("?", "?").Replace("*", "*").Replace("|", "|").Replace("<", "<").Replace(">", ">");
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                Myrq.Referer = "";

                if (url.IndexOf("stream") != -1)
                {
                    //128kbps
                    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;  ");
                }
                else
                {
                    //32kbps、192kbps下载模式
                    Myrq.Headers.Add("Cache-Control: no-cache");
                    Myrq.Headers.Add("Pragma: getIfoFileURI.dlna.org");
                    Myrq.Headers.Add("Cookie: qqmusic_uin=10001; qqmusic_key=; qqmusic_privatekey=; qqmusic_fromtag=11;");
                    Myrq.Headers.Add("GetContentFeatures.DLNA.ORG: 1");
                }
                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;
                    int endtime = System.DateTime.Now.Second;

                    if ((endtime - starttime) >= 1)
                    {
                        //计算下载速度
                        int Speed = Convert.ToInt16(((totalDownloadedByte - lasttotalDownloadedByte) / 1024));
                        lasttotalDownloadedByte = totalDownloadedByte;
                        starttime = endtime;
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                        {
                            DownLoadList[id].Speed = Speed.ToString() + " KB/s";
                        });
                    }
                    so.Write(by, 0, osize);
                    if (Maximum != 0)
                    {
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                        {
                            DownLoadList[id].DownloadProgress = Math.Floor((double)(int)totalDownloadedByte / Maximum * 100).ToString() + " %";
                        });
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                }
                so.Close();
                so.Dispose();
                st.Close();
                st.Dispose();
                this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                {
                    DownLoadList[id].DownloadProgress = "已完成";
                    DownLoadList[id].Speed            = "";
                });
            }
            catch (Exception e)
            {
                #region  载失败处理模块
                this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                {
                    DownLoadList[id].DownloadProgress = "下载失败";
                    DownLoadList[id].Speed            = "";
                    MessageBox.Show("下载文件错误,请将下列内容反馈给我们,以方便进一步完善软件!\n(Ctrl+C 可复制 官方网站:www.4321.la)\n" + e.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                });
                try
                {
                    FileInfo file = new FileInfo(@filename);
                    if (file.Exists)
                    {
                        file.Delete();
                    }
                }
                catch
                {
                    //Do Nothing
                }
                #endregion
            }
            finally
            {
                #region  载完成处理模块
                try
                {
                    FileInfo file = new FileInfo(@filename);
                    if (file.Exists)
                    {
                        try
                        {
                            FileInfo fileo = new FileInfo(@filename.Replace(".!", ""));
                            if (fileo.Exists)
                            {
                                fileo.Delete();
                            }
                            filename = filename.Replace(".!", "");
                            file.MoveTo(@filename);  //重命名文件
                        }
                        catch (Exception e)
                        {
                            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                            {
                                MessageBox.Show("下载文件错误,请将下列内容反馈给我们,以方便进一步完善软件!\n(Ctrl+C 可复制 官方网站:www.4321.la)\n" + e.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                            });
                        }
                        finally
                        {
                            //歌词
                            if (!(string.IsNullOrEmpty(DownLoadList[id].DLrc)))
                            {
                                StreamWriter writer = new StreamWriter(filename.Replace(".mp3", ".lrc"));
                                writer.Write(DynamicLyrics);
                                writer.Close();
                            }
                            if (!(string.IsNullOrEmpty(DownLoadList[id].SLrc)))
                            {
                                WriteITunesLyrics(filename, StaticLyrics);
                            }

                            //下载专辑图片
                            if (DownLoadList[id].AutoAlbum)
                            {
                                WebClient mywebclient = new WebClient();
                                string    aurl        = DownLoadList[id].AlbumURL2;
                                string    newfilename = System.Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + "\\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".jpg";
                                try
                                {
                                    mywebclient.DownloadFile(aurl, newfilename);
                                }
                                catch (Exception ex)
                                {
                                    this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                                    {
                                        MessageBox.Show("下载文件错误,请将下列内容反馈给我们,以方便进一步完善软件!\n(Ctrl+C 可复制 官方网站:www.4321.la)\n" + ex.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                    });
                                }
                                finally
                                {
                                    mywebclient.Dispose();
                                    SetCover(filename, newfilename); //应用到MP3文件标签中
                                    FileInfo picfile = new FileInfo(@newfilename);
                                    picfile.Delete();                //删除专辑图片
                                }
                            }


                            //FixID3Tags
                            FixID3Tags(filename, DownLoadList[id].SongTitle, DownLoadList[id].Artist, DownLoadList[id].Album);

                            //自动添加到iTunes
                            if (DownLoadList[id].AutoiTunes)
                            {
                                FileInfo Fileo = new FileInfo(filename);
                                Fileo.CopyTo(System.Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + @"\iTunes\iTunes Media\自动添加到 iTunes\" + System.IO.Path.GetFileName(filename), true);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart) delegate()
                    {
                        MessageBox.Show("下载文件错误,请将下列内容反馈给我们,以方便进一步完善软件!\n(Ctrl+C 可复制 官方网站:www.4321.la)\n" + e.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    });
                }
                #endregion
            }
        }
Пример #43
0
        /// <summary>
        /// Methods to upload file to FTP Server
        /// </summary>
        /// <param name="_FileName">local source file name</param>
        /// <param name="_UploadPath">Upload FTP path including Host name</param>
        /// <param name="_FTPUser">FTP login username</param>
        /// <param name="_FTPPass">FTP login password</param>
        public static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass, bool isDeleteFile)
        {
            System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName);

            // Create FtpWebRequest object from the Uri provided
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));

            // Provide the WebPermission Credentials
            _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
            _FtpWebRequest.Proxy       = null;
            // _FtpWebRequest.ConnectionGroupName = _FileName;
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            _FtpWebRequest.KeepAlive = false;

            // set timeout for 20 seconds
            _FtpWebRequest.Timeout = 30000;

            // Specify the command to be executed.
            _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            _FtpWebRequest.UseBinary = true;

            // Notify the server about the size of the uploaded file
            _FtpWebRequest.ContentLength = _FileInfo.Length;

            // The buffer size is set to 2kb
            int buffLength = 1024 * 4;

            byte[] buff = new byte[buffLength];

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            System.IO.FileStream _FileStream = _FileInfo.OpenRead();

            System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();

            try
            {
                // Stream to which the file to be upload is written


                // Read from the file stream 2kb at a time
                int contentLen = _FileStream.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    _Stream.Write(buff, 0, contentLen);
                    contentLen = _FileStream.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                _Stream.Close();
                _Stream.Dispose();
                _FileStream.Close();
                _FileStream.Dispose();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (isDeleteFile)
                {
                    DeletePrintJobFile(_FileName);
                }
                if (_Stream != null)
                {
                    _Stream.Close();
                    _Stream.Dispose();
                }
                if (_FileStream != null)
                {
                    _FileStream.Close();
                    _FileStream.Dispose();
                }
                _FtpWebRequest = null;
            }
        }
Пример #44
0
    public bool Load(string Filename)
    {
        if (string.IsNullOrEmpty(Filename))
        {
            return(false);
        }
        if (!System.IO.File.Exists(Filename))
        {
            return(false);
        }

        this.Filename = Filename;

        Clear();

        System.IO.FileStream fs     = new System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        BinaryReader         Stream = new BinaryReader(fs);

        PreviewTex       = new Texture2D(0, 0);
        TexturemapTex    = new Texture2D(0, 0);
        TexturemapTex2   = new Texture2D(0, 0);
        NormalmapTex     = new Texture2D(0, 0);
        WatermapTex      = new Texture2D(0, 0);
        WaterDataTexture = new Texture2D(0, 0);

        byte[] TexturemapData  = new byte[0];
        byte[] TexturemapData2 = new byte[0];
        byte[] NormalmapData   = new byte[0];
        byte[] WatermapData    = new byte[0];


        int Count = 0;

        BinaryReader _with1 = Stream;

        //# Header Section #
        if (_with1.ReadInt32() == MAP_MAGIC)
        {
            VersionMajor = _with1.ReadInt32();
            //? always 2
            Unknown10 = _with1.ReadInt32();
            //? always EDFE EFBE
            Unknown11 = _with1.ReadInt32();
            //? always 2
            Unknown16 = _with1.ReadSingle();
            //Map Width (in float)
            Unknown17 = _with1.ReadSingle();
            //Map Height (in float)
            Unknown12 = _with1.ReadSingle();
            //? always 0
            Unknown13 = _with1.ReadInt16();
            //? always 0
            PreviewImageLength = _with1.ReadInt32();
            PreviewData        = _with1.ReadBytes(PreviewImageLength);

            VersionMinor = _with1.ReadInt32();
            if (VersionMinor <= 0)
            {
                VersionMinor = 56;
            }


            //# Heightmap Section #
            Width  = _with1.ReadInt32();
            Height = _with1.ReadInt32();

            HeightScale = _with1.ReadSingle();
            //Height Scale, usually 1/128

            HeightmapData = new ushort[(Height + 1) * (Width + 1)];
            for (int i = 0; i < HeightmapData.Length; i++)
            {
                HeightmapData[i] = _with1.ReadUInt16();
            }
            //HeightmapData = _with1.ReadInt16Array((Height + 1) * (Width + 1));//TODO: Current saving method gets a memory overload on trying to reload the map here.
            //heightmap dimension is always 1 more than texture dimension!

            if (VersionMinor >= 56)
            {
                Unknown15 = _with1.ReadByte();
            }
            else
            {
                Unknown15 = 0;
            }
            //Always 0?

            //# Texture Definition Section #
            TerrainShader = _with1.ReadStringNull();
            //Terrain Shader, usually "TTerrain"
            TexPathBackground = _with1.ReadStringNull();
            TexPathSkyCubemap = _with1.ReadStringNull();

            if (VersionMinor >= 56)
            {
                Count = _with1.ReadInt32();
                //always 1?
                EnvCubemapsName = new string[Count];
                EnvCubemapsFile = new string[Count];
                for (int i = 0; i <= Count - 1; i++)
                {
                    EnvCubemapsName[i] = _with1.ReadStringNull();
                    EnvCubemapsFile[i] = _with1.ReadStringNull();
                }
            }
            else
            {
                EnvCubemapsName    = new string[3];
                EnvCubemapsFile    = new string[3];
                EnvCubemapsName[0] = "<aeon>";
                EnvCubemapsName[1] = "<default>";
                EnvCubemapsName[2] = "<seraphim>";
                EnvCubemapsFile[0] = "/textures/environment/envcube_aeon_evergreen.dds";
                EnvCubemapsFile[1] = _with1.ReadStringNull();
                EnvCubemapsFile[2] = "/textures/environment/envcube_seraphim_evergreen.dds";
            }

            LightingMultiplier = _with1.ReadSingle();
            SunDirection       = _with1.ReadVector3();
            SunAmbience        = _with1.ReadVector3();
            SunColor           = _with1.ReadVector3();
            ShadowFillColor    = _with1.ReadVector3();
            SpecularColor      = _with1.ReadVector4();
            Bloom = _with1.ReadSingle();

            FogColor = _with1.ReadVector3();
            FogStart = _with1.ReadSingle();
            FogEnd   = _with1.ReadSingle();


            Water.Load(Stream);

            Count = _with1.ReadInt32();
            WaveGenerators.Clear();
            for (int i = 0; i <= Count - 1; i++)
            {
                WaveGenerator WaveGen = new WaveGenerator();
                WaveGen.Load(Stream);
                WaveGenerators.Add(WaveGen);
            }

            if (VersionMinor < 56)
            {
                _with1.ReadStringNull();
                // always "No Tileset"
                Count = _with1.ReadInt32();
                //always 6
                for (int i = 0; i <= 4; i++)
                {
                    Layer Layer = new Layer();
                    Layer.Load(Stream);
                    Layers.Add(Layer);
                }
                for (int i = 5; i <= 8; i++)
                {
                    Layers.Add(new Layer());
                }
                for (int i = 9; i <= 9; i++)
                {
                    Layer Layer = new Layer();
                    Layer.Load(Stream);
                    Layers.Add(Layer);
                }
            }
            else
            {
                MinimapContourInterval = _with1.ReadInt32();

                int argb = _with1.ReadInt32();
                MinimapDeepWaterColor = Int32ToColor(argb);

                /*int r = (argb)&0xFF;
                 * int g = (argb>>8)&0xFF;
                 * int b = (argb>>16)&0xFF;
                 * int a = (argb>>24)&0xFF;
                 * MinimapDeepWaterColor = new Color(r,g,b,a);*/
                int argb2 = _with1.ReadInt32();

                /*int r2 = (argb2)&0xFF;
                 * int g2 = (argb2>>8)&0xFF;
                 * int b2 = (argb2>>16)&0xFF;
                 * int a2 = (argb2>>24)&0xFF;
                 * MinimapContourColor = new Color(r2,g2,b2,a2);*/
                MinimapContourColor = Int32ToColor(argb2);
                int argb3 = _with1.ReadInt32();

                /*int r3 = (argb3)&0xFF;
                 * int g3 = (argb3>>8)&0xFF;
                 * int b3 = (argb3>>16)&0xFF;
                 * int a3 = (argb3>>24)&0xFF;
                 * MinimapShoreColor = new Color(r3,g3,b3,a3);*/
                MinimapShoreColor = Int32ToColor(argb3);
                int argb4 = _with1.ReadInt32();

                /*int r4 = (argb4)&0xFF;
                 * int g4 = (argb4>>8)&0xFF;
                 * int b4 = (argb4>>16)&0xFF;
                 * int a4 = (argb4>>24)&0xFF;
                 * MinimapLandStartColor = new Color(r4,g4,b4,a4);*/
                MinimapLandStartColor = Int32ToColor(argb4);
                int argb5 = _with1.ReadInt32();

                /*int r5 = (argb5)&0xFF;
                 * int g5 = (argb5>>8)&0xFF;
                 * int b5 = (argb5>>16)&0xFF;
                 * int a5 = (argb5>>24)&0xFF;
                 * MinimapLandEndColor = new Color(r5,g5,b5,a5);*/
                MinimapLandEndColor = Int32ToColor(argb5);

                if (VersionMinor > 56)
                {
                    Unknown14 = _with1.ReadSingle(); //Not sure what this is.
                }
                Count = 10;
                for (int i = 0; i <= Count - 1; i++)
                {
                    Layer Layer = new Layer();
                    Layer.LoadAlbedo(Stream);
                    Layers.Add(Layer);
                }
                for (int i = 0; i <= Count - 2; i++)
                {
                    Layers[i].LoadNormal(Stream);
                }
            }
            Unknown7 = _with1.ReadInt32();
            //?
            Unknown8 = _with1.ReadInt32();
            //?

            int DecalCount = _with1.ReadInt32();
            //Debug.Log(DecalCount);
            for (int i = 0; i < DecalCount; i++)
            {
                Decal Feature = new Decal();
                Feature.Load(Stream);
                Decals.Add(Feature);
            }

            int GroupCount = _with1.ReadInt32();
            for (int i = 0; i <= GroupCount - 1; i++)
            {
                IntegerGroup Group = new IntegerGroup();
                Group.Load(Stream);
                DecalGroups.Add(Group);
            }

            _with1.ReadInt32();
            //Width again
            _with1.ReadInt32();
            //Height again

            int Length         = 0;
            int NormalmapCount = _with1.ReadInt32();
            //always 1
            for (int i = 0; i < NormalmapCount; i++)
            {
                Length = _with1.ReadInt32();
                if (i == 0)
                {
                    NormalmapData = _with1.ReadBytes(Length);
                }
                else
                {
                    _with1.BaseStream.Position += Length;
                    // just to make sure that it doesn't crash if it is not just 1 normalmap for some reason
                }
            }


            if (VersionMinor < 56)
            {
                _with1.ReadInt32();
            }
            //always 1
            Length         = _with1.ReadInt32();
            TexturemapData = _with1.ReadBytes(Length);

            if (VersionMinor >= 56)
            {
                Length          = _with1.ReadInt32();
                TexturemapData2 = _with1.ReadBytes(Length);
            }


            //Watermap
            _with1.ReadInt32();
            //always 1
            Length       = _with1.ReadInt32();
            WatermapData = _with1.ReadBytes(Length);

            int HalfSize = (Width / 2) * (Height / 2);
            WaterFoamMask      = _with1.ReadBytes(HalfSize);
            WaterFlatnessMask  = _with1.ReadBytes(HalfSize);
            WaterDepthBiasMask = _with1.ReadBytes(HalfSize);

            WaterDataTexture = new Texture2D(Width / 2, Height / 2, TextureFormat.RGB24, false);
            Color32[] NewColors = new Color32[HalfSize];
            for (int i = 0; i < HalfSize; i++)
            {
                NewColors [i] = new Color32(WaterFoamMask [i], WaterFlatnessMask [i], WaterDepthBiasMask [i], 0);
            }
            WaterDataTexture.SetPixels32(NewColors);
            WaterDataTexture.Apply();

            TerrainTypeData = _with1.ReadBytes(Width * Height);
//            TerrainTypeData = _with1.ReadBytes(Width * Height).ToList();

            if (VersionMinor <= 52)
            {
                _with1.ReadInt16();
            }


            //Debug.Log("Scmap file version: " + VersionMinor);

            if (VersionMinor >= 60)
            {
                AdditionalSkyboxData.Load(_with1);
            }
            else
            {
                ScmapEditor.Current.LoadDefaultSkybox();
            }


            try{
                int PropCount = _with1.ReadInt32();
                //Debug.Log ("PropCount: " + PropCount + ", v" + VersionMinor );
                for (int i = 0; i < PropCount; i++)
                {
                    Prop Prop = new Prop();
                    Prop.Load(Stream);
                    Props.Add(Prop);
                    //Debug.Log(Prop.BlueprintPath);
                }
            }
            catch {
                Debug.LogError("Loading props crashed");
            }
        }
        _with1.Close();
        fs.Close();
        fs.Dispose();

        PreviewTextHeader        = GetGamedataFile.GetDdsFormat(PreviewData);
        PreviewTextHeader.Format = TextureFormat.BGRA32;
        PreviewTex = TextureLoader.ConvertToRGBA(TextureLoader.LoadTextureDXT(PreviewData, PreviewTextHeader));

        TextureMapHeader        = GetGamedataFile.GetDdsFormat(TexturemapData);
        TextureMapHeader.Format = TextureFormat.BGRA32;
        //TexturemapTex = TextureLoader.LoadTextureDXT(TexturemapData, TextureMapHeader);
        TexturemapTex  = TextureLoader.ConvertToRGBA(TextureLoader.LoadTextureDXT(TexturemapData, TextureMapHeader));
        TexturemapData = new byte[0];

        if (TexturemapData2.Length > 0)
        {
            TextureMap2Header        = GetGamedataFile.GetDdsFormat(TexturemapData2);
            TextureMap2Header.Format = TextureFormat.BGRA32;
            TexturemapTex2           = TextureLoader.ConvertToRGBA(TextureLoader.LoadTextureDXT(TexturemapData2, TextureMap2Header));
            TexturemapData2          = new byte[0];
        }
        else
        {
            TextureMap2Header = TextureMapHeader;
            TexturemapTex2    = new Texture2D(Width / 2, Height / 2);
            Color[] Pixels = TexturemapTex2.GetPixels();
            for (int p = 0; p < Pixels.Length; p++)
            {
                Pixels[p] = new Color(0, 0, 0, 0);
            }
            TexturemapTex2.SetPixels(Pixels);
            TexturemapTex2.Apply();
        }
        TexturemapTex.wrapMode  = TextureWrapMode.Clamp;
        TexturemapTex2.wrapMode = TextureWrapMode.Clamp;

        NormalmapHeader        = GetGamedataFile.GetDdsFormat(NormalmapData);
        NormalmapHeader.Format = TextureFormat.DXT5;
        NormalmapTex           = TextureLoader.LoadTextureDXT(NormalmapData, NormalmapHeader);
        NormalmapData          = new byte[0];

        UncompressedNormalmapTex = new Texture2D(NormalmapTex.width, NormalmapTex.height, TextureFormat.RGBA32, false);
        UncompressedNormalmapTex.SetPixels(NormalmapTex.GetPixels());
        UncompressedNormalmapTex.wrapMode = TextureWrapMode.Clamp;
        UncompressedNormalmapTex.Apply();

        WatermapHeader        = GetGamedataFile.GetDdsFormat(WatermapData);
        WatermapHeader.Format = TextureFormat.DXT5;
        WatermapTex           = TextureLoader.LoadTextureDXT(WatermapData, WatermapHeader);
        WatermapData          = new byte[0];

        UncompressedWatermapTex = new Texture2D(WatermapTex.width, WatermapTex.height, TextureFormat.RGBA32, false);
        UncompressedWatermapTex.SetPixels(WatermapTex.GetPixels());
        UncompressedWatermapTex.wrapMode = TextureWrapMode.Clamp;

        UncompressedWatermapTex.Apply();

        if (VersionMinor < 56)
        {
            ConvertToV56();
        }

        return(true);
    }
Пример #45
0
        private static void ReleaseJos(DataSet dsJobs, string serviceName)
        {
            // Get Distinct MFPs

            //For MFPs{
            // Get the job release request for one MFP

            // Get FTP Details

            // Open FTP Connection

            // Loop through Files

            // Clost FTP Connection

            //}

            bool isJobReleaseWithSettings = false;
            bool isJobSettingsChanged     = false;

            string        jobFilePath        = null;
            string        destinationFTPPath = string.Empty;
            string        ftpUserName        = string.Empty;
            string        ftpUserPassword    = string.Empty;
            string        message            = string.Empty;
            DataSet       tempDataSet        = new DataSet();
            StringBuilder sbRecSysId         = new StringBuilder();
            string        mfpIP            = string.Empty;
            string        jobFileName      = string.Empty;
            string        printSettingType = string.Empty;

            byte[]        SendingBuffer    = null;
            TcpClient     client           = null;
            bool          isJobTransmitted = false;
            NetworkStream netstream        = null;
            int           BufferSize       = 8 * 1024 * 1024;

            try
            {
                //dsJobs = RemoveRequestFileNotExists(dsJobs);
                tempDataSet.Tables.Add(dsJobs.Tables[0].Copy());

                for (int mfpIndex = 0; mfpIndex < dsJobs.Tables[1].Rows.Count; mfpIndex++)
                {
                    message = string.Format("Received Job release request @ {0}", DateTime.Now.ToString());
                    LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Detailed, message, "", "", "");

                    //message = string.Format("Processing file# {0}", mfpIndex);
                    //LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Information, message, "", "", "");

                    mfpIP = dsJobs.Tables[1].Rows[mfpIndex]["JOB_REQUEST_MFP"].ToString();
                    var row = dsJobs.Tables[0].AsEnumerable().FirstOrDefault(r => r.Field <string>("JOB_REQUEST_MFP") == mfpIP);
                    if (row != null)
                    {
                        printSettingType = row["JOB_PRINT_TYPE"].ToString();
                    }

                    if (printSettingType.ToLower() == "dir")
                    {
                        string jobFileNameTCP;

                        foreach (DataRow drJob in dsJobs.Tables[0].Rows)
                        {
                            if (drJob["JOB_REQUEST_MFP"].ToString() == mfpIP)
                            {
                                DataRow drPrintJob = drJob as DataRow;
                                jobFileNameTCP = drPrintJob["JOB_FILE"].ToString();
                                int tcpPort = 9100;

                                try
                                {
                                    tcpPort = int.Parse(drJob["MFP_DIR_PRINT_PORT"].ToString());
                                }
                                catch
                                { }
                                client = new TcpClient(drJob["JOB_REQUEST_MFP"].ToString(), tcpPort);

                                netstream = client.GetStream();
                                FileStream jobStream   = new FileStream(jobFileNameTCP, FileMode.Open, FileAccess.Read);
                                int        NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(jobStream.Length) / Convert.ToDouble(BufferSize)));

                                int TotalLength = (int)jobStream.Length, CurrentPacketLength, counter = 0;

                                for (int i = 0; i < NoOfPackets; i++)
                                {
                                    if (TotalLength > BufferSize)
                                    {
                                        CurrentPacketLength = BufferSize;
                                        TotalLength         = TotalLength - CurrentPacketLength;
                                    }
                                    else
                                    {
                                        CurrentPacketLength = TotalLength;
                                    }
                                    SendingBuffer = new byte[CurrentPacketLength];
                                    jobStream.Read(SendingBuffer, 0, CurrentPacketLength);
                                    netstream.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
                                }

                                jobStream.Close();
                            }
                        }
                    }


                    else
                    {
                        if (row != null)
                        {
                            if (row != null)
                            {
                                destinationFTPPath = row["JOB_FTP_PATH"].ToString();
                                ftpUserName        = row["JOB_FTP_ID"].ToString();
                                ftpUserPassword    = row["JOB_FTP_PASSWORD"].ToString();
                            }
                            message = string.Format("Opening MFP connection @ {0}", DateTime.Now.ToString());
                            LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Detailed, message, "", "", "");

                            // Create FtpWebRequest object from the Uri provided
                            System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(destinationFTPPath));

                            // Provide the WebPermission Credintials
                            ftpWebRequest.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpUserPassword);
                            string enableFTPProxy   = "false";
                            string ftpProxyUri      = string.Empty;
                            string ftpProxyUser     = string.Empty;
                            string ftpProxyDomain   = string.Empty;
                            string ftpProxyPassword = string.Empty;

                            try
                            {
                                enableFTPProxy = ConfigurationManager.AppSettings["EnableFTPProxy"];
                            }
                            catch (Exception)
                            {
                            }

                            if (!string.IsNullOrEmpty(enableFTPProxy))
                            {
                                enableFTPProxy = "false";
                            }


                            if (enableFTPProxy == "false")
                            {
                                ftpWebRequest.Proxy = null;
                            }
                            else if (enableFTPProxy == "true")
                            {
                                try
                                {
                                    ftpProxyUri      = ConfigurationManager.AppSettings["FTPProxy_Uri"];
                                    ftpProxyUser     = ConfigurationManager.AppSettings["FTPProxy_User"];
                                    ftpProxyDomain   = ConfigurationManager.AppSettings["FTPProxy_Domain"];
                                    ftpProxyPassword = ConfigurationManager.AppSettings["FTPProxy_Password"];

                                    System.Net.WebProxy webProxy = new System.Net.WebProxy();
                                    webProxy.Address            = new Uri(ftpProxyUri);
                                    webProxy.BypassProxyOnLocal = true;
                                    webProxy.Credentials        = new System.Net.NetworkCredential(ftpProxyUser, ftpProxyPassword, ftpProxyDomain);

                                    ftpWebRequest.Proxy = webProxy;
                                }
                                catch (Exception) { }
                            }

                            //ftpWebRequest.ConnectionGroupName = mfpIP;
                            // By default KeepAlive is true, where the control connection is not closed
                            // after a command is executed.
                            ftpWebRequest.KeepAlive = false;

                            //ftpWebRequest.UsePassive

                            // set timeout for 20 seconds
                            ftpWebRequest.Timeout = 20000;

                            // Specify the command to be executed.
                            //ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //uncomment********

                            // Specify the data transfer type.
                            ftpWebRequest.UseBinary = true;
                            System.IO.Stream stream = null;
                            //ftpWebRequest.GetRequestStream(); //uncomment*********

                            foreach (DataRow drJob in dsJobs.Tables[0].Rows)
                            {
                                if (drJob["JOB_REQUEST_MFP"].ToString() == mfpIP)
                                {
                                    GetFilePathNewSetting(serviceName, ref isJobReleaseWithSettings, ref isJobSettingsChanged, ref jobFilePath, drJob);

                                    message = string.Format("File Transfer to MFP started @ {0}", DateTime.Now.ToString());
                                    LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Detailed, message, "", "", "");

                                    string   jobFile           = null;
                                    DateTime dtJobReleaseStart = DateTime.Now;

                                    DataRow drPrintJob = drJob as DataRow;
                                    string  jobDBID    = drPrintJob["REC_SYSID"].ToString();
                                    jobFileName = drPrintJob["JOB_FILE"].ToString();
                                    if (!string.IsNullOrEmpty(jobFile))
                                    {
                                        jobFileName = jobFile;
                                    }
                                    if (isJobReleaseWithSettings == true && isJobSettingsChanged == true)
                                    {
                                        jobFileName = jobFilePath;
                                    }

                                    string isDeleteFile = drPrintJob["DELETE_AFTER_PRINT"].ToString();
                                    // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                                    if (File.Exists(jobFileName))
                                    {
                                        //string encryptedFile = jobFileName;
                                        //System.IO.FileInfo fileInfoEn = new System.IO.FileInfo(jobFileName);



                                        //string oldname = fileInfoEn.Name;
                                        //string newName = "New" + oldname;

                                        //string decryptedFile = jobFileName.Replace(oldname, newName);


                                        //string encryptFile = ConfigurationManager.AppSettings["Key2"].ToLower();

                                        //Cryptography.Encryption.Decrypt(jobFileName, decryptedFile);



                                        // ByteArrayToString(byt);

                                        int           bIsRenderToPDF   = 1;
                                        uint          bwPageCount      = 0;
                                        uint          colorPageCount   = 0;
                                        uint          copyCount        = 0;
                                        double        nPageWidth       = 0;
                                        double        nPageHeight      = 0;
                                        StringBuilder strPaperSizeName = new StringBuilder(300);

                                        ReadInfoSetCode("XXXXXXXXXXXXXXXXXX");
                                        ReadInfoFromAllFormats(jobFileName, bIsRenderToPDF, ref bwPageCount, ref colorPageCount, ref copyCount, ref nPageWidth, ref nPageHeight, strPaperSizeName);
                                        LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Information, bwPageCount.ToString() + "<-BW-Color->" + colorPageCount.ToString(), "", "", "");



                                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(jobFileName);
                                        // Stream to which the file to be upload is written
                                        System.IO.FileStream fileStream = fileInfo.OpenRead();

                                        try
                                        {
                                            // Notify the server about the size of the uploaded file
                                            ftpWebRequest.ContentLength = fileInfo.Length;

                                            // The buffer size is set to 4MB
                                            int    buffLength = 4 * 1024 * 1024;
                                            byte[] buff       = new byte[buffLength];

                                            // Read from the file stream 4MB at a time
                                            int contentLen = fileStream.Read(buff, 0, buffLength);

                                            // Till Stream content ends
                                            while (contentLen != 0)
                                            {
                                                // Write Content from the file stream to the FTP Upload Stream
                                                stream.Write(buff, 0, contentLen);
                                                contentLen = fileStream.Read(buff, 0, buffLength);
                                            }

                                            // Close the file stream and the Request Stream

                                            fileStream.Close();
                                            fileStream.Dispose();

                                            DateTime dtJobReleaseEnd = DateTime.Now;
                                            UpdateJobReleaseTimings(serviceName, drPrintJob["JOB_FILE"].ToString().Replace("_PDFinal", "_PD"), dtJobReleaseStart, dtJobReleaseEnd, jobDBID);

                                            if (isDeleteFile.ToLower() == "true")
                                            {
                                                //DeletePrintJobsFile(serviceName, decryptedFile);
                                                DeletePrintJobsFile(serviceName, jobFileName);
                                            }

                                            //if (File.Exists(jobFileName))
                                            //{
                                            //    DeletePrintJobsFile(serviceName, decryptedFile);
                                            //}
                                            //Delete released jobs from tempDataset
                                            try
                                            {
                                                DataRow[] dtRow = tempDataSet.Tables[0].Select("REC_SYSID=' " + jobDBID + " ' ");
                                                for (int i = 0; i < dtRow.Length; i++)
                                                {
                                                    dtRow[i].Delete();
                                                }
                                                tempDataSet.Tables[0].AcceptChanges();
                                            }
                                            catch
                                            {
                                            }

                                            message = string.Format("File transferred to MFP : {1} , file : {0}", jobFileName, mfpIP);

                                            LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Information, message, "", "", "");
                                        }
                                        catch (Exception ex)
                                        {
                                            LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Exception, "Failed to Transfer file : " + jobFileName + " to MFP : " + mfpIP + " <br/>" + ex.Message, "Restart the Print Data Provider Service", ex.Message, ex.StackTrace);
                                        }
                                        finally
                                        {
                                            if (fileStream != null)
                                            {
                                                fileStream.Close();
                                                fileStream.Dispose();
                                            }
                                        }
                                    }
                                }
                            }
                            if (stream != null)
                            {
                                stream.Close();
                                stream.Dispose();
                            }

                            message = string.Format("Closing MFP connection  @ {0}", DateTime.Now.ToString());
                            LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Detailed, message, "", "", "");
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                message = string.Format("Failed to transfer data to MFP : {1} file : {2} @ {0}", DateTime.Now.ToString(), mfpIP, jobFileName);
                LogManager.RecordMessage(serviceName, "ReleaseJobs", LogManager.MessageType.Exception, message + "<br/>" + ex.Message, "", "", "");
            }

            finally
            {
                try
                {
                    for (int i = 0; i < tempDataSet.Tables[0].Rows.Count; i++)
                    {
                        sbRecSysId.Append(tempDataSet.Tables[0].Rows[i]["REC_SYSID"].ToString() + ",");
                    }

                    if (!string.IsNullOrEmpty(sbRecSysId.ToString()))
                    {
                        string sqlQuery = string.Format("exec UpdateFileTransferDetails '{0}'", sbRecSysId.ToString());

                        using (Database database = new Database())
                        {
                            database.ExecuteNonQuery(database.GetSqlStringCommand(sqlQuery));
                        }
                    }
                }
                catch
                {
                }
            }
        }
Пример #46
0
        public Result Txn249999(ClientInfo ci, RequestInfo ri, DbConnections db, ref Log lg)
        {
            Result res = new Result();

            try
            {
                object[]  param    = new object[1];
                string    ViewName = "";
                Hashtable colindex = new Hashtable();
                string    query    = "";
                if (Static.ToInt(ri.ReceivedParam[1]) == 0)
                {
                    Excel.Application xlsm         = new Excel.Application();
                    Excel.Workbook    xlsWorkBook  = xlsm.Workbooks.Open(@Static.ToStr(ri.ReceivedParam[0]), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                    Excel.Worksheet   xlsWorkSheet = xlsWorkBook.Worksheets[1];
                    ViewName = xlsWorkSheet.Name;
                    for (int i = 1; i <= xlsWorkSheet.UsedRange.Columns.Count; i++)
                    {
                        if (!colindex.ContainsKey(xlsWorkSheet.Cells[1, i].Value.ToString()))
                        {
                            colindex.Add(xlsWorkSheet.Cells[1, i].Value.ToString(), i);
                        }
                        else
                        {
                            colindex.Clear();
                            res.ResultNo   = 9110146;
                            res.ResultDesc = string.Format("Тайлангын загвар алдаатай байна. {0} талбар өмнө нь үүссэн байна.", xlsWorkSheet.Cells[1, i].Value);
                            return(res);
                        }
                    }
                    res = IPos.DB.Main.DB202351(db, Static.ToStr(ViewName));
                    if (res.ResultNo != 0)
                    {
                        colindex.Clear();
                        return(res);
                    }
                    object[] obj = new object[2];
                    obj[0]    = colindex;
                    obj[1]    = ViewName;
                    res.Param = obj;
                }
                else
                {
                    int rowindex                   = 2;
                    Excel.Application xlsm         = new Excel.Application();
                    Excel.Workbook    xlsWorkBook  = xlsm.Workbooks.Open(@Static.ToStr(ri.ReceivedParam[0]), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                    Excel.Worksheet   xlsWorkSheet = xlsWorkBook.Worksheets[1];
                    ViewName = xlsWorkSheet.Name;
                    StringBuilder sb      = new StringBuilder();
                    object[]      prop    = (object[])ri.ReceivedParam[2];
                    bool          isfirst = false;
                    bool          iswhere = false;
                    if (prop.Count() > 0)
                    {
                        for (int i = 0; i < prop.Count() / 3; i = i + 3)
                        {
                            if (prop[i + 2] != null && prop[i + 2] != "")
                            {
                                if (isfirst == false)
                                {
                                    if (Static.ToStr(prop[i + 1]).ToUpper() == "LIKE")
                                    {
                                        sb.Append(Static.ToStr(prop[i]));
                                        sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1])));
                                        sb.Append(string.Format("'{0}%'", Static.ToStr(prop[i + 2])));
                                        isfirst = true;
                                    }
                                    else
                                    {
                                        sb.Append(Static.ToStr(prop[i]));
                                        sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1])));
                                        sb.Append(Static.ToStr(prop[i + 2]));
                                        isfirst = true;
                                    }
                                }
                                else
                                {
                                    if (Static.ToStr(prop[i + 1]).ToUpper() == "LIKE")
                                    {
                                        sb.Append(" and ");
                                        sb.Append(Static.ToStr(prop[i]));
                                        sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1])));
                                        sb.Append(string.Format("'{0}%'", Static.ToStr(prop[i + 2])));
                                        isfirst = true;
                                    }
                                    else
                                    {
                                        sb.Append(" and ");
                                        sb.Append(Static.ToStr(prop[i]));
                                        sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1])));
                                        sb.Append(Static.ToStr(prop[i + 2]));
                                        iswhere = true;
                                    }
                                }
                            }
                        }
                        if (isfirst == true || iswhere == true)
                        {
                            query = string.Format("select * from {0} where {1}", ViewName, sb.ToString());
                        }
                        else
                        {
                            query = string.Format("select * from {0}", ViewName);
                        }
                    }
                    else
                    {
                        query = string.Format("select * from {0}", ViewName);
                    }
                    res = db.ExecuteQuery("core", query, enumCommandType.SELECT, "Txn249999", null);
                    if (res.ResultNo != 0)
                    {
                        return(res);
                    }

                    colindex = (Hashtable)ri.ReceivedParam[3];
                    foreach (DataRow row in res.Data.Tables[0].Rows)
                    {
                        foreach (DictionaryEntry fieldname in colindex)
                        {
                            xlsWorkSheet.Cells[rowindex, Convert.ToInt32(fieldname.Value)].Value = row[fieldname.Key.ToString()];
                        }
                        rowindex++;
                    }

                    string temp     = Path.GetTempPath();
                    string filepath = string.Format(@temp + @"rep{0}.xlsm", DateTime.Now.Ticks);
                    xlsWorkBook.SaveCopyAs(filepath);

                    byte[] _Buffer = null;
                    System.IO.FileStream   _FileStream   = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
                    long _TotalBytes = new System.IO.FileInfo(@Static.ToStr(ri.ReceivedParam[0])).Length;
                    _Buffer  = _BinaryReader.ReadBytes((Int32)_TotalBytes);
                    param[0] = _Buffer;
                    _FileStream.Dispose();
                    _FileStream.Close();
                    _BinaryReader.Dispose();
                    _BinaryReader.Close();
                    colindex.Clear();
                    Result result = new Result();
                    result.Param = param;
                    return(result);
                }
                return(res);
            }
            catch (Exception ex)
            {
                res.ResultNo   = 9110002;
                res.ResultDesc = "Програм руу нэвтрэхэд алдаа гарлаа" + ex.Message;

                EServ.Shared.Static.WriteToLogFile("Error.log", ex.Message + ex.Source + ex.StackTrace);

                return(res);
            }
            finally
            {
                lg.item.Desc = "Excel тайлангийн жагсаалт авах";
            }
        }
Пример #47
0
        private void ProcessRequest(HttpListenerContext context)
        {
            HttpListenerResponse response = context.Response;
            HttpListenerRequest  request  = context.Request;

            try
            {
                if (request.HttpMethod.ToLower().Equals("get"))
                {
                    string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl);

                    #region 获取版本信息
                    if (rawUrl.StartsWith(search_version))
                    {
                        string groupid = context.Request.QueryString["groupid"];

                        XmlSerializerWrapper <RFEntity.XmlUpdateFiles> xmlSerializer_UpdateFiles = new XmlSerializerWrapper <RFEntity.XmlUpdateFiles>();
                        List <RFEntity.UpdateFile> lstUpdateFile = xmlSerializer_UpdateFiles.Entity.lstupdatefiles;
                        if (lstUpdateFile != null && lstUpdateFile.Count > 0)
                        {
                            RFEntity.UpdateFile file = lstUpdateFile.Find(item => { return(item.groupid.ToString() == groupid); });
                            if (file != null)
                            {
                                string files = JsonHelper.GetJson(file);
                                Response(context, files);
                            }
                        }
                    }
                    #endregion

                    #region  载文件
                    if (rawUrl.StartsWith(download_files))
                    {
                        string groupid     = context.Request.QueryString["groupid"];
                        string versioninfo = context.Request.QueryString["versioninfo"];

                        XmlSerializerWrapper <RFEntity.XmlUpdateFiles> xmlSerializer_UpdateFiles = new XmlSerializerWrapper <RFEntity.XmlUpdateFiles>();
                        List <RFEntity.UpdateFile> lstUpdateFile = xmlSerializer_UpdateFiles.Entity.lstupdatefiles;
                        if (lstUpdateFile != null && lstUpdateFile.Count > 0)
                        {
                            RFEntity.UpdateFile file = lstUpdateFile.Find(item => { return(item.groupid.ToString() == groupid && item.versioninfo == versioninfo); });
                            if (file != null && !string.IsNullOrEmpty(file.filepath) && File.Exists(file.filepath))
                            {
                                response.StatusCode = 200;

                                FileStream fileStream = new System.IO.FileStream(file.filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                                int        l          = 0;
                                byte[]     fileBytes  = new byte[1024];
                                while ((l = fileStream.Read(fileBytes, 0, fileBytes.Length)) > 0)
                                {
                                    response.OutputStream.Write(fileBytes, 0, l);
                                }
                                fileStream.Close();
                                fileStream.Dispose();
                                response.OutputStream.Close();
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                myLogFile.WriteErrLogFile("客户端获取文件信息异常" + request.RemoteEndPoint.Address + ";" + ex);
            }

            try
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            catch
            {
            }
        }
Пример #48
0
        private void bgW_DoWork(object sender, DoWorkEventArgs e)
        {
            {
                try
                {
                    chkLDAP.Enabled  = false;
                    txtFile.ReadOnly = true;
                    btnStart.Text    = "Cancel Backup";
                    CheckForIllegalCrossThreadCalls = false;
                    var    appSettings  = ConfigurationManager.AppSettings;
                    string checkreplace = ConfigurationManager.AppSettings["checkreplace"];
                    string userfile     = txtFile.Text;
                    int    counter      = 0;
                    proBar1.Visible = true;
                    // Take a peek inside our users file!
                    // enumerate through each domain account and check for changed
                    // or new files.

                    if (userfile.Length >= 1)
                    {
                        if (bgW.CancellationPending)
                        {
                            e.Cancel        = true;
                            stripLabel.Text = "Operation was canceled!";
                            return;
                        }
                        string[] users = File.ReadAllLines(userfile);


                        for (int z = 0; z >= counter; z++)
                        {
                            if (bgW.CancellationPending)
                            {
                                e.Cancel        = true;
                                stripLabel.Text = "Operation was canceled!";
                                return;
                            }
                            string names = users[z];
                            if (users != null)
                            {
                                try
                                {
                                    proBar1.Visible = true;
                                    stripLabel.Text = "";
                                    Console.WriteLine("Selecting user: "******"Selecting user: "******"savelocation"] + user + "\\";
                                    FileInfo testdir      = new FileInfo(savelocation);
                                    //Console.WriteLine("New directory created at: " + testdir);
                                    testdir.Directory.Create();
                                    string       savedStartPageToken = "";
                                    var          start   = CreateService.BuildService(user).Changes.GetStartPageToken().Execute();
                                    StreamWriter logFile = new StreamWriter(savelocation + ".recent.log");

                                    // This token is set by Google, it defines changes made and
                                    // increments the token value automatically.
                                    // The following reads the current token file (if it exists)
                                    if (File.Exists(savelocation + ".currenttoken.tok"))
                                    {
                                        StreamReader curtokenfile = new StreamReader(savelocation + ".currenttoken.tok");
                                        savedStartPageToken = curtokenfile.ReadLine().ToString();
                                        curtokenfile.Close();
                                        curtokenfile.Dispose();
                                    }
                                    else
                                    {
                                        // Token record didn't exist. Create a generic file, start at "1st" token
                                        // In reality, I have no idea what token to start at, but 1 seems to be safe.
                                        Console.Write("Creating new token file.\n");
                                        txtLog.Text += ("Creating new token file.\n" + Environment.NewLine);
                                        StreamWriter sw = new StreamWriter(savelocation + ".currenttoken.tok");
                                        sw.Write(1);
                                        sw.Close();
                                        sw.Dispose();
                                        savedStartPageToken = "1";
                                    }
                                    proBar1.Value = 0;
                                    Console.WriteLine("Previous user token: " + savedStartPageToken);
                                    txtLog.Text += ("Previous user token: " + savedStartPageToken + Environment.NewLine);
                                    Console.WriteLine("My brand new token --->: " + start.StartPageTokenValue);
                                    txtLog.Text += ("Current user token: " + start.StartPageTokenValue + Environment.NewLine);
                                    Console.Write("Logging into your Gapps domain as: " + user + "\nChecking for any existing files...\nPlease wait as this may take a while.\n");
                                    txtLog.Text  += ("Now logging into your Gapps domain as: " + user + Environment.NewLine + "Please wait as this may take a while." + Environment.NewLine);
                                    proBar1.Value = 0;
                                    string pageToken = savedStartPageToken;
                                    int    gtoken    = int.Parse(start.StartPageTokenValue);
                                    int    mytoken   = int.Parse(savedStartPageToken);
                                    txtPrevToken.Text    = pageToken.ToString();
                                    txtCurrentToken.Text = gtoken.ToString();

                                    if (gtoken <= 10)
                                    {
                                        Console.WriteLine("Nothing to save!\n");
                                        txtLog.Text += ("User has nothing to save!" + Environment.NewLine);
                                    }
                                    else
                                    {
                                        if (pageToken == start.StartPageTokenValue)
                                        {
                                            Console.WriteLine("No file changes found for " + user + "\n");
                                            txtLog.Text += ("No file changes found! Please wait while I tidy up." + Environment.NewLine);
                                        }
                                        else
                                        {
                                            // .deltalog.tok is where we will place our records for changed files
                                            Console.WriteLine("Changes detected. Making notes while we go through these.");
                                            if (File.Exists(savelocation + ".deltalog.tok"))
                                            {
                                                File.Delete(savelocation + ".deltalog.tok");
                                            }
                                            lblProgresslbl.Text = "Scanning Drive directory.";
                                            using (StreamWriter deltalog = new StreamWriter(savelocation + ".deltalog.tok", true))
                                            {
                                                StreamWriter folderlog = new StreamWriter(savelocation + "folderlog.txt", true);
                                                while (pageToken != null)
                                                {
                                                    counter1++;
                                                    var request = CreateService.BuildService(user).Changes.List(pageToken);

                                                    request.Spaces = "drive";
                                                    request.Fields = "*";

                                                    DateTime dt = DateTime.Now;

                                                    var changes = request.Execute();

                                                    foreach (var change in changes.Changes)
                                                    {
                                                        if (bgW.CancellationPending)
                                                        {
                                                            e.Cancel        = true;
                                                            stripLabel.Text = "Operation was canceled!";
                                                            return;
                                                        }
                                                        try
                                                        {
                                                            string   updatedfile = change.File.Name;
                                                            string   mimetype    = change.File.MimeType;
                                                            string   folderid    = String.Join(",", change.File.Parents);
                                                            string   dirname     = (savelocation + updatedfile + "\\");
                                                            FileInfo newdir      = new FileInfo(dirname);

                                                            // If it's a folder, let's create it now so we can move files into it later.
                                                            if (mimetype == "application/vnd.google-apps.folder")
                                                            {
                                                                newdir.Directory.Create();
                                                                logFile.WriteLine("Directory " + dirname + " was successfully created!");
                                                                Console.WriteLine("Directory " + dirname + " was successfully created!\n");
                                                                folderlog.WriteLine(change.FileId + "," + dirname);
                                                                folderlog.Flush();
                                                            }
                                                            else
                                                            {
                                                                // Record the changed file
                                                                Console.WriteLine(user + ": New or changed file found: " + updatedfile + "\n");
                                                                logFile.WriteLine(user + ": New or changed file found: " + change.FileId + " --- " + updatedfile);
                                                                txtLog.Text += (user + ": New or changed file found: --- " + updatedfile + " Type: " + mimetype + Environment.NewLine);
                                                                deltalog.WriteLine(change.FileId + "," + updatedfile + "," + mimetype + "," + folderid);
                                                                deltalog.Flush();
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            // Google seems to track every file ever created for the user
                                                            // it also keeps a record of the fileId. Even if a user
                                                            // deletes the file, it's still retained in Google's record
                                                            // although the file is no longer available.
                                                            // We'll throw an error to the user so the program will continue forth.
                                                            if (ex.Message.ToString().Contains("404"))
                                                            {
                                                                Console.WriteLine(user + ": 404 error. Selected record no longer exists.");
                                                                logFile.WriteLine(user + ": 404 error. Selected record no longer exists.");
                                                                txtLog.Text += (user + ": 404 error. Selected record no longer exists. Possibly old file that was renamed or removed by the user." + Environment.NewLine);
                                                            }
                                                            else
                                                            {
                                                                //Console.WriteLine(user + ": Verbatim error: " + ex.Message.ToString() + "\n");
                                                                logFile.WriteLine(user + ": Verbatim error: " + ex.Message.ToString() + "\n");
                                                                //txtLog.Text += (user + ": Verbatim error: " + ex.Message.ToString() + "\n" + Environment.NewLine);
                                                            }
                                                        }
                                                    }
                                                    if (changes.NewStartPageToken != null)
                                                    {
                                                        // Last page, save this token for the next polling interval
                                                        savedStartPageToken = changes.NewStartPageToken;
                                                    }

                                                    // Bring our token up to date for next run
                                                    pageToken = changes.NextPageToken;
                                                    File.WriteAllText(savelocation + ".currenttoken.tok", start.StartPageTokenValue);
                                                }
                                                deltalog.Close();
                                                folderlog.Close();
                                            }

                                            // Get all our files for the user. Max page size is 1k
                                            // after that, we have to use Google's next page token
                                            // to let us get more files.
                                            FilesResource.ListRequest listRequest = CreateService.BuildService(user).Files.List();
                                            listRequest.PageSize = 1000;
                                            listRequest.Fields   = "nextPageToken, files(id, name)";
                                            string[] deltafiles = File.ReadAllLines(savelocation + ".deltalog.tok");
                                            int      totalfiles = deltafiles.Count();
                                            int      cnttototal = 0;
                                            proBar1.Maximum = totalfiles;

                                            IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                                                                                           .Files;
                                            Console.WriteLine("\nFiles to backup:\n");
                                            txtLog.Text += (Environment.NewLine + "Files to backup:" + Environment.NewLine);
                                            if (deltafiles == null)
                                            {
                                                return;
                                            }
                                            else
                                            {
                                                double damn = ((gtoken - double.Parse(txtPrevToken.Text)));
                                                damn = Math.Round((damn / totalfiles));
                                                foreach (var file in deltafiles)
                                                {
                                                    try
                                                    {
                                                        if (bgW.CancellationPending)
                                                        {
                                                            stripLabel.Text = "Backup canceled!";
                                                            e.Cancel        = true;
                                                            break;
                                                        }
                                                        DateTime dt           = DateTime.Now;
                                                        string[] foldervalues = File.ReadAllLines(savelocation + "folderlog.txt");

                                                        cnttototal++;
                                                        bgW.ReportProgress(cnttototal);
                                                        stripLabel.Text = "File " + cnttototal + " of " + totalfiles;
                                                        double mathisfun = ((100 * cnttototal) / totalfiles);
                                                        double mathToken = double.Parse(txtPrevToken.Text);
                                                        mathToken = Math.Round((damn + mathToken));
                                                        // Bring our token up to date for next run
                                                        txtPrevToken.Text = mathToken.ToString();
                                                        File.WriteAllText(savelocation + ".currenttoken.tok", mathToken.ToString());
                                                        lblProgresslbl.Text = ("Current progress: " + mathisfun.ToString() + "% completed.");
                                                        //if (cnttototal == totalfiles)
                                                        //    stripLabel.Text = cnttototal + "/" + totalfiles + "!";
                                                        // Our file is a CSV. Column 1 = file ID, Column 2 = File name
                                                        var values = file.Split(',');

                                                        string fileId        = values[0];
                                                        string fileName      = values[1];
                                                        string mimetype      = values[2];
                                                        string folder        = values[3];
                                                        int    foundmatch    = 0;
                                                        int    folderfilelen = foldervalues.Count();

                                                        fileName = fileName.Replace('\\', '_').Replace('/', '_').Replace(':', '_').Replace('!', '_').Replace('\'', '_').Replace('*', '_').Replace('#', '_').Replace('[', '_').Replace(']', '_');
                                                        Console.WriteLine("Filename: " + values[1]);
                                                        txtLog.Text += (Environment.NewLine + "Timestamp: " + dt.ToString() + " Filename: " + values[1]);
                                                        logFile.WriteLine("ID: " + values[0] + " - Filename: " + values[1]);
                                                        var requestfileid = CreateService.BuildService(user).Files.Get(fileId);
                                                        //requestfileid.Fields = "*";
                                                        //var folderidexec = requestfileid.Execute();
                                                        //var folderid = string.Join(",", folderidexec.Parents);

                                                        var request = CreateService.BuildService(user).Files.Export(fileId, mimetype);

                                                        //Default extensions for files. Not sure what this should be, so we'll null it for now.
                                                        string ext = null;


                                                        // Things get sloppy here. The reason we're checking MimeTypes
                                                        // is because we have to export the files from Google's format
                                                        // to a format that is readable by a desktop computer program
                                                        // So for example, the google-apps.spreadsheet will become an MS Excel file.
                                                        if (mimetype == "application/vnd.google-apps.spreadsheet" || mimetype == "application/vnd.google-apps.ritz" || mimetype == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                                                        {
                                                            request = CreateService.BuildService(user).Files.Export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                                                            ext     = ".xls";
                                                        }
                                                        if (mimetype == "application/vnd.google-apps.document" || mimetype == "application/vnd.google-apps.kix")
                                                        {
                                                            request = CreateService.BuildService(user).Files.Export(fileId, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                                                            ext     = ".docx";
                                                        }
                                                        if (mimetype == "application/vnd.google-apps.presentation" || mimetype == "application/vnd.google-apps.punch")
                                                        {
                                                            request = CreateService.BuildService(user).Files.Export(fileId, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                                                            ext     = ".ppt";
                                                        }

                                                        // Google's folders are really just mime file types. Check for the file type
                                                        // grab the name of the file, and create it as such on the server FS.
                                                        lblFile.Text = (savelocation + fileName + ext);
                                                        if (mimetype == "application/vnd.google-apps.folder")
                                                        {
                                                            throw new Exception("This is a folder which already exists. Skipping.");
                                                        }
                                                        else
                                                        {
                                                            // Again, things get a little sloppy. Let's find if these files match any of the types in our IF statement.
                                                            if (mimetype == "image/gif" || mimetype == "image/jpeg" || mimetype == "image/png" || mimetype == "text/plain" || mimetype == "application/pdf" || mimetype == "application/vnd.google-apps.drawing" || mimetype == "application/vnd.google-apps.form")
                                                            {
                                                                if (mimetype == "application/pdf")
                                                                {
                                                                    throw new Exception("PDF files not supported right now as they tend to hang the backup.");
                                                                }
                                                                Console.Write("MIME Type update: " + mimetype);
                                                                txtLog.Text += (Environment.NewLine + "MIME Type update: " + mimetype + Environment.NewLine);
                                                                logFile.WriteLine(fileName + " MIME Type ---> " + mimetype + "\n");
                                                                string dest1   = Path.Combine(savelocation, fileName);
                                                                var    stream1 = new System.IO.FileStream(dest1, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                                                lblFile.Text = (savelocation + fileName + ext);
                                                                // Add a handler which will be notified on progress changes.
                                                                // It will notify on each chunk download and when the
                                                                // download is completed or failed.
                                                                requestfileid.MediaDownloader.ProgressChanged +=
                                                                    (IDownloadProgress progress) =>
                                                                {
                                                                    switch (progress.Status)
                                                                    {
                                                                    case DownloadStatus.Downloading:
                                                                    {
                                                                        txtLog.Text += (progress.BytesDownloaded);
                                                                        break;
                                                                    }

                                                                    case DownloadStatus.Completed:
                                                                    {
                                                                        Console.WriteLine("Download complete.");
                                                                        logFile.WriteLine(fileName + " downloaded successfully.\n");
                                                                        break;
                                                                    }

                                                                    case DownloadStatus.Failed:
                                                                    {
                                                                        Console.WriteLine("Error: There is nothing I can do with this file\n Is this is a draw or form?");
                                                                        txtLog.Text += (Environment.NewLine + "Error: There is nothing I can do with this file\n Is this is a draw or form?" + Environment.NewLine);
                                                                        logFile.WriteLine(fileName + " could not be downloaded. Possible Google draw/form OR bad name.\n");
                                                                        break;
                                                                    }
                                                                    }
                                                                };
                                                                requestfileid.Download(stream1);
                                                                stream1.Close();
                                                                stream1.Dispose();
                                                            }
                                                            else
                                                            {
                                                                // Any other file type, assume as know what it is (which in our case, will be a txt file)
                                                                // apply the mime type and carry on.
                                                                logFile.WriteLine(fileName + " MIME Type ---> " + mimetype + "\n");
                                                                string dest   = Path.Combine(savelocation, fileName + ext);
                                                                var    stream = new System.IO.FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                                                int    oops   = 0;
                                                                // Add a handler which will be notified on progress changes.
                                                                // It will notify on each chunk download and when the
                                                                // download is completed or failed.
                                                                request.MediaDownloader.ProgressChanged +=
                                                                    (IDownloadProgress progress) =>
                                                                {
                                                                    switch (progress.Status)
                                                                    {
                                                                    case DownloadStatus.Downloading:
                                                                    {
                                                                        txtLog.Text += (progress.BytesDownloaded);
                                                                        break;
                                                                    }

                                                                    case DownloadStatus.Completed:
                                                                    {
                                                                        Console.WriteLine("Download complete.");

                                                                        logFile.WriteLine(fileName + " downloaded successfully\n");
                                                                        break;
                                                                    }

                                                                    case DownloadStatus.Failed:
                                                                    {
                                                                        oops = 1;
                                                                        logFile.WriteLine(fileName + " could not be downloaded. Possible Google draw/form OR bad name.\n");
                                                                        break;
                                                                    }
                                                                    }
                                                                };
                                                                request.Download(stream);
                                                                if (oops == 1)
                                                                {
                                                                    txtLog.Text += (Environment.NewLine + fileName + " could not be downloaded. Possible Google draw/form OR bad name.\n" + Environment.NewLine);
                                                                    stream.Close();
                                                                    stream.Dispose();
                                                                }
                                                                else
                                                                {
                                                                    // Move file to the FS directory.
                                                                    stream.Close();
                                                                    stream.Dispose();
                                                                    while (foundmatch != folderfilelen)
                                                                    {
                                                                        foreach (string folders in foldervalues)
                                                                        {
                                                                            var    split      = folders.Split(',');
                                                                            string folderid   = split[0];
                                                                            string foldername = split[1];
                                                                            if (folder == folderid)
                                                                            {
                                                                                txtLog.Text += Environment.NewLine + "Info: Moving file to correct directory";
                                                                                string filetomove = (savelocation + fileName + ext);
                                                                                string dest1      = (foldername + fileName + ext);
                                                                                var    copyfrom   = Path.Combine(savelocation, fileName + ext);
                                                                                File.Move(lblFile.Text, dest1);
                                                                                throw new Exception("File moved to: " + dest1);
                                                                            }
                                                                            else
                                                                            {
                                                                                foundmatch++;
                                                                            }
                                                                        }
                                                                    }
                                                                    txtLog.Text += (Environment.NewLine + "Download complete." + Environment.NewLine);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // Well, we found a file that isn't usable or convertable
                                                        // we typically see this with a google form or google draw file, too.
                                                        Console.Write("\nInfo: ---> " + ex.Message.ToString() + "\n");
                                                        txtLog.Text += (Environment.NewLine + "Info: " + ex.Message.ToString() + Environment.NewLine);
                                                    }
                                                }
                                            }

                                            Console.WriteLine("\n\n\tBackup completed for selected user!");
                                            lblFile.Text  = "";
                                            txtLog.Text  += ("Backup completed for current selected user!" + Environment.NewLine);
                                            proBar1.Value = 0;
                                            btnStart.Text = "&Start Backup";
                                            logFile.Close();
                                            logFile.Dispose();
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Info: " + ex.Message.ToString());
                                    txtLog.Text += (Environment.NewLine + "Info: " + ex.Message.ToString() + Environment.NewLine);
                                }
                            }

                            else
                            {
                                Console.WriteLine("No data found in " + users);
                                txtLog.Text += ("No data found in " + users);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Info: " + ex.Message.ToString());
                    txtLog.Text += (Environment.NewLine);
                    //txtLog.Text += (Environment.NewLine + "Error: " + ex.Message.ToString());
                }
            }
        }
Пример #49
0
        private void SavePic(BitmapSource bitmap)
        {
            TestingData.ProfilePhoto = new BitmapImage();

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;

            //HACK
            TestingData.SubjectCode = "11";

            var PICTURE_FILENAME = string.Format("{0}.jpg", TestingData.sheet._id);
            //var PICTURE_FILENAME = "";
            string serverPath = @"C:\PCTest\pic\";
            var    picPath    = System.IO.Path.Combine(serverPath, PICTURE_FILENAME);

            if (!Directory.Exists(serverPath))
            {
                Directory.CreateDirectory(serverPath);
            }

            using (var fstream = new System.IO.FileStream(picPath, FileMode.Create))
            {
                encoder.Save(fstream);
                fstream.Flush();
                fstream.Close();
                fstream.Dispose();

                webcam.Stop();
                _isCameraOn = false;
            }

            var profileBitmap = BitmapFromSource(bitmap);

            ProfilePhoto = profileBitmap;


            TestingData.ProfilePhoto = new BitmapImage();
            Uri uri = new Uri(picPath, UriKind.RelativeOrAbsolute);

            TestingData.ProfilePhoto.BeginInit();
            TestingData.ProfilePhoto.UriSource   = uri;
            TestingData.ProfilePhoto.CacheOption = BitmapCacheOption.OnLoad;
            TestingData.ProfilePhoto.EndInit();

            //save image to server
            byte[] bit = new byte[0];

            using (var stream = new System.IO.MemoryStream())
            {
                JpegBitmapEncoder encoder2 = new JpegBitmapEncoder();
                encoder2.Frames.Add(BitmapFrame.Create(bitmap));
                encoder2.QualityLevel = 100;
                encoder2.Save(stream);
                bit = stream.ToArray();

                OnsiteServices svc = new OnsiteServices();

                PicRequest picre = new PicRequest
                {
                    FileName = PICTURE_FILENAME,
                    bytes    = bit
                };
                svc.SavePic(picre);

                stream.Flush();
                stream.Close();
                stream.Dispose();
            }
        }
Пример #50
0
 /// <inheritdoc />
 public virtual void Dispose()
 {
     _fileStream?.Dispose();
     _fileStream = null;
 }
Пример #51
0
 public void Start()
 {
     Controller.Instance.Popup.SetText("Please select any <#FF6666>Image<#FFFFFF> file to import.", false, () => {
         StandaloneFileBrowser.OpenFilePanelAsync("Import image", "", new ExtensionFilter[] { new ExtensionFilter("Image", new string[] { "png", "jpg", "jpeg", "bmp", "gif", "acnl", "webp" }) }, false, (path) =>
         {
             if (path.Length > 0)
             {
                 try
                 {
                     if (path[0].EndsWith(".acnl"))
                     {
                         var bytes = System.IO.File.ReadAllBytes(path[0]);
                         this.SetBytes(bytes);
                     }
                     else
                     {
                         Bitmap bmp       = null;
                         var imageStream  = new System.IO.FileStream(path[0], System.IO.FileMode.Open, System.IO.FileAccess.Read);
                         byte[] fourBytes = new byte[4];
                         imageStream.Read(fourBytes, 0, 4);
                         if (fourBytes[0] == 0x52 && fourBytes[1] == 0x49 && fourBytes[2] == 0x46 && fourBytes[3] == 0x46)
                         {
                             using (WebP webp = new WebP())
                                 bmp = webp.Load(path[0]);
                             imageStream.Close();
                             imageStream.Dispose();
                         }
                         else
                         {
                             bmp = new Bitmap(System.Drawing.Image.FromFile(path[0]));
                             imageStream.Close();
                             imageStream.Dispose();
                         }
                         this.SetImage(bmp);
                     }
                 }
                 catch (System.IO.FileLoadException e)
                 {
                     Controller.Instance.Popup.SetText("Failed to load the file. File error.", false, () =>
                     {
                         return(true);
                     });
                     return;
                 }
                 catch (Exception e)
                 {
                     Controller.Instance.Popup.SetText("Invalid image file.", false, () =>
                     {
                         return(true);
                     });
                     return;
                 }
                 Controller.Instance.PatternSelector.ActionMenu.Close();
                 Controller.Instance.SwitchToPatternEditor(
                     () =>
                 {
                     Controller.Instance.SwitchToNameInput(
                         () =>
                     {
                         ResultPattern.Name = this.Name;
                         Controller.Instance.CurrentSavegame.DesignPatterns[Pattern.Index].CopyFrom(ResultPattern);
                         _IsFinished = true;
                     },
                         () =>
                     {
                         _IsFinished = true;
                     }
                         );
                 },
                     () =>
                 {
                     _IsFinished = true;
                 }
                     );
             }
         });
         return(true);
     });
 }
Пример #52
0
    public bool Save(string Filename, int MapFileVersion)
    {
        if (!string.IsNullOrEmpty(Filename) & Filename != this.Filename)
        {
            this.Filename = Filename;
        }
        else
        {
            Filename = this.Filename;
        }
        if (MapFileVersion <= 0)
        {
            MapFileVersion = VersionMinor;
        }
        if (MapFileVersion <= 0)
        {
            MapFileVersion = 56;
        }
        if (MapFileVersion != VersionMinor)
        {
            VersionMinor = MapFileVersion;
        }

        Debug.Log("Save file version: " + VersionMinor);

        System.IO.FileStream fs     = new System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        BinaryWriter         Stream = new BinaryWriter(fs);

        var _with2 = Stream;

        //# Header Section #
        _with2.Write(MAP_MAGIC);
        _with2.Write(MAP_VERSION);

        _with2.Write(Unknown10);
        //? always EDFE EFBE
        _with2.Write(Unknown11);
        //? always 2
        _with2.Write((float)Width);
        //Map Width (in float)
        _with2.Write((float)Height);
        //Map Height (in float)
        _with2.Write(Unknown12);
        //? always 0
        _with2.Write(Unknown13);
        //? always 0
        //byte[] SaveData = new byte[0];

        //SaveData = PreviewTex.GetRawTextureData();
        //_with2.Write(SaveData.Length);
        //_with2.Write(SaveData);
        //Debug.Log(PreviewTex.GetRawTextureData().Length);
        TextureLoader.GetHeaderBGRA(PreviewTex, ref PreviewTextHeader);
        SaveTexture(_with2, TextureLoader.ConvertToBGRA(PreviewTex), PreviewTextHeader);
        //_with2.Write(PreviewImageLength);
        //_with2.Write(PreviewData);
        //Debug.Log( _with2.BaseStream.Length );

        //# Heightmap Section #
        _with2.Write(MapFileVersion);
        _with2.Write(Width);
        _with2.Write(Height);
        _with2.Write(HeightScale);
        //Height Scale, usually 1/128
        //_with2.Write(HeightmapData);

        for (int i = 0; i < HeightmapData.Length; i++)
        {
            _with2.Write(HeightmapData[i]);
        }

        if (MapFileVersion >= 56)
        {
            //_with2.Write(Convert.ToByte(0));
            _with2.Write(Unknown15);
        }
        //Always 0?

        //# Texture Definition Section #
        _with2.Write(TerrainShader, true);
        //usually "TTerrain"
        _with2.Write(TexPathBackground, true);
        _with2.Write(TexPathSkyCubemap, true);
        if (VersionMinor >= 56)
        {
            _with2.Write(EnvCubemapsName.Length);
            for (int i = 0; i < EnvCubemapsName.Length; i++)
            {
                _with2.Write(EnvCubemapsName[i], true);
                _with2.Write(EnvCubemapsFile[i], true);
            }
        }
        else
        {
            if (EnvCubemapsFile.Length >= 1)
            {
                _with2.Write(EnvCubemapsFile[0], true);
            }
            else
            {
                _with2.Write(Convert.ToByte(0));
            }
        }

        _with2.Write(LightingMultiplier);
        _with2.Write(SunDirection);
        _with2.Write(SunAmbience);
        _with2.Write(SunColor);
        _with2.Write(ShadowFillColor);
        _with2.Write(SpecularColor);
        _with2.Write(Bloom);

        _with2.Write(FogColor);
        _with2.Write(FogStart);
        _with2.Write(FogEnd);

        Water.Save(_with2);

        _with2.Write(WaveGenerators.Count);
        for (int i = 0; i < WaveGenerators.Count; i++)
        {
            WaveGenerators[i].Save(_with2);
        }

        if (VersionMinor < 56)
        {
            _with2.Write("No Tileset", true);

            _with2.Write(6);
            for (int i = 0; i <= 4; i++)
            {
                Layers[i].Save(_with2);
            }
            Layers[Layers.Count - 1].Save(_with2);
        }
        else
        {
            _with2.Write(MinimapContourInterval);
            int color = 0;
            color |= MinimapDeepWaterColor.a << 24;
            color |= MinimapDeepWaterColor.r << 16;
            color |= MinimapDeepWaterColor.g << 8;
            color |= MinimapDeepWaterColor.b;
            _with2.Write(color);

            int color2 = 0;
            color2 |= MinimapContourColor.a << 24;
            color2 |= MinimapContourColor.r << 16;
            color2 |= MinimapContourColor.g << 8;
            color2 |= MinimapContourColor.b;
            _with2.Write(color2);

            int color3 = 0;
            color3 |= MinimapShoreColor.a << 24;
            color3 |= MinimapShoreColor.r << 16;
            color3 |= MinimapShoreColor.g << 8;
            color3 |= MinimapShoreColor.b;
            _with2.Write(color3);

            int color4 = 0;
            color4 |= MinimapLandStartColor.a << 24;
            color4 |= MinimapLandStartColor.r << 16;
            color4 |= MinimapLandStartColor.g << 8;
            color4 |= MinimapLandStartColor.b;
            _with2.Write(color4);

            int color5 = 0;
            color5 |= MinimapLandEndColor.a << 24;
            color5 |= MinimapLandEndColor.r << 16;
            color5 |= MinimapLandEndColor.g << 8;
            color5 |= MinimapLandEndColor.b;
            _with2.Write(color5);

            if (VersionMinor > 56)
            {
                _with2.Write(Unknown14);
            }

            for (int i = 0; i < Layers.Count; i++)
            {
                Layers[i].SaveAlbedo(_with2);
            }
            for (int i = 0; i < Layers.Count - 1; i++)
            {
                Layers[i].SaveNormal(_with2);
            }
        }

        _with2.Write(Unknown7);
        //?
        _with2.Write(Unknown8);
        //?

        Decals = DecalsControler.GetAllDecals();

        _with2.Write(Decals.Count);
        for (int i = 0; i < Decals.Count; i++)
        {
            Decals[i].Save(_with2, i);
        }

        _with2.Write(DecalGroups.Count);
        for (int i = 0; i < DecalGroups.Count; i++)
        {
            DecalGroups[i].Save(_with2);
        }

        _with2.Write(Width);
        //Width again
        _with2.Write(Height);
        //Height again

        _with2.Write(1);

        TextureLoader.GetHeaderDxt5(NormalmapTex, ref NormalmapHeader);
        SaveTexture(_with2, NormalmapTex, NormalmapHeader);
        //Format.Dxt5

        if (VersionMinor < 56)
        {
            _with2.Write(1);
        }

        TextureLoader.GetHeaderBGRA(TexturemapTex, ref TextureMapHeader);
        SaveTexture(_with2, TextureLoader.ConvertToBGRA(TexturemapTex), TextureMapHeader);

        if (VersionMinor >= 56)
        {
            TextureLoader.GetHeaderBGRA(TexturemapTex2, ref TextureMap2Header);
            SaveTexture(_with2, TextureLoader.ConvertToBGRA(TexturemapTex2), TextureMap2Header);
        }

        _with2.Write(1);
        TextureLoader.GetHeaderDxt5(WatermapTex, ref WatermapHeader);
        SaveTexture(_with2, WatermapTex, WatermapHeader);

        _with2.Write(WaterFoamMask);
        _with2.Write(WaterFlatnessMask);
        _with2.Write(WaterDepthBiasMask);

        _with2.Write(TerrainTypeData.ToArray());

        if (MapFileVersion <= 52)
        {
            _with2.Write(Convert.ToInt16(0));
        }


        if (VersionMinor >= 60)
        {
            AdditionalSkyboxData.Save(_with2);
        }

        _with2.Write(Props.Count);
        for (int i = 0; i <= Props.Count - 1; i++)
        {
            Props[i].Save(_with2);
        }

        _with2.Close();
        fs.Close();
        fs.Dispose();
        return(true);
    }
Пример #53
0
        public CompiledMaterialInformationErrorCode Load(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(CompiledMaterialInformationErrorCode.NotFound);
            }

            System.IO.FileStream fs = null;
            if (!System.IO.File.Exists(path))
            {
                return(CompiledMaterialInformationErrorCode.NotFound);
            }

            try
            {
                fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            }
            catch
            {
                return(CompiledMaterialInformationErrorCode.FailedToOpen);
            }


            var br = new System.IO.BinaryReader(fs);

            var buf = new byte[1024];


            if (br.Read(buf, 0, 20) != 20)
            {
                fs.Dispose();
                br.Close();
                return(CompiledMaterialInformationErrorCode.InvalidFormat);
            }

            if (buf[0] != 'e' ||
                buf[1] != 'M' ||
                buf[2] != 'C' ||
                buf[3] != 'B')
            {
                fs.Dispose();
                br.Close();
                return(CompiledMaterialInformationErrorCode.InvalidFormat);
            }

            int version = BitConverter.ToInt32(buf, 4);

            // bacause of camera position node, structure of uniform is changed
            if (version == 0)
            {
                fs.Dispose();
                br.Close();
                return(CompiledMaterialInformationErrorCode.TooOldFormat);
            }

            int fversion = BitConverter.ToInt32(buf, 4);

            GUID = BitConverter.ToUInt64(buf, 8);

            var platformCount = BitConverter.ToInt32(buf, 16);

            for (int i = 0; i < platformCount; i++)
            {
                if (br.Read(buf, 0, 4) != 4)
                {
                    fs.Dispose();
                    br.Close();
                    return(CompiledMaterialInformationErrorCode.InvalidFormat);
                }

                var type = (CompiledMaterialPlatformType)BitConverter.ToInt32(buf, 0);
                Platforms.Add(type);
            }

            fs.Dispose();
            br.Close();
            return(CompiledMaterialInformationErrorCode.OK);
        }
Пример #54
0
        /// <summary>
        /// Write an input stream to a torrent GZ file
        /// </summary>
        /// <param name="inputStream">Input stream to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the write was a success, false otherwise</returns>
        /// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks>
        public override bool Write(Stream inputStream, string outDir, Rom rom = null, bool date = false, bool romba = false)
        {
            bool success = false;

            // If the stream is not readable, return
            if (!inputStream.CanRead)
            {
                return(success);
            }

            // Make sure the output directory exists
            if (!Directory.Exists(outDir))
            {
                Directory.CreateDirectory(outDir);
            }
            outDir = Path.GetFullPath(outDir);

            // Now get the Rom info for the file so we have hashes and size
            rom = new Rom(Utilities.GetStreamInfo(inputStream, inputStream.Length, keepReadOpen: true));

            // Get the output file name
            string outfile = null;

            // If we have a romba output, add the romba path
            if (romba)
            {
                outfile = Path.Combine(outDir, Utilities.GetRombaPath(rom.SHA1));                 // TODO: When updating to SHA-256, this needs to update to SHA256

                // Check to see if the folder needs to be created
                if (!Directory.Exists(Path.GetDirectoryName(outfile)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(outfile));
                }
            }
            // Otherwise, we're just rebuilding to the main directory
            else
            {
                outfile = Path.Combine(outDir, rom.SHA1 + ".gz");                 // TODO: When updating to SHA-256, this needs to update to SHA256
            }

            // If the output file exists, don't try to write again
            if (!File.Exists(outfile))
            {
                // Compress the input stream
                FileStream outputStream = Utilities.TryCreate(outfile);

                // Open the output file for writing
                BinaryWriter sw = new BinaryWriter(outputStream);

                // Write standard header and TGZ info
                byte[] data = Constants.TorrentGZHeader
                              .Concat(Utilities.StringToByteArray(rom.MD5))                                   // MD5
                              .Concat(Utilities.StringToByteArray(rom.CRC))                                   // CRC
                              .ToArray();
                sw.Write(data);
                sw.Write((ulong)rom.Size);                 // Long size (Unsigned, Mirrored)

                // Now create a deflatestream from the input file
                DeflateStream ds = new DeflateStream(outputStream, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression, true);

                // Copy the input stream to the output
                byte[] ibuffer = new byte[_bufferSize];
                int    ilen;
                while ((ilen = inputStream.Read(ibuffer, 0, _bufferSize)) > 0)
                {
                    ds.Write(ibuffer, 0, ilen);
                    ds.Flush();
                }
                ds.Dispose();

                // Now write the standard footer
                sw.Write(Utilities.StringToByteArray(rom.CRC).Reverse().ToArray());
                sw.Write((uint)rom.Size);

                // Dispose of everything
                sw.Dispose();
                outputStream.Dispose();
                inputStream.Dispose();
            }

            return(true);
        }
Пример #55
0
    private void ImportImage()
    {
        Controller.Instance.Popup.SetText("Please select any <#FF6666>Image<#FFFFFF> file to import.", false, () => {
            StandaloneFileBrowser.OpenFilePanelAsync("Import image", "", new ExtensionFilter[] { new ExtensionFilter("Image", new string[] { "png", "jpg", "jpeg", "bmp", "gif" }) }, false, (path) =>
            {
                if (path.Length > 0)
                {
                    try
                    {
                        System.Drawing.Bitmap bmp = null;
                        var imageStream           = new System.IO.FileStream(path[0], System.IO.FileMode.Open, System.IO.FileAccess.Read);
                        byte[] fourBytes          = new byte[4];
                        imageStream.Read(fourBytes, 0, 4);
                        if (fourBytes[0] == 0x52 && fourBytes[1] == 0x49 && fourBytes[2] == 0x46 && fourBytes[3] == 0x46)
                        {
                            var bytes = System.IO.File.ReadAllBytes(path[0]);
                            int webpWidth;
                            int webpHeight;
                            WebP.Error error;
                            WebP.Texture2DExt.GetWebPDimensions(bytes, out webpWidth, out webpHeight);
                            var colorData = WebP.Texture2DExt.LoadRGBAFromWebP(bytes, ref webpWidth, ref webpHeight, false, out error);
                            bmp           = new System.Drawing.Bitmap(webpWidth, webpHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            bmp.FromBytes(colorData);

                            /*using (WebP webp = new WebP())
                             *      bmp = webp.Load(path[0]);*/
                            imageStream.Close();
                            imageStream.Dispose();
                        }
                        else
                        {
                            bmp = new System.Drawing.Bitmap(System.Drawing.Image.FromFile(path[0]));
                            imageStream.Close();
                            imageStream.Dispose();
                        }
                        int x           = 0;
                        int y           = 0;
                        int width       = Editor.CurrentPattern.CurrentSubPattern.Width;
                        int height      = Editor.CurrentPattern.CurrentSubPattern.Height;
                        var newLayer    = new SmartObjectLayer(Editor.CurrentPattern.CurrentSubPattern, System.IO.Path.GetFileNameWithoutExtension(path[0]), bmp, x, y, width, height);
                        newLayer.Colors = new UnityEngine.Color[width * height];
                        newLayer.UpdateColors();
                        var index = Editor.CurrentPattern.CurrentSubPattern.Layers.IndexOf(Editor.CurrentPattern.CurrentSubPattern.SelectedLayer) + 1;
                        Editor.CurrentPattern.CurrentSubPattern.Layers.Insert(index, newLayer);
                        Editor.CurrentPattern.CurrentSubPattern.SelectedLayer = newLayer;
                        Editor.LayersChanged();
                        Editor.CurrentPattern.CurrentSubPattern.SelectLayer(newLayer);
                        Editor.CurrentPattern.CurrentSubPattern.UpdateImage();

                        Editor.CurrentPattern.CurrentSubPattern.History.AddEvent(new History.LayerCreatedAction("Created: " + newLayer.Name, index, newLayer));

                        Controller.Instance.Popup.Close();
                    }
                    catch (System.IO.FileLoadException e)
                    {
                        Debug.LogException(e);
                        Controller.Instance.Popup.SetText("Failed to load the file. File error.", false, () =>
                        {
                            return(true);
                        });
                        return;
                    }
                    catch (System.Exception e)
                    {
                        Debug.LogException(e);
                        Controller.Instance.Popup.SetText("Invalid image file.", false, () =>
                        {
                            return(true);
                        });
                        return;
                    }
                }
                else
                {
                    Controller.Instance.Popup.Close();
                }
            });
            return(false);
        });
    }
Пример #56
0
        private void aceeoptButton_Click(object sender, EventArgs e)
        {
            string originalText = originalTextBox.Text.Replace("\r\n", "");

            string resultText = resultTextbox.Text.Replace("\r\n", "");

            if (originalText != "" && resultTextbox.Text != "")
            {
                if (dicFileName.CompareTo("") == 0)
                {
                    dicFileName = ".\\DIC\\dic.txt";

                    if (isUseJpnFlag == true)
                    {
                        dicFileName = ".\\DIC\\dicJpn.txt";
                    }
                }
                else
                {
                    dicFileName = ".\\DIC\\" + dicFileName;
                }


                System.IO.StreamWriter file;


                try
                {
                    using (file = new System.IO.StreamWriter(dicFileName, true, Encoding.UTF8))
                    {
                        file.Write(System.Environment.NewLine);
                        file.WriteLine("/s");
                        file.WriteLine(originalText);
                        file.WriteLine(resultText);
                        file.Write(System.Environment.NewLine);
                    }
                }
                catch (FileNotFoundException)
                {
                    using (System.IO.FileStream fs = System.IO.File.Create(dicFileName))
                    {
                        fs.Close();
                        fs.Dispose();
                        file = new System.IO.StreamWriter(dicFileName, true);

                        file.Write(System.Environment.NewLine);
                        file.WriteLine("/s");
                        file.WriteLine(originalText);
                        file.WriteLine(resultText);
                        file.Write(System.Environment.NewLine);
                    }
                }

                file.Close();
                file.Dispose();

                setSpellCheck();
            }


            this.Close();
        }
Пример #57
0
    private static void ExportBindPoseToTex(Matrix4x4[] mats, string fileName)
    {
        if ((!string.IsNullOrEmpty(fileName)) && mats != null && mats.Length > 0)
        {
            // 每个骨骼12个Float,三个颜色就可以代替(3 * 4)
            int       colorPtCnt = mats.Length * 3;
            float     half       = Mathf.Sqrt(colorPtCnt);
            int       w          = Mathf.CeilToInt(half);
            int       h          = Mathf.CeilToInt(((float)colorPtCnt) / ((float)w));
            Texture2D tex        = new Texture2D(w, h, TextureFormat.RGBAHalf, false);

            Color[] cs = new Color[w * h];

            // 只需要保存3行4列,因为最后一行为0 0 0 1
            for (int i = 0; i < mats.Length; ++i)
            {
                Color c = new Color(mats[i].m00, mats[i].m01, mats[i].m02, mats[i].m03);
                cs[i * 3]     = c;
                c             = new Color(mats[i].m10, mats[i].m11, mats[i].m12, mats[i].m13);
                cs[i * 3 + 1] = c;
                c             = new Color(mats[i].m20, mats[i].m21, mats[i].m22, mats[i].m23);
                cs[i * 3 + 2] = c;
            }

            tex.SetPixels(cs);
            // 保存EXR
            byte[] buffer = tex.EncodeToEXR();
            System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            try {
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            } finally {
                stream.Close();
                stream.Dispose();
            }
#if UNITY_EDITOR
            GameObject.DestroyImmediate(tex);
#else
            GameObject.Destroy(tex);
#endif

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            fileName = fileName.Replace('\\', '/');
            int idx = fileName.IndexOf("Assets/", StringComparison.CurrentCultureIgnoreCase);
            if (idx < 0)
            {
                Debug.LogError("not found exr in Assets");
                return;
            }
            fileName = fileName.Substring(idx);
            var texImport = AssetImporter.GetAtPath(fileName) as TextureImporter;
            if (texImport != null)
            {
                texImport.textureType   = TextureImporterType.Lightmap;
                texImport.npotScale     = TextureImporterNPOTScale.None;
                texImport.mipmapEnabled = false;
                texImport.isReadable    = false;
                texImport.wrapMode      = TextureWrapMode.Clamp;
                texImport.filterMode    = FilterMode.Point;

                texImport.SetPlatformTextureSettings("Standalone", 1024, TextureImporterFormat.RGBAHalf);
                texImport.SetPlatformTextureSettings("Android", 1024, TextureImporterFormat.RGBAHalf);
                texImport.SetPlatformTextureSettings("iPhone", 1024, TextureImporterFormat.RGBAHalf);

                texImport.SaveAndReimport();
            }
            else
            {
                Debug.LogError("texImport == null");
            }
        }
    }
Пример #58
0
        /// <summary>
        /// Write an input stream to an output folder
        /// </summary>
        /// <param name="inputStream">Input stream to be moved</param>
        /// <param name="outDir">Output directory to build to</param>
        /// <param name="rom">DatItem representing the new information</param>
        /// <param name="date">True if the date from the DAT should be used if available, false otherwise (default)</param>
        /// <param name="romba">True if files should be output in Romba depot folders, false otherwise</param>
        /// <returns>True if the write was a success, false otherwise</returns>
        /// <remarks>This works for now, but it can be sped up by using Ionic.Zip or another zlib wrapper that allows for header values built-in. See edc's code.</remarks>
        public virtual bool Write(Stream inputStream, string outDir, Rom rom, bool date = false, bool romba = false)
        {
            bool success = false;

            // If either input is null or empty, return
            if (inputStream == null || rom == null || rom.Name == null)
            {
                return(success);
            }

            // If the stream is not readable, return
            if (!inputStream.CanRead)
            {
                return(success);
            }

            // Set internal variables
            FileStream outputStream = null;

            // Get the output folder name from the first rebuild rom
            string fileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName), Utilities.RemovePathUnsafeCharacters(rom.Name));

            try
            {
                // If the full output path doesn't exist, create it
                if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                }

                // Overwrite output files by default
                outputStream = Utilities.TryCreate(fileName);

                // If the output stream isn't null
                if (outputStream != null)
                {
                    // Copy the input stream to the output
                    inputStream.Seek(0, SeekOrigin.Begin);
                    int    bufferSize = 4096 * 128;
                    byte[] ibuffer    = new byte[bufferSize];
                    int    ilen;
                    while ((ilen = inputStream.Read(ibuffer, 0, bufferSize)) > 0)
                    {
                        outputStream.Write(ibuffer, 0, ilen);
                        outputStream.Flush();
                    }
                    outputStream.Dispose();

                    if (rom.Type == ItemType.Rom)
                    {
                        if (date && !String.IsNullOrWhiteSpace(((Rom)rom).Date))
                        {
                            File.SetCreationTime(fileName, DateTime.Parse(((Rom)rom).Date));
                        }
                    }

                    success = true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                success = false;
            }
            finally
            {
                inputStream.Dispose();
                outputStream?.Dispose();
            }

            return(success);
        }
Пример #59
0
    protected void Button3_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();// strWhere = "1=1";

        sb.Append("1=1");
        string browser = Request.Browser.Browser;

        if (!string.IsNullOrEmpty(Request["code"]))
        {
            sb.AppendFormat(" and CWB_Code like '%{0}%'", Request["code"].ToString().Trim());//;;//存 客户名称
        }
        if (!string.IsNullOrEmpty(Request["cname"]))
        {
            sb.AppendFormat(" and b.CC_Name like '%{0}%'", Request["cname"].ToString().Trim());//存 客户名称
        }
        if (!string.IsNullOrEmpty(Request["uname"]))
        {
            sb.AppendFormat(" and d.UserName like '%{0}%'", Request["uname"].ToString().Trim());//存 用户名称
        }
        if (!string.IsNullOrEmpty(Request["stime"]))
        {
            DateTime dtStime = Convert.ToDateTime("1980-01-01");
            DateTime.TryParse(Request["stime"].ToString().Trim(), out dtStime);
            sb.AppendFormat(" and CWB_CreateTime > '{0}'", dtStime.AddDays(-1));//保存操作开始时间
        }
        if (!string.IsNullOrEmpty(Request["etime"]))
        {
            DateTime dtEtime = Convert.ToDateTime("2250-01-01");
            DateTime.TryParse(Request["etime"].ToString().Trim(), out dtEtime);
            sb.AppendFormat(" and CWB_CreateTime < '{0}'", dtEtime.AddDays(1)); //保存操作结束时间
        }
        if (!string.IsNullOrEmpty(Request["Owner"]))                            //存 客户所属工程师
        {
            sb.AppendFormat(" and CWB_Description = '{0}'", Request["Owner"].ToString().Trim());
        }
        if (!string.IsNullOrEmpty(Request["sltType"]) && Request["sltType"].ToString().Trim() != "0")
        {
            sb.AppendFormat(" and CWB_Type = '{0}'", Convert.ToInt16(Request["sltType"].ToString().Trim()));
        }
        if (!string.IsNullOrEmpty(Request["status"]))
        {
            int intStatus = 0;
            int.TryParse(Request["status"].ToString().Trim(), out intStatus);
            int intStatus1 = 27;
            int.TryParse(ConfigurationManager.AppSettings["workbillStatusAll"].ToString(), out intStatus1);
            if (intStatus1 == intStatus)
            {
            }
            else
            {
                sb.AppendFormat(" and CWB_Status = '{0}'", intStatus);
            }
        }

        DataTable dt = new DataTable();

        HYTD.BLL.Call_WorkBillBLL bll = new HYTD.BLL.Call_WorkBillBLL();
        dt = bll.ImportExcelCustomerWorkBill(sb.ToString()).Tables[0];
        NPOI.SS.UserModel.IWorkbook book1 = new ImportExcel().ImportCustomerWorkBill(dt, "客户服务记录");
        string strFile  = string.Empty;
        string filename = string.Empty;
        string strPath  = HttpContext.Current.Server.MapPath("/" + System.Configuration.ConfigurationManager.AppSettings["CustomerFiles"].ToString().Replace("\\", "/") + "/")
                          + "\\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + "\\";

        if (dt.Rows.Count > 0)
        {
            strFile  = dt.Rows[0]["客户名称"].ToString();
            filename = strPath + dt.Rows[0]["客户名称"].ToString() + ".xls";
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filename)))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filename));
            }
            try
            {
                System.IO.FileStream file1 = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                book1.Write(file1);

                file1.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        Response.Clear();
        Response.BufferOutput    = false;
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        if (browser.ToLower() != "firefox")
        {
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFile) + ".xls");
        }
        else
        {
            Response.AddHeader("Content-Disposition", "attachment;filename=" + strFile + ".xls");
        }
        Response.ContentType = "application/ms-excel";
        book1.Write(Response.OutputStream);
        book1.Dispose();
    }
        protected void SetUp()
        {
            var f = new FileStream("config.json", FileMode.Open);
            var sr = new StreamReader(f);
            try
            {
                var settings = JsonConvert
                    .DeserializeObject<MongoSettings>(sr.ReadToEnd());
                var client = new MongoClient(new MongoUrl(settings.Url));
                _database = client.GetDatabase(settings.DatabaseName);
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Talk to John about why this one fails");
            }
            finally
            {
                f.Dispose();
                sr.Dispose();
            }

            _collectionName = Guid.NewGuid().ToString();
            _collection = _database.GetCollection<Container>(_collectionName);
            var mapper = new StringMapper<BasePaymentModel>(x => x.PaymentType)
                .Register<AchInputModel>("ach")
                .Register<CreditCardInputModel>("cc")
                .Register<PayPalInputModel>("paypal");
            BsonSerializer.RegisterDiscriminatorConvention(
                typeof(BasePaymentModel),
                new DiscriminatorConvention<string, BasePaymentModel>(mapper));
        }