Ejemplo n.º 1
0
        protected void SaveDownloadedFile(System.Net.HttpWebResponse webresponse, string filename)
        {
            System.IO.Stream filestream = webresponse.GetResponseStream();
            this.Uri = webresponse.ResponseUri;

            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(filestream))
            {
                using (System.IO.FileStream iofilestream = new System.IO.FileStream(filename, System.IO.FileMode.Create))
                {
                    int    BUFFER_SIZE = 1024;
                    byte[] buf         = new byte[BUFFER_SIZE];
                    int    n           = reader.Read(buf, 0, BUFFER_SIZE);
                    while (n > 0)
                    {
                        iofilestream.Write(buf, 0, n);
                        n = reader.Read(buf, 0, BUFFER_SIZE);
                    }

                    this.Uri    = webresponse.ResponseUri;
                    this.Length = iofilestream.Length;
                    iofilestream.Close();
                    iofilestream.Dispose();
                }
                reader.Close();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 分析网络数据包并进行转换为信息对象
        /// </summary>
        /// <param name="packs">接收到的封包对象</param>
        /// <returns></returns>
        /// <remarks>
        /// 对于分包消息,如果收到的只是片段并且尚未接收完全,则不会进行解析
        /// </remarks>
        public static IPMessager.Entity.Message ParseToMessage(params Entity.PackedNetworkMessage[] packs)
        {
            if (packs.Length == 0 || (packs[0].PackageCount > 1 && packs.Length != packs[0].PackageCount))
            {
                return(null);
            }

            //尝试解压缩,先排序
            Array.Sort(packs);
            //尝试解压缩
            System.IO.MemoryStream           ms  = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
            try
            {
                Array.ForEach(packs, s => zip.Write(s.Data, 0, s.Data.Length));
            }
            catch (Exception)
            {
                OnDecompressFailed(new DecomprssFailedEventArgs(packs));
                return(null);
            }

            zip.Close();
            ms.Flush();
            ms.Seek(0, System.IO.SeekOrigin.Begin);

            //构造读取流
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms, System.Text.Encoding.Unicode);

            //开始读出数据
            IPMessager.Entity.Message m = new FSLib.IPMessager.Entity.Message(packs[0].RemoteIP);
            m.PackageNo = br.ReadUInt64();                                                      //包编号
            ulong tl = br.ReadUInt64();

            m.Command = (Define.Consts.Commands)(tl & 0xFF); //命令编码
            m.Options = tl & 0xFFFFFF00;                     //命令参数

            m.UserName = br.ReadString();                    //用户名
            m.HostName = br.ReadString();                    //主机名

            int length = br.ReadInt32();

            m.NormalMsgBytes = new byte[length];
            br.Read(m.NormalMsgBytes, 0, length);

            length = br.ReadInt32();
            m.ExtendMessageBytes = new byte[length];
            br.Read(m.ExtendMessageBytes, 0, length);

            if (!Consts.Check(m.Options, Consts.Cmd_All_Option.BinaryMessage))
            {
                m.NormalMsg     = System.Text.Encoding.Unicode.GetString(m.NormalMsgBytes, 0, length);                  //正文
                m.ExtendMessage = System.Text.Encoding.Unicode.GetString(m.ExtendMessageBytes, 0, length);              //扩展消息
            }

            return(m);
        }
Ejemplo n.º 3
0
 public float ReadFloat()
 {
     mReader.Read(mTmpData, 0, 4);
     if (!LittleEndian)
     {
         Array.Reverse(mTmpData, 0, 4);
     }
     return(BitConverter.ToSingle(mTmpData, 0));
 }
Ejemplo n.º 4
0
		public static void  Main(System.String[] args)
		{
			PorterStemmer s = new PorterStemmer();
			
			for (int i = 0; i < args.Length; i++)
			{
				try
				{
					System.IO.BinaryReader in_Renamed = new System.IO.BinaryReader(System.IO.File.Open(args[i], System.IO.FileMode.Open, System.IO.FileAccess.Read));
					byte[] buffer = new byte[1024];
					int bufferLen, offset, ch;
					
					bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
					offset = 0;
					s.Reset();
					
					while (true)
					{
						if (offset < bufferLen)
							ch = buffer[offset++];
						else
						{
							bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
							offset = 0;
							if (bufferLen <= 0)
								ch = - 1;
							else
								ch = buffer[offset++];
						}
						
						if (System.Char.IsLetter((char) ch))
						{
							s.Add(System.Char.ToLower((char) ch));
						}
						else
						{
							s.Stem();
							System.Console.Out.Write(s.ToString());
							s.Reset();
							if (ch < 0)
								break;
							else
							{
								System.Console.Out.Write((char) ch);
							}
						}
					}
					
					in_Renamed.Close();
				}
				catch (System.IO.IOException )
				{
					System.Console.Out.WriteLine("error reading " + args[i]);
				}
			}
		}
Ejemplo n.º 5
0
        public bool Load(string path)
        {
            System.IO.FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            }
            catch(System.IO.FileNotFoundException e)
            {
                return false;
            }

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

            var buf = new byte[1024];

            if (br.Read(buf, 0, 8) != 8)
            {
                fs.Dispose();
                br.Dispose();
                return false;
            }

            // png Header 89 50 4E 47 0D 0A 1A 0A
            if (buf[0] == 0x89 &&
                buf[1] == 0x50 &&
                buf[2] == 0x4E &&
                buf[3] == 0x47 &&
                buf[4] == 0x0D &&
                buf[5] == 0x0A &&
                buf[6] == 0x1A &&
                buf[7] == 0x0A)
            {
                if (br.Read(buf, 0, 25) != 25)
                {
                    fs.Dispose();
                    br.Dispose();
                    return false;
                }

                var width = new byte[] { buf[11], buf[10], buf[9], buf[8] };
                var height = new byte[] { buf[15], buf[14], buf[13], buf[12] };
                Width = BitConverter.ToInt32(width, 0);
                Height = BitConverter.ToInt32(height, 0);
            }
            else
            {
                fs.Dispose();
                br.Dispose();
                return false;
            }

            fs.Dispose();
            br.Dispose();
            return true;
        }
Ejemplo n.º 6
0
        public bool Load(string path)
        {
            System.IO.FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            }
            catch (System.IO.FileNotFoundException e)
            {
                return(false);
            }

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

            var buf = new byte[1024];

            if (br.Read(buf, 0, 8) != 8)
            {
                fs.Dispose();
                br.Dispose();
                return(false);
            }

            // png Header 89 50 4E 47 0D 0A 1A 0A
            if (buf[0] == 0x89 &&
                buf[1] == 0x50 &&
                buf[2] == 0x4E &&
                buf[3] == 0x47 &&
                buf[4] == 0x0D &&
                buf[5] == 0x0A &&
                buf[6] == 0x1A &&
                buf[7] == 0x0A)
            {
                if (br.Read(buf, 0, 25) != 25)
                {
                    fs.Dispose();
                    br.Dispose();
                    return(false);
                }

                var width  = new byte[] { buf[11], buf[10], buf[9], buf[8] };
                var height = new byte[] { buf[15], buf[14], buf[13], buf[12] };
                Width  = BitConverter.ToInt32(width, 0);
                Height = BitConverter.ToInt32(height, 0);
            }
            else
            {
                fs.Dispose();
                br.Dispose();
                return(false);
            }

            fs.Dispose();
            br.Dispose();
            return(true);
        }
Ejemplo n.º 7
0
        public string ReadUTF8Path()
        {
            Int64 pathLen = _objReader.ReadInt64();

            byte[] buffer = new byte[pathLen];
            _objReader.Read(buffer, 0, buffer.Length);
            string ret = System.Text.Encoding.UTF8.GetString(buffer);

            return(ret);
        }
Ejemplo n.º 8
0
        public bool Load(string path)
        {
            System.IO.FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            }
            catch (System.IO.FileNotFoundException e)
            {
                return(false);
            }

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

            var buf = new byte[1024];

            if (br.Read(buf, 0, 8) != 8)
            {
                fs.Dispose();
                br.Dispose();
                return(false);
            }

            var version = BitConverter.ToInt32(buf, 0);

            if (version == 2)
            {
                Scale = BitConverter.ToSingle(buf, 4);
                fs.Dispose();
                br.Dispose();
                return(false);
            }

            if (version == 3)
            {
                fs.Seek(-4, System.IO.SeekOrigin.End);

                if (br.Read(buf, 0, 4) == 4)
                {
                    Scale = BitConverter.ToSingle(buf, 0);
                }
                else
                {
                    fs.Dispose();
                    br.Dispose();
                    return(false);
                }
            }

            fs.Dispose();
            br.Dispose();

            return(true);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 读float
 /// </summary>
 /// <returns></returns>
 public unsafe float ReadFloat()
 {
     //int num;
     //num = this.ReadInt();
     //return *(float*)(&num);
     reader.Read(tempData, 0, 4);
     if (!LittleEndian)
     {
         Array.Reverse(tempData, 0, 4);
     }
     return(BitConverter.ToSingle(tempData, 0));
 }
        static int _m_Read(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.BinaryReader gen_to_be_invoked = (System.IO.BinaryReader)translator.FastGetCSObj(L, 1);


                int gen_param_count = LuaAPI.lua_gettop(L);

                if (gen_param_count == 1)
                {
                    int gen_ret = gen_to_be_invoked.Read(  );
                    LuaAPI.xlua_pushinteger(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 4 && translator.Assignable <char[]>(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4))
                {
                    char[] _buffer = (char[])translator.GetObject(L, 2, typeof(char[]));
                    int    _index  = LuaAPI.xlua_tointeger(L, 3);
                    int    _count  = LuaAPI.xlua_tointeger(L, 4);

                    int gen_ret = gen_to_be_invoked.Read(_buffer, _index, _count);
                    LuaAPI.xlua_pushinteger(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 4 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4))
                {
                    byte[] _buffer = LuaAPI.lua_tobytes(L, 2);
                    int    _index  = LuaAPI.xlua_tointeger(L, 3);
                    int    _count  = LuaAPI.xlua_tointeger(L, 4);

                    int gen_ret = gen_to_be_invoked.Read(_buffer, _index, _count);
                    LuaAPI.xlua_pushinteger(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }

            return(LuaAPI.luaL_error(L, "invalid arguments to System.IO.BinaryReader.Read!"));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Buffers incoming P2P direct connected messages.
        /// </summary>
        /// <param name="reader"></param>
        public override void BufferData(System.IO.BinaryReader reader)
        {
            lock (reader.BaseStream)
            {
                // make sure we read the last retrieved message if available
                if (bytesLeft > 0 && lastMessage != null)
                {
                    // make sure no overflow occurs
                    int length = (int)Math.Min(bytesLeft, (uint)(reader.BaseStream.Length - reader.BaseStream.Position));
                    reader.Read(lastMessage, lastMessage.Length - bytesLeft, (int)length);
                    bytesLeft -= length;


                    if (bytesLeft == 0)
                    {
                        // insert it into the temporary buffer for later retrieval
                        messages.Enqueue(lastMessage);
                        lastMessage = null;
                    }
                }


                while (reader.BaseStream.Position < reader.BaseStream.Length)
                {
                    // read the length of the message
                    uint messageLength = reader.ReadUInt32();

                    // make sure no overflow occurs
                    int length = (int)Math.Min(messageLength, (uint)(reader.BaseStream.Length - reader.BaseStream.Position));

                    // read in the bytes
                    byte[] message = new byte[messageLength];
                    reader.Read(message, 0, (int)length);

                    if (length < messageLength)
                    {
                        bytesLeft   = (int)messageLength - length;
                        lastMessage = message;
                    }
                    else
                    {
                        lastMessage = null;

                        // insert it into the temporary buffer for later retrieval
                        messages.Enqueue(message);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public static LevelDbOperation Deserialize(ref System.IO.BinaryReader stream)
        {
            LevelDbOperation levelDbOperation = new LevelDbOperation();

            //tableid
            levelDbOperation.tableid = (byte)stream.ReadByte();
            //key
            var isnull = stream.ReadByte();

            if (isnull != 1)
            {
                levelDbOperation.key = null;
            }
            else
            {
                byte[] bytes_keyL = new byte[4];
                stream.Read(bytes_keyL, 0, 4);
                var    keyL      = BitConverter.ToInt32(bytes_keyL, 0);
                byte[] bytes_key = new byte[keyL];
                stream.Read(bytes_key, 0, keyL);
                levelDbOperation.key = bytes_key;
            }

            //value
            isnull = stream.ReadByte();
            if (isnull != 1)
            {
                levelDbOperation.value = null;
            }
            else
            {
                byte[] bytes_valueL = new byte[4];
                stream.Read(bytes_valueL, 0, 4);
                var    valueL      = BitConverter.ToInt32(bytes_valueL, 0);
                byte[] bytes_value = new byte[valueL];
                stream.Read(bytes_value, 0, valueL);
                levelDbOperation.value = bytes_value;
            }

            //state
            levelDbOperation.state = (byte)stream.ReadByte();

            ////height
            //byte[] bytes_height = new byte[4];
            //stream.Read(bytes_height,0,4);
            //levelDbOperation.height = (ulong)BitConverter.ToInt32(bytes_height,0);

            return(levelDbOperation);
        }
Ejemplo n.º 13
0
        private void CopiaRapida(string source, string destination, bool BorrarOrigen = false)
        {
            int array_length = (int)Math.Pow(2, 19);

            byte[] dataArray = new byte[array_length];

            using (System.IO.FileStream fsread = new System.IO.FileStream
                                                     (source, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, array_length))
            {
                using (System.IO.BinaryReader bwread = new System.IO.BinaryReader(fsread))
                {
                    using (System.IO.FileStream fswrite = new System.IO.FileStream
                                                              (destination, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, array_length))
                    {
                        using (System.IO.BinaryWriter bwwrite = new System.IO.BinaryWriter(fswrite))
                        {
                            for (; ;)
                            {
                                int read = bwread.Read(dataArray, 0, array_length);
                                if (0 == read)
                                {
                                    break;
                                }
                                bwwrite.Write(dataArray, 0, read);
                            }
                        }
                    }
                }
            }

            if (BorrarOrigen)
            {
                File.Delete(source);
            }
        }
Ejemplo n.º 14
0
            public Manager(System.IO.Stream Stream, int T = 0)
            {
                //System.IO.FileStream fl;
                this.T      = T;
                BTreeSize   = 224 * T - 98;
                this.Stream = Stream;
                Reader      = new System.IO.BinaryReader(Stream);
                Writer      = new System.IO.BinaryWriter(Stream);

                if (Stream.Length == 0) // => FILE IS EMPTY
                {
                    Stream.Position = 28;
                    RootN           = -1;
                    RootP           = -1;
                    RootA           = -1;
                    LastInsertion   = 28;
                }

                else //=> EXIST DATA SAVE IN THE FILE
                {
                    byte[] buffer = new byte[28];
                    Stream.Position = 0;
                    Reader.Read(buffer, 0, 28);

                    System.IO.MemoryStream memStream   = new System.IO.MemoryStream(buffer);
                    System.IO.BinaryReader tempBReader = new System.IO.BinaryReader(memStream);
                    T             = tempBReader.ReadInt32(); //DEGREE OF BTREE
                    RootN         = tempBReader.ReadInt64(); //POSITION OF THE BTREE ROOTS
                    RootP         = tempBReader.ReadInt64();
                    RootA         = tempBReader.ReadInt64();
                    LastInsertion = Stream.Length;
                }
            }
Ejemplo n.º 15
0
        /// <summary>
        /// Checks KOM file headers and returns the version of kom it is. An return of 0 is an Error.
        /// </summary>
        private static int GetHeaderVersion(string komfile)
        {
            int ret = 0;

            System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(System.Windows.Forms.Application.StartupPath + "\\koms\\" + komfile), System.Text.Encoding.ASCII);
            byte[] headerbuffer           = new byte[27];
            // 27 is the size of the header string denoting the KOM file version number.
            int offset = 0;

            reader.Read(headerbuffer, offset, 27);
            string headerstring = System.Text.Encoding.UTF8.GetString(headerbuffer);

            reader.Dispose();
            foreach (var komplugin in komplugins)
            {
                // get version of kom file for unpacking it.
                if (komplugin.KOMHeaderString == string.Empty)
                {
                    // skip this plugin it does not implement an packer or unpacker.
                    continue;
                }
                if (headerstring == komplugin.KOMHeaderString)
                {
                    ret = komplugin.SupportedKOMVersion;
                }
            }
            return(ret);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 从网络流中读取一个缓冲对象,对象大小由长度字段指定。
        /// </summary>
        /// <param name="ns"></param>
        /// <returns></returns>
        private byte[] readBuffer(System.Net.Sockets.NetworkStream ns)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(ns);
            byte[] len        = br.ReadBytes(4);//头四个字节为命令长度
            uint   size       = ReverseByteOrder.ReverseBytes(BitConverter.ToUInt32(len, 0));
            int    buffersize = 0;

            if (size > 40960)//不处理大于40k的数据包
            {
                throw new Exception("数据大于40K");
            }
            else
            {
                buffersize = (int)size;
            }
            byte[] result = new byte[buffersize];
            int    count  = br.Read(result, 4, buffersize - 4);

            if (count != buffersize - 4)
            {
                throw new Exception("不完整的数据");
            }
            //将头长度拷贝入结果
            Buffer.BlockCopy(len, 0, result, 0, 4);
            return(result);
        }
		protected void filAddExtension_Upload(object sender, FileUploadEventArgs e)
		{
			//get the uploaded file and its metadata
			HttpPostedFile postedFile = e.PostedFile;
			string filepath = postedFile.FileName;
			string filename = filepath.Substring(filepath.LastIndexOf('\\') + 1);

			if (ValidateFile(filename))
			{
				//separate the file extension from the filename
				string fileExt = System.IO.Path.GetExtension(filename);
				string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(filename);

				int contentLength = postedFile.ContentLength;
				string contentType = postedFile.ContentType;

				System.IO.BinaryReader reader = new System.IO.BinaryReader(postedFile.InputStream);
				byte[] bytes = new byte[contentLength];
				reader.Read(bytes, 0, contentLength);

				//store the file into the data store
				Utility.DocumentStorage documentStorageObject = Utility.DocumentStorage.GetDocumentStorageObject(_itatSystem.DocumentStorageType);
				documentStorageObject.RootPath = _itatSystem.DocumentStorageRootPath;
				string objectId = documentStorageObject.SaveDocument(fileNameWithoutExt, fileExt, bytes);

				//add metadata about the extension to the template object
				Business.Extension extension = new Kindred.Knect.ITAT.Business.Extension();
				extension.FileName = filename;
				extension.ObjectID = objectId;
				_template.Extensions.Add(extension);

				//update the form
				InitializeForm(_template.Extensions.Count - 1);  //select newly added row (last row in the grid)
			}
		}
Ejemplo n.º 18
0
        public static string GetHash(System.IO.BinaryReader reader)
        {
            System.IntPtr pContext = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Context)));
            MurmurHash32Init(pContext, 0);

            byte[]   bytes  = new byte[1024];
            GCHandle hBytes = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            System.IntPtr ptr  = hBytes.AddrOfPinnedObject();
            int           size = 0;

            while (0 < (size = reader.Read(bytes, 0, 1024)))
            {
                if (size < 1024)
                {
                    MurmurHash32Tail(pContext, ptr, 0U, (uint)size);
                }
                else
                {
                    MurmurHash32Update4(pContext, ptr, 0U, (uint)size);
                }
            }
            hBytes.Free();
            uint hash = MurmurHash32Finalize(pContext);

            Marshal.FreeHGlobal(pContext);
            return(toHex(hash));
        }
Ejemplo n.º 19
0
        public void ProcessRequest(HttpContext context)
        {
            var req = context.Request;
            var rep = context.Response;

            req.ContentType = "application/json";
            var fileName = req["fileName"];

            if (String.IsNullOrWhiteSpace(fileName))
            {
                fileName = Guid.NewGuid().ToString();
            }
            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(req.InputStream))
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                int bte;
                while ((bte = reader.Read()) != -1)
                {
                    ms.WriteByte((byte)bte);
                }
                var arrayBytes = ms.ToArray();
                var base64     = System.Text.Encoding.UTF8.GetString(arrayBytes);
                var data       = Convert.FromBase64String(base64);

                var fileFullPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Static/" + fileName);

                this.AppedOrCreate(fileFullPath, data);
            }
            rep.Write("{\"FileName\":\"" + fileName + "\"}");
        }
Ejemplo n.º 20
0
        ////////////////////////////////////////////////////////////////////////////////
        //
        ////////////////////////////////////////////////////////////////////////////////
        public static void GetFileBytes(String filePath, String base64)
        {
            if (String.Empty == base64)
            {
                base64 = "false";
            }

            if (!Boolean.TryParse(base64, out Boolean bBase64))
            {
                Console.WriteLine("Unable to parse wait parameter (true, false)");
                return;
            }

            Byte[] fileBytes;
            using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.GetFullPath(filePath), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
            {
                using (System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream))
                {
                    fileBytes = new Byte[binaryReader.BaseStream.Length];
                    binaryReader.Read(fileBytes, 0, (Int32)binaryReader.BaseStream.Length);
                }
            }

            String strBytes = "0x" + BitConverter.ToString(fileBytes).Replace("-", ",0x");

            if (bBase64)
            {
                Convert.ToBase64String(fileBytes);
            }
        }
Ejemplo n.º 21
0
        private bool[,] GetBlacks(string sFile)
        {
            System.IO.FileStream   fs = new System.IO.FileStream(LtrDraw_txtPath.Text, System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
            byte[] bRaw = new byte[(imgW * imgH) / 2];
            br.Read(new byte[0x76], 0, 0x76);
            br.Read(bRaw, 0, (imgW * imgH) / 2);
            br.Close(); fs.Close(); fs.Dispose();

            bool[,] bSet = new bool[imgW, imgH];
            int iRawPos = 0; bool bHugeDef = true;

            for (int y = imgH - 1; y >= 0; y--)
            {
                for (int x = 0; x < imgW; x++)
                {
                    if (bHugeDef)
                    {
                        if (bRaw[iRawPos] == 0xF0 || bRaw[iRawPos] == 0xFF)
                        {
                            bSet[x, y] = false;
                        }
                        else
                        {
                            bSet[x, y] = true;
                        }
                    }
                    else
                    {
                        if (bRaw[iRawPos] == 0x0F || bRaw[iRawPos] == 0xFF)
                        {
                            bSet[x, y] = false;
                        }
                        else
                        {
                            bSet[x, y] = true;
                        }
                    }
                    if (!bHugeDef)
                    {
                        iRawPos++;
                    }
                    bHugeDef = !bHugeDef;
                }
            }
            return(bSet);
        }
        public static int Read(this System.IO.BinaryReader binaryReader, Span <char> buffer)
        {
            var arr       = new char[buffer.Length];
            var readBytes = binaryReader.Read(arr, 0, arr.Length);

            arr.AsSpan().CopyTo(buffer);
            return(readBytes);
        }
Ejemplo n.º 23
0
        void readFileContents(File f, System.IO.BinaryReader br)
        {
            int len = br.ReadInt32();

            byte[] data = new byte[len];
            br.Read(data, 0, len);
            f.replace(data, this);
        }
Ejemplo n.º 24
0
        public static IStream CreateReaderStream(System.IO.BinaryReader reader)
        {
            var cnt = (int)(reader.BaseStream.Length - reader.BaseStream.Position);

            byte[] bytes = new byte[cnt];
            reader.Read(bytes, 0, cnt);
            wxb.WRStream stream = new WRStream(bytes);
            stream.WritePos = cnt;
            return(stream);
        }
Ejemplo n.º 25
0
        public static void ToCertUtil(string inputFile, string outputFile)
        {
            //const int BUFFER_SIZE = 4032; // 4032%3=0 && 4032%64=0
            // const int BUFFER_SIZE = 4080; // 4080%3=0 && 4080%8=0
            const int BUFFER_SIZE = 4095; // 4095%3=0 && 4095~=4096 (pageSize)

            byte[] buffer = new byte[BUFFER_SIZE];

            using (System.IO.FileStream outputStream = System.IO.File.OpenWrite(outputFile))
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputStream, System.Text.Encoding.ASCII))
                {
                    sw.Write("-----BEGIN CERTIFICATE-----");
                    sw.Write(System.Environment.NewLine);

                    using (System.IO.FileStream inputStream = System.IO.File.OpenRead(inputFile))
                    {
                        using (System.IO.BinaryReader br = new System.IO.BinaryReader(inputStream))
                        {
                            br.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                            long totalLength = inputStream.Length;


                            long totalRead = 0;
                            int  bytesRead;
                            while ((bytesRead = br.Read(buffer, 0, BUFFER_SIZE)) > 0)
                            {
                                totalRead += bytesRead;

                                // string b64 = System.Convert.ToBase64String(buffer, 0, bytesRead, System.Base64FormattingOptions.InsertLineBreaks);
                                // string b64 = System.Convert.ToBase64String(buffer);

                                bool isFinal = (bytesRead < BUFFER_SIZE || totalRead == totalLength);
                                CertSSL.cb64.ConvertToBase64Array(sw, buffer, 0, bytesRead, true, isFinal);

                                //if (bytesRead < BUFFER_SIZE || totalRead == totalLength)
                                //    b64 = b64.Substring(0, b64.Length - 2);

                                //sw.Write(b64);

                                // sw.Write(System.Environment.NewLine);
                                // CertSSL.cb64.ConvertToBase64Array(sw, buffer, 0, bytesRead, true);
                            } // Whend

                            br.Close();
                        } // End Using br
                    }     // End Using inputStream

                    sw.Write(System.Environment.NewLine);
                    sw.Write("-----END CERTIFICATE-----");
                    sw.Write(System.Environment.NewLine);
                } // End Using sw
            }     // End Using outputStream
        }         // End Sub ToCertUtil
Ejemplo n.º 26
0
        //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
        public virtual void readExternal(System.IO.BinaryReader in_Renamed, PrototypeFactory pf)
        {
            int size = in_Renamed.ReadInt32();

            if (size != -1)
            {
                data = new sbyte[size];
                in_Renamed.Read((byte[])(Array)data, 0, data.Length);
            }
            name = ExtUtil.readString(in_Renamed);
        }
Ejemplo n.º 27
0
        /* (non-Javadoc)
         * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory)
         */
        //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
        public virtual void readExternal(System.IO.BinaryReader in_Renamed, PrototypeFactory pf)
        {
            int length = in_Renamed.ReadInt32();

            if (length > 0)
            {
                this.payload = new byte[length];
                in_Renamed.Read(this.payload, 0, this.payload.Length);
            }
            id = ExtUtil.nullIfEmpty(ExtUtil.readString(in_Renamed));
        }
Ejemplo n.º 28
0
        //上传图片
        public byte[] GetBytes(FileUpload fileupload)
        {
            int contentLength = fileupload.PostedFile.ContentLength;

            byte[] photo = new byte[contentLength];
            using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileupload.FileContent))
            {
                br.Read(photo, 0, contentLength);
                return(photo);
            }
        }
Ejemplo n.º 29
0
        public void Initialize(System.IO.BinaryReader br)
        {
            byte[] objectData = new byte[2];

            br.BaseStream.Position = SegmentAddress.Offset;
            for (int i = 0; i < Objects; i++)
            {
                br.Read(objectData, 0, 2);
                Endian.Convert(out ushort o, objectData, 0);
                ObjectList.Add(o);
            }
        }
Ejemplo n.º 30
0
 public void LoadState(System.IO.BinaryReader stream)
 {
     stream.Read(data, 0, data.Length);
     mode     = (EpromMode)stream.ReadInt32();
     nextmode = (EpromMode)stream.ReadInt32();
     psda     = stream.ReadBoolean();
     pscl     = stream.ReadBoolean();
     output   = stream.ReadInt32();
     cbit     = stream.ReadInt32();
     caddress = stream.ReadInt32();
     cdata    = stream.ReadInt32();
     isRead   = stream.ReadBoolean();
 }
Ejemplo n.º 31
0
        public void OpenStream()
        {
            long exeSize  = ExeUtils.GetCurrentExeVirtualSize();
            long fileSize = ExeUtils.GetCurrentExeDiskSize();

            // Validate size
            if ((exeSize + _cOffsetToken.Length) > fileSize)
            {
                Globals.Throw("Installer exe file size was too short.  It appears the installer did not pack any data. (0094812).");
            }

            byte[] buffer  = new byte[_cOffsetToken.Length];
            string exePath = ExeUtils.GetCurrentExePath();

            // Create stream
            _objFileStream = new System.IO.FileStream(exePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            _objReader     = new System.IO.BinaryReader(_objFileStream);

            //_objReader.BaseStream.Seek(exeSize, System.IO.SeekOrigin.Begin);
            //Read the binary.
            _binaryData = new byte[exeSize];
            _objReader.Read(_binaryData, 0, _binaryData.Length);

            //Read the token
            _objReader.Read(buffer, 0, buffer.Length);

            // Validate Token
            string strToken = System.Text.Encoding.ASCII.GetString(buffer);

            if (!strToken.Equals(_cOffsetToken))
            {
                //**This is no longer valid.  The uninstaller MUST have the file table and the config (just no files)
                //Globals.Logger.LogError("Installer data token was invalid.  The installer exe computed size may be wrong. OR the user has tried to run the uninstaller without the /u switdch.  App will now exit.", false, true);
                //Environment.Exit(1);

                //This will throw
                Globals.Logger.LogError("Error installing/Uninstalling, Invalid binary Token. (01903)", true, true);
            }
        }
Ejemplo n.º 32
0
        static public bool CopyBinaryFile(string srcfilename, string destfilename)

        {
            if (System.IO.File.Exists(srcfilename) == false)

            {
                Console.WriteLine("Could not find the Source file");

                return(false);
            }



            System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open);

            System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create);



            System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1);

            System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2);



            while (true)

            {
                byte[] buf = new byte[10240];

                int sz = f1.Read(buf, 0, 10240);

                if (sz <= 0)
                {
                    break;
                }

                f2.Write(buf, 0, sz);

                if (sz < 10240)
                {
                    break; // eof reached
                }
            }

            f1.Close();

            f2.Close();

            return(true);
        }
Ejemplo n.º 33
0
        public byte[] GetEmbeddedContentAsBinary(string defaultNamespace, string content)
        {
            string resourceName1 = content.Replace("/", ".");
            string resourceName2 = defaultNamespace + resourceName1;
            string resourceName3 = resourceName2.ToLower();
            string resourceName;
            if (!mapCaseInsensitiveToCaseSensitive.TryGetValue(resourceName3, out resourceName))
            {
                return null;
            }

            using (System.IO.Stream stream = this.assembly.GetManifestResourceStream(resourceName))
            using (var reader = new System.IO.BinaryReader(stream))
            {
                var result = new byte[stream.Length];
                reader.Read(result, 0, (int)stream.Length);
                return result;
            }
        }
Ejemplo n.º 34
0
        public void Start(string InputFilename, string OutputFilename, UInt64 Key, DESMode.DESMode Mode, bool Decode)
        {
            using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(System.IO.File.Open(InputFilename, System.IO.FileMode.Open)))
            {
                using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(System.IO.File.Open(OutputFilename, System.IO.FileMode.OpenOrCreate)))
                {
                    const int MaxSize = 1048576;
                    int n = 0;
                    byte[] buffer = new byte[MaxSize];
                    int size = 0;
                    int k = 0;
                    UInt64 DESResult = 0;

                    while ((n = Reader.Read(buffer, 0, MaxSize)) > 0)
                    {
                        k = 0;
                        while (n > 0)
                        {
                            if ((n / 8) > 0)
                                size = 8;
                            else
                                size = n;
                            byte[] tempArray = new byte[size];
                            for (int i = 0; i != size; ++i, ++k)
                                tempArray[i] = buffer[k];

                            if (!Decode)
                                DESResult = Mode.EncodeBlock(GetUIntFromByteArray(tempArray), Key);
                            else
                                DESResult = Mode.DecodeBlock(GetUIntFromByteArray(tempArray), Key);
                            Writer.Write(GetByteArrayFromUInt(DESResult, size), 0, size);

                            n -= 8;
                        }
                    }
                    Writer.Close();
                }
                Reader.Close();
            }
        }
Ejemplo n.º 35
0
        private void vdxChooser_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (game == GameID.T7G)
            {
                if (vdx != null)
                    vdx.stop();

                string file = vdxChooser.SelectedItem.ToString();

                GJD.RLData rl;
                System.IO.BinaryReader reader = gjd.getVDX(file, out rl);
                if (reader != null)
                {
                    if (midi != null)
                        midi.Close();
                    if (!gjd.Name.Contains("xmi"))
                        vdx = new VDX(reader, rl, s);
                    else
                    {
                        if (!System.IO.File.Exists(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid"))
                        {
                            System.Diagnostics.Process p = new System.Diagnostics.Process();
                            p.StartInfo.FileName = path + "mid\\xmi2mid.exe";
                            p.StartInfo.Arguments = path + "mid\\" + file.Substring(0, file.IndexOf(".") + 4) + " " + path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid";
                            p.StartInfo.UseShellExecute = false;
                            p.StartInfo.WorkingDirectory = path + "mid\\";
                            System.Threading.Thread.Sleep(500);
                            p.Start();
                            p.WaitForExit();
                            System.Console.WriteLine("Missing midi");
                        }
                        if (System.IO.File.Exists(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid"))
                        {
                            midi = new SdlDotNet.Audio.Music(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid");
                            midi.Play(1);
                        }

                    }

                    modEnviron();

                    textBox1.Text = ((Array.IndexOf(gjd.filemap, gjd.Name) << 10) + rl.number).ToString();
                }
            }
            else
            {
                frameSeek.Enabled = false;
                // 11H
                if (gjdChooser.SelectedItem.ToString() == "Icons")
                {
                    Cursors_v2 cur = ((Cursors_v2)(this.gjdChooser.Tag));
                    frameSeek.Maximum = cur.cursors[vdxChooser.SelectedIndex == 4 ? 3 : vdxChooser.SelectedIndex].frames - 1;
                    frameSeek.Value = 0;
                    Cursors_v2.decodeCursor((byte)vdxChooser.SelectedIndex, 0, ref cur, ref s);
                    frameSeek.Enabled = true;
                }
                else
                {
                    // ROQ parser
                    if (roq != null)
                        roq.stop();
                    roq = null;

                    GJD.RLData rl = new GJD.RLData();

                    foreach (GJD.RLData subrl in V2_RL[gjdChooser.SelectedIndex])
                    {
                        if (subrl.filename == vdxChooser.SelectedItem.ToString())
                        {
                            rl = subrl;
                            break;
                        }
                    }
                    System.IO.BinaryReader r = new System.IO.BinaryReader(new System.IO.FileStream(path + "\\media\\" + gjdChooser.SelectedItem, System.IO.FileMode.Open,  System.IO.FileAccess.Read, System.IO.FileShare.Read));
                    r.BaseStream.Seek(rl.offset, System.IO.SeekOrigin.Begin);

                    System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.MemoryStream(r.ReadBytes((int)rl.length)));
                    if (rl.filename.Contains("xmi"))
                    {
                        roq = null;
                        string file = rl.filename;
                        if (file.Contains("\0"))
                            file = file.Substring(0, file.IndexOf("\0"));

                        if (!System.IO.File.Exists(path + "mid\\" + file))
                        {
                            byte[] buffer = new byte[reader.BaseStream.Length];
                            reader.Read(buffer, 0, buffer.Length);
                            System.IO.File.WriteAllBytes(path + "mid\\" + file, buffer);
                        }

                        if (!System.IO.File.Exists(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid"))
                        {
                            System.Diagnostics.Process p = new System.Diagnostics.Process();
                            p.StartInfo.FileName = path + "mid\\xmi2mid.exe";
                            p.StartInfo.Arguments = path + "mid\\" + file.Substring(0, file.IndexOf(".") + 4) + " " + path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid";
                            p.StartInfo.UseShellExecute = false;
                            p.StartInfo.WorkingDirectory = path + "mid\\";
                           // System.Threading.Thread.Sleep(500);
                           // p.Start();
                           // p.WaitForExit();
                            System.Console.WriteLine("Missing midi");
                        }
                        if (System.IO.File.Exists(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid"))
                        {
                            midi = new SdlDotNet.Audio.Music(path + "mid\\" + file.Substring(0, file.IndexOf(".")) + ".mid");
                            midi.Play(1);
                        }
                    }
                    else
                    {
                        roq = new ROQ(reader, s);
                    }
                    r.Close();
                    r = null;
                    modEnviron();

                    textBox1.Text = (rl.number).ToString();
                }
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// This function is called within VTDGen's loadIndex
        /// </summary>
        /// <param name="is_Renamed"></param>
        /// <param name="vg"></param>
        /// <returns></returns>
        public static void readIndex(System.IO.Stream is_Renamed, VTDGen vg)
        {
            if (is_Renamed == null || vg == null)
            {
                throw new System.ArgumentException("Invalid argument(s) for readIndex()");
            }
            //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' 
            //which has a different behavior. 
            //"ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
            System.IO.BinaryReader dis = new System.IO.BinaryReader(is_Renamed);
            byte b = dis.ReadByte(); // first byte
            // no check on version number for now
            // second byte
            vg.encoding = dis.ReadByte();
            int intLongSwitch;
            int endian;
            // third byte
            b = dis.ReadByte();
            if ((b & 0x80) != 0)
                intLongSwitch = 1;
            //use ints
            else
                intLongSwitch = 0;
            if ((b & 0x40) != 0)
                vg.ns = true;
            else
                vg.ns = false;
            if ((b & 0x20) != 0)
                endian = 1;
            else
                endian = 0;
            if ((b & 0x1f) != 0)
                throw new IndexReadException("Last 5 bits of the third byte should be zero");

            // fourth byte
            vg.VTDDepth = dis.ReadByte();

            // 5th and 6th byte
            int LCLevel = (((int)dis.ReadByte()) << 8) | dis.ReadByte();
            if (LCLevel != 4 &&  LCLevel != 6)
            {
                throw new IndexReadException("LC levels must be at least 3");
            }
            if (LCLevel == 4)
                vg.shallowDepth = true;
            else
                vg.shallowDepth = false;
            // 7th and 8th byte
            vg.rootIndex = (((int)dis.ReadByte()) << 8) | dis.ReadByte();

            // skip a long
            long l = dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            l = dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            l = dis.ReadInt64();
            //Console.WriteLine(" l ==>" + l);
            int size;
            // read XML size
            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
                size = (int)l;
            else
                size = (int)reverseLong(l);


            // read XML bytes
            byte[] XMLDoc = new byte[size];
            dis.Read(XMLDoc, 0, size);
            if ((size & 0x7) != 0)
            {
                int t = (((size >> 3) + 1) << 3) - size;
                while (t > 0)
                {
                    dis.ReadByte();
                    t--;
                }
            }

            vg.setDoc(XMLDoc);

            if (BitConverter.IsLittleEndian && endian == 0
                || BitConverter.IsLittleEndian == false && endian == 1)
            {
                // read vtd records
                int vtdSize = (int)dis.ReadInt64();
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(dis.ReadInt64());
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)dis.ReadInt64();
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(dis.ReadInt64());
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)dis.ReadInt64();
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(dis.ReadInt64());
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)dis.ReadInt64();
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(dis.ReadInt32());
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append((int)(dis.ReadInt64() >> 32));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(dis.ReadInt64());
                        l3Size--;
                    }

                    int l4Size = (int)dis.ReadInt64();
                    while (l4Size > 0)
                    {
                        vg._l4Buffer.append(dis.ReadInt64());
                        l4Size--;
                    }

                    int l5Size = (int)dis.ReadInt64();
                    if (intLongSwitch == 1)
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(dis.ReadInt32());
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append((int)(dis.ReadInt64() >> 32));
                            l5Size--;
                        }
                    }
                }
            }
            else
            {
                // read vtd records
                int vtdSize = (int)reverseLong(dis.ReadInt64());
                while (vtdSize > 0)
                {
                    vg.VTDBuffer.append(reverseLong(dis.ReadInt64()));
                    vtdSize--;
                }
                // read L1 LC records
                int l1Size = (int)reverseLong(dis.ReadInt64());
                while (l1Size > 0)
                {
                    vg.l1Buffer.append(reverseLong(dis.ReadInt64()));
                    l1Size--;
                }
                // read L2 LC records
                int l2Size = (int)reverseLong(dis.ReadInt64());
                while (l2Size > 0)
                {
                    vg.l2Buffer.append(reverseLong(dis.ReadInt64()));
                    l2Size--;
                }
                // read L3 LC records
                int l3Size = (int)reverseLong(dis.ReadInt64());
                if (vg.shallowDepth)
                {
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt(dis.ReadInt32()));
                            l3Size--;
                        }
                    }
                    else
                    {
                        while (l3Size > 0)
                        {
                            vg.l3Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l3Size--;
                        }
                    }
                }
                else
                {
                    while (l3Size > 0)
                    {
                        vg._l3Buffer.append(reverseLong(dis.ReadInt64()));
                        l3Size--;
                    }

                    int l4Size = (int)reverseLong(dis.ReadInt64());
                    {
                        vg._l4Buffer.append(reverseLong(dis.ReadInt64()));
                        l4Size--;
                    }

                    int l5Size = (int)reverseLong(dis.ReadInt64());
                    if (intLongSwitch == 1)
                    {
                        //l3 uses ints
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt(dis.ReadInt32()));
                            l5Size--;
                        }
                    }
                    else
                    {
                        while (l5Size > 0)
                        {
                            vg._l5Buffer.append(reverseInt((int)(dis.ReadInt64() >> 32)));
                            l5Size--;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 生成报表
        /// </summary>
        /// <param name="reportInfoName"></param>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <returns></returns>
        public static byte[] GenerateReport(string reportInfoName, DateTime dateStart, DateTime dateEnd)
        {
            CrystalHelper crystalHelper = new CrystalHelper();

            ReportInfo reportInfo = ADInfoBll.Instance.GetReportInfo(reportInfoName);
            if (reportInfo == null)
            {
                throw new ArgumentException("不存在名为" + reportInfoName + "的ReportInfo!");
            }
            ReportDocument reportDocument = ReportHelper.CreateReportDocument(reportInfo.ReportDocument);
            crystalHelper.ReportSource = reportDocument;
            System.Data.DataSet templateDataSet = ReportHelper.CreateDataset(reportInfo.DatasetName);

            IList<ISearchManager> sms = new List<ISearchManager>();
            IList<ReportDataInfo> reportDataInfos = ADInfoBll.Instance.GetReportDataInfo(reportInfo.Name);
            foreach (ReportDataInfo reportDataInfo in reportDataInfos)
            {
                if (string.IsNullOrEmpty(reportDataInfo.SearchManagerClassName))
                {
                    throw new ArgumentException("ReportDataInfo of " + reportDataInfo.Name + " 's SearchManagerClassName must not be null!");
                }

                ISearchManager sm = ServiceProvider.GetService<IManagerFactory>().GenerateSearchManager(reportDataInfo.SearchManagerClassName, reportDataInfo.SearchManagerClassParams);

                sm.EnablePage = false;

                sms.Add(sm);
            }

            ISearchExpression se = SearchExpression.And(SearchExpression.Ge("日期", dateStart),
                SearchExpression.Le("日期", dateEnd));
            for (int i = 0; i < reportDataInfos.Count; ++i)
            {
                System.Collections.IEnumerable dataList = sms[i].GetData(se, null);

                string s = reportDataInfos[i].DatasetTableName;
                if (!templateDataSet.Tables.Contains(s))
                {
                    throw new ArgumentException("报表DataSet中未包含名为" + s + "的DataTable!");
                }
                System.Data.DataTable dt = templateDataSet.Tables[s];
                dt.Rows.Clear();
                GenerateReportData.Generate(dt, dataList, reportDataInfos[i].GridName);
            }

            // Set Parameter
            SetParameter(crystalHelper, se);

            crystalHelper.DataSource = templateDataSet;

            string fileName = System.IO.Path.GetTempFileName();
            crystalHelper.Export(fileName, CrystalExportFormat.PortableDocFormat);

            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] fileData = new byte[fs.Length];

            using (System.IO.BinaryReader sr = new System.IO.BinaryReader(fs))
            {
                sr.Read(fileData, 0, fileData.Length);
            }
            fs.Close();
            System.IO.File.Delete(fileName);

            return fileData;
        }
Ejemplo n.º 38
0
		/// <summary>Renames an existing file in the directory. </summary>
		public override void  RenameFile(System.String from, System.String to)
		{
			lock (this)
			{
				System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from));
				System.IO.FileInfo nu = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, to));
				
				/* This is not atomic.  If the program crashes between the call to
				delete() and the call to renameTo() then we're screwed, but I've
				been unable to figure out how else to do this... */
				
				bool tmpBool;
				if (System.IO.File.Exists(nu.FullName))
					tmpBool = true;
				else
					tmpBool = System.IO.Directory.Exists(nu.FullName);
				if (tmpBool)
				{
					bool tmpBool2;
					if (System.IO.File.Exists(nu.FullName))
					{
						System.IO.File.Delete(nu.FullName);
						tmpBool2 = true;
					}
					else if (System.IO.Directory.Exists(nu.FullName))
					{
						System.IO.Directory.Delete(nu.FullName);
						tmpBool2 = true;
					}
					else
						tmpBool2 = false;
					if (!tmpBool2)
						throw new System.IO.IOException("Cannot delete " + to);
				}
				
				// Rename the old file to the new one. Unfortunately, the renameTo()
				// method does not work reliably under some JVMs.  Therefore, if the
				// rename fails, we manually rename by copying the old file to the new one
                try
                {
                    old.MoveTo(nu.FullName);
                }
                catch (System.Exception ex)
                {
                    System.IO.BinaryReader in_Renamed = null;
                    System.IO.Stream out_Renamed = null;
                    try
                    {
                        in_Renamed = new System.IO.BinaryReader(System.IO.File.Open(old.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        out_Renamed = new System.IO.FileStream(nu.FullName, System.IO.FileMode.Create);
                        // see if the buffer needs to be initialized. Initialization is
                        // only done on-demand since many VM's will never run into the renameTo
                        // bug and hence shouldn't waste 1K of mem for no reason.
                        if (buffer == null)
                        {
                            buffer = new byte[1024];
                        }
                        int len;
                        len = in_Renamed.Read(buffer, 0, buffer.Length);
                        out_Renamed.Write(buffer, 0, len);
						
                        // delete the old file.
                        bool tmpBool3;
                        if (System.IO.File.Exists(old.FullName))
                        {
                            System.IO.File.Delete(old.FullName);
                            tmpBool3 = true;
                        }
                        else if (System.IO.Directory.Exists(old.FullName))
                        {
                            System.IO.Directory.Delete(old.FullName);
                            tmpBool3 = true;
                        }
                        else
                            tmpBool3 = false;
                        bool generatedAux = tmpBool3;
                    }
                    catch (System.IO.IOException e)
                    {
                        throw new System.IO.IOException("Cannot rename " + from + " to " + to);
                    }
                    finally
                    {
                        if (in_Renamed != null)
                        {
                            try
                            {
                                in_Renamed.Close();
                            }
                            catch (System.IO.IOException e)
                            {
                                throw new System.SystemException("Cannot close input stream: " + e.Message);
                            }
                        }
                        if (out_Renamed != null)
                        {
                            try
                            {
                                out_Renamed.Close();
                            }
                            catch (System.IO.IOException e)
                            {
                                throw new System.SystemException("Cannot close output stream: " + e.Message);
                            }
                        }
                    }
                }
			}
		}
Ejemplo n.º 39
0
        /// <summary>
        /// CML: Created shared binary reader to ensure the file is being read correctly.
        /// </summary>
        /// <param name="File"></param>
        /// <returns>An array containing data.  Array is sized for the data from the file.</returns>
        public static byte[] readBinaryFile(System.IO.FileInfo File)
        {
            byte[] data = new byte[(int)File.Length];
            System.IO.BinaryReader fis = null;
            try
                {
                fis = new System.IO.BinaryReader(new System.IO.FileStream(File.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                fis.Read(data, 0, data.Length);
                }
            finally
                {
                if (fis != null)
                    fis.Close();
                }

            return data;
        }
Ejemplo n.º 40
0
        private void LoadPhoto(Profile profile, string path, string type)
        {
            if (!System.IO.File.Exists(path))
            {
                return;
            }

            System.IO.FileStream fs = null;
            System.IO.BinaryReader br = null;

            try
            {
                fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                br = new System.IO.BinaryReader(fs);

                long fileSize = fs.Length;
                byte[] buffer = new byte[fileSize];
                br.Read(buffer, 0, (int)buffer.Length);

                br.Close();
                fs.Close();

                profile.Photo = buffer;
                profile.PhotoFilename = path;
                profile.PhotoMimeType = type;
                profile.PhotoSize = buffer.Length;
                profile.PhotoUploadedOn = DateTime.Now;
            }
            catch
            { }
            finally
            {
                if (br != null) br.Close();
                if (fs != null) fs.Close();
            }
        }
Ejemplo n.º 41
0
        private void buttonUploadLocal_Click(object sender, RoutedEventArgs e)
        {
            const int bufferSize = 4096;

            var dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.Title = "选择文件";
            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            VFS.Directory dir = vfs.NewDirectory(currentDirectory);
            if (dir.Contains(dialog.SafeFileName))
            {
                System.Windows.Forms.MessageBox.Show("文件夹下已存在同名文件或文件夹", "添加失败", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 写入文件
                using (var reader = new System.IO.BinaryReader(new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open)))
                {
                    var file = vfs.NewFile(currentDirectory + dialog.SafeFileName, VFS.FileMode.Create);
                    byte[] buffer = new byte[bufferSize];
                    int count;
                    while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        file.Write(buffer, 0, (uint)count);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("添加文件失败 :-(", "添加失败", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }

            Reload();
        }
Ejemplo n.º 42
0
        private void listView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            const int bufferSize = 4096;

            var item = (DirectoryItem)listView.SelectedItem;

            if (item == null)
            {
                return;
            }

            if (item.isDirectory)
            {
                if (item.name == ".")
                {
                    Reload();
                    return;
                }
                if (item.name == "..")
                {
                    GoUp();
                    return;
                }

                if (history.Count - historyNeedle - 1 > 0)
                {
                    history.RemoveRange(historyNeedle + 1, history.Count - historyNeedle - 1);
                }
                var newDir = currentDirectory + item.name + "/";
                if (LoadDirectory(newDir))
                {
                    history.Add(newDir);
                    historyNeedle++;
                    buttonForward.IsEnabled = (historyNeedle + 1 < history.Count);
                    buttonBack.IsEnabled = (historyNeedle - 1 >= 0);
                }
            }
            else
            {
                // 读取文件内容到临时变量
                String tempFileName = System.IO.Path.GetTempFileName() + System.IO.Path.GetExtension(item.path);
                using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(new System.IO.FileStream(tempFileName, System.IO.FileMode.Create)))
                {
                    var file = vfs.NewFile(item.path, VFS.FileMode.Open);
                    byte[] buffer = new byte[bufferSize];
                    int count;
                    while ((count = (int)file.Read(buffer, 0, (uint)buffer.Length)) != 0)
                    {
                        writer.Write(buffer, 0, count);
                    }
                }

                FadeOutWindow();

                XamDialogWindow win = CreateDialogWindow();
                win.Header = "VFS";

                Label label = new Label();
                label.Content = "正在等待应用程序关闭, 文件内容将在程序关闭后自动更新...";
                label.VerticalContentAlignment = VerticalAlignment.Center;
                label.HorizontalAlignment = HorizontalAlignment.Center;

                win.Content = label;
                win.IsModal = true;
                windowContainer.Children.Add(win);

                Utils.ProcessUITasks();

                // 调用系统默认程序打开
                var process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(tempFileName);
                process.EnableRaisingEvents = true;
                process.Start();

                try
                {
                    process.WaitForExit();
                }
                catch (Exception ex)
                {
                }

                // 在关闭后,读取内容写回文件系统
                using (System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.FileStream(tempFileName, System.IO.FileMode.Open)))
                {
                    var file = vfs.NewFile(item.path, VFS.FileMode.Create);
                    byte[] buffer = new byte[bufferSize];
                    int count;
                    while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        file.Write(buffer, 0, (uint)count);
                    }
                }

                win.Close();
                windowContainer.Children.Remove(win);
                FadeInWindow();

                Reload();
                UpdateInfo();
            }
        }
Ejemplo n.º 43
0
        public void LoadLevelFile(System.IO.Stream stream)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(stream);

            /* Get Current App Version For Comparison */
            String currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            /* Check Loading File's Version To Current */
            String fileVersion = br.ReadString();
            if (fileVersion != currentVersion)
            {
                /* ERROR: File Version Out of Date */
                throw new IncorrectFileVersionException();
            }

            /* Load the Level Attributes */
            levelName = br.ReadString();

            /* Load the Object Type Palette */
            List<FileOps.LevelObjectTypeDefinition> types = FileOps.ReadObjectPalette(br);

            /* Level Terrain */
            int numTerrainChunks = br.ReadInt32();
            for (int i = 0; i < numTerrainChunks; i++)
            {
                LevelTerrain terrain = new LevelTerrain();
                terrain.Name = br.ReadString();
                terrain.Position = FileOps.ReadVec3(br);

                Scale scale = new Scale();
                scale.scales = FileOps.ReadVec3(br);
                terrain.Scaling = scale;

                Point pt = new Point();
                pt.X = br.ReadInt32();
                pt.Y = br.ReadInt32();
                terrain.HeightMapDimensions = pt;

                int numSamples = terrain.HeightMapDimensions.X * terrain.HeightMapDimensions.Y;
                byte[] heightMap = new byte[numSamples];
                br.Read(heightMap, 0, numSamples);
                terrain.HeightMap = heightMap;

                terrainObjects.Add(terrain.Name, terrain);
            }

            /* Load Level Object Instances */
            int levelCnt = br.ReadInt32();
            System.Collections.Generic.List<LevelObject> lvlObjs = new List<LevelObject>();

            for (int i = 0; i < levelCnt; i++)
            {
                LevelObject lo = new LevelObject();

                /* Save Object Instance Attributes */
                lo.Index = br.ReadInt32();
                lo.Name = br.ReadString();
                lo.TypeId = new Guid(br.ReadString());

                /* Object Instance Transforms */
                lo.Rotation = FileOps.ReadVec3(br);
                lo.Scale = FileOps.ReadVec3(br);
                lo.Position = FileOps.ReadVec3(br);

                lvlObjs.Add(lo);

                m_nextUnusedObID = Math.Max(lo.Index, m_nextUnusedObID);
                m_nextUnusedObID++;
            }

            br.Close();

            /* Load the Level Object Types Definitions From
             * Files For Each Type in Level's Object Palette */
            foreach (FileOps.LevelObjectTypeDefinition t in types)
            {
                /* Try to Open the Type's File */
                String typeFilename = levelFileName;
                int idx = typeFilename.LastIndexOf('\\')+1;
                typeFilename = typeFilename.Substring(0, idx);
                typeFilename += t.FileName;

                System.IO.FileStream typeFile = null;

                try
                {
                    typeFile = System.IO.File.Open(typeFilename, System.IO.FileMode.Open);

                    /* Fill Out a New Object Type from The File Definition */
                    LevelObjectType lot = LoadTypeFile(typeFile);

                    /* Verify the Type Matches the Guid From the Level Type Palette */
                    if (lot.TypeID == t.TypeId)
                    {
                        this.objectPalette.Add(lot.Name, lot);
                    }
                    else
                    {
                        System.Diagnostics.Debug.Assert(true);
                    }

                    /* Increment the Type ID counter */
                    m_nextUnusedTypeID = Math.Max(lot.Index, m_nextUnusedTypeID);
                    m_nextUnusedTypeID++;
                }
                finally
                {
                    typeFile.Close();
                }
            }

            /* Add the object to the level linked to their type */
            foreach (LevelObject lo in lvlObjs)
            {
                AddObjectToLvl(lo, false);
            }
        }
Ejemplo n.º 44
0
        public LevelTerrain LoadTerrainFile(System.IO.Stream stream)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(stream);

            byte[] fileBuffer = new byte[stream.Length];
            br.Read(fileBuffer, 0, (int)stream.Length);

            LevelTerrain terrain = new LevelTerrain();
            Scale scales = new Scale();
            scales.Scales = new Vector3(10.0f, 1.0f, 10.0f);
            terrain.Scaling = scales;

            // assume square image
            int dim = (int)Math.Sqrt(stream.Length);
            terrain.HeightMapDimensions = new Point(dim, dim);
            terrain.HeightMap = fileBuffer;

            String name = "TERRAIN" + GetNextTerrainIdx();
            terrain.Name = name;
            return terrain;
        }
Ejemplo n.º 45
0
 public static RangedListFilter Deserialize(byte[] bytes)
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             int itemCount = BR.ReadInt32 ();
             int skipBytes = BR.ReadInt32 ();
             byte[] skippedBytes = BR.ReadBytes (skipBytes);
             byte[][] items = new byte[itemCount][];
             for (int n = 0; n != itemCount; n++) {
                 int itemLength = BR.ReadInt32 ();
                 byte[] item = new byte[skipBytes + itemLength];
                 System.Buffer.BlockCopy (skippedBytes, 0, item, 0, skipBytes);
                 BR.Read (item, skipBytes, itemLength);
                 items [n] = item;
             }
             return new RangedListFilter (new [] { items });
         }
     }
 }
Ejemplo n.º 46
0
        /// <summary>
        /// Get a cryptographic service for encrypting data using the server's RSA public key
        /// </summary>
        /// <param name="key">Byte array containing the encoded key</param>
        /// <returns>Returns the corresponding RSA Crypto Service</returns>
        public static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] x509key)
        {
            /* Code from StackOverflow no. 18091460 */

            byte[] SeqOID = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };

            System.IO.MemoryStream ms = new System.IO.MemoryStream(x509key);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(ms);

            if (reader.ReadByte() == 0x30)
                ReadASNLength(reader); //skip the size
            else
                return null;

            int identifierSize = 0; //total length of Object Identifier section
            if (reader.ReadByte() == 0x30)
                identifierSize = ReadASNLength(reader);
            else
                return null;

            if (reader.ReadByte() == 0x06) //is the next element an object identifier?
            {
                int oidLength = ReadASNLength(reader);
                byte[] oidBytes = new byte[oidLength];
                reader.Read(oidBytes, 0, oidBytes.Length);
                if (oidBytes.SequenceEqual(SeqOID) == false) //is the object identifier rsaEncryption PKCS#1?
                    return null;

                int remainingBytes = identifierSize - 2 - oidBytes.Length;
                reader.ReadBytes(remainingBytes);
            }

            if (reader.ReadByte() == 0x03) //is the next element a bit string?
            {
                ReadASNLength(reader); //skip the size
                reader.ReadByte(); //skip unused bits indicator
                if (reader.ReadByte() == 0x30)
                {
                    ReadASNLength(reader); //skip the size
                    if (reader.ReadByte() == 0x02) //is it an integer?
                    {
                        int modulusSize = ReadASNLength(reader);
                        byte[] modulus = new byte[modulusSize];
                        reader.Read(modulus, 0, modulus.Length);
                        if (modulus[0] == 0x00) //strip off the first byte if it's 0
                        {
                            byte[] tempModulus = new byte[modulus.Length - 1];
                            Array.Copy(modulus, 1, tempModulus, 0, modulus.Length - 1);
                            modulus = tempModulus;
                        }

                        if (reader.ReadByte() == 0x02) //is it an integer?
                        {
                            int exponentSize = ReadASNLength(reader);
                            byte[] exponent = new byte[exponentSize];
                            reader.Read(exponent, 0, exponent.Length);

                            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                            RSAParameters RSAKeyInfo = new RSAParameters();
                            RSAKeyInfo.Modulus = modulus;
                            RSAKeyInfo.Exponent = exponent;
                            RSA.ImportParameters(RSAKeyInfo);
                            return RSA;
                        }
                    }
                }
            }
            return null;
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Loads the file data in binary format
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>Binary file data</returns>
        private static byte[] LoadFileData(string fileName)
        {
            byte[] data = null;

            using (System.IO.FileStream fStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (System.IO.BinaryReader reader = new System.IO.BinaryReader(fStream))
                {
                    data = new byte[fStream.Length];
                    reader.Read(data, 0, data.Length);
                }
            }

            return data;
        }
Ejemplo n.º 48
0
 public static ActionLibrary Load(System.IO.Stream s)
 {
     ActionLibrary lib = new ActionLibrary();
     System.IO.BinaryReader br = new System.IO.BinaryReader(s, Encoding.ASCII);
     lib.GameMakerVersion = br.ReadInt32();
     bool gm5 = lib.GameMakerVersion == 500;
     lib.TabCaption = new string(br.ReadChars(br.ReadInt32()));
     lib.LibraryID = br.ReadInt32();
     lib.Author = new string(br.ReadChars(br.ReadInt32()));
     lib.Version = br.ReadInt32();
     lib.LastChanged = new DateTime(1899, 12, 30).AddDays(br.ReadDouble());
     lib.Info = new string(br.ReadChars(br.ReadInt32()));
     lib.InitializationCode = new string(br.ReadChars(br.ReadInt32()));
     lib.AdvancedModeOnly = br.ReadInt32() == 0 ? false : true;
     lib.ActionNumberIncremental = br.ReadInt32();
     for (int i = br.ReadInt32(); i > 0; i--)
     {
         int ver = br.ReadInt32();
         ActionDefinition a = new ActionDefinition(lib, new string(br.ReadChars(br.ReadInt32())), br.ReadInt32());
         a.GameMakerVersion = ver;
         int size = br.ReadInt32();
         a.OriginalImage = new byte[size];
         br.Read(a.OriginalImage, 0, size);
         System.IO.MemoryStream ms = new System.IO.MemoryStream(a.OriginalImage);
         System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(ms);
         a.Image = new System.Drawing.Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
         using (var g = System.Drawing.Graphics.FromImage(a.Image))
         {
             g.DrawImage(b, new System.Drawing.Rectangle(0, 0, b.Width, b.Height));
         }
         if (b.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
             ((System.Drawing.Bitmap)a.Image).MakeTransparent(b.GetPixel(0, b.Height - 1));
         ms.Close();
         b.Dispose();
         a.Hidden = br.ReadInt32() == 0 ? false : true;
         a.Advanced = br.ReadInt32() == 0 ? false : true;
         a.RegisteredOnly = ver == 500 || (br.ReadInt32() == 0) ? false : true;
         a.Description = new string(br.ReadChars(br.ReadInt32()));
         a.ListText = new string(br.ReadChars(br.ReadInt32()));
         a.HintText = new string(br.ReadChars(br.ReadInt32()));
         a.Kind = (ActionKind)br.ReadInt32();
         a.InterfaceKind = (ActionInferfaceKind)br.ReadInt32();
         a.IsQuestion = br.ReadInt32() == 0 ? false : true;
         a.ShowApplyTo = br.ReadInt32() == 0 ? false : true;
         a.ShowRelative = br.ReadInt32() == 0 ? false : true;
         a.ArgumentCount = br.ReadInt32();
         int count = br.ReadInt32();
         if (a.Arguments.Length != count)
             a.Arguments = new ActionArgument[count];
         for (int j = 0; j < count; j++)
         {
             a.Arguments[j] = new ActionArgument();
             a.Arguments[j].Caption = new string(br.ReadChars(br.ReadInt32()));
             a.Arguments[j].Type = (ActionArgumentType)br.ReadInt32();
             a.Arguments[j].DefaultValue = new string(br.ReadChars(br.ReadInt32()));
             a.Arguments[j].Menu = new string(br.ReadChars(br.ReadInt32()));
         }
         a.ExecutionType = (ActionExecutionType)br.ReadInt32();
         a.FunctionName = new string(br.ReadChars(br.ReadInt32()));
         a.Code = new string(br.ReadChars(br.ReadInt32()));
         lib.Actions.Add(a);
     }
     //Hmm...
     //ActionDefinition d = new ActionDefinition(lib);
     //d.Description = "Font...";
     //d.ArgumentCount = 1;
     //d.Arguments[0] = new ActionArgument();
     //d.Arguments[0].Type = ActionArgumentType.FontString;
     //d.ListText = "@0";
     //lib.Actions.Add(d);
     //d.Arguments[0].DefaultValue = "\"Times New Roman\",10,0,0,0,0,0";
     return lib;
 }
Ejemplo n.º 49
0
        private System.Drawing.Image LoadImageFromURL(string URL)
        {
            const int BYTESTOREAD = 10000;
            WebRequest myRequest = WebRequest.Create(URL);
            WebResponse myResponse = myRequest.GetResponse();
            System.IO.Stream ReceiveStream = myResponse.GetResponseStream();
            System.IO.BinaryReader br = new System.IO.BinaryReader(ReceiveStream);
            System.IO.MemoryStream memstream = new System.IO.MemoryStream();
            byte[] bytebuffer = new byte[BYTESTOREAD];
            int BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);
            while (BytesRead > 0) {
                memstream.Write(bytebuffer, 0, BytesRead);
                BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD);
            }

            return System.Drawing.Image.FromStream(memstream);
        }
    /// <summary>
    /// Imports a Galactic SPC file into a x and an y array. The file must not be a multi spectrum file (an exception is thrown in this case).
    /// </summary>
    /// <param name="xvalues">The x values of the spectrum.</param>
    /// <param name="yvalues">The y values of the spectrum.</param>
    /// <param name="filename">The filename where to import from.</param>
    /// <returns>Null if successful, otherwise an error description.</returns>
    public static string ToArrays(string filename, out double [] xvalues, out double [] yvalues)
    {
      System.IO.Stream stream=null;

      SPCHDR hdr = new SPCHDR();
      SUBHDR subhdr = new SUBHDR();

      try
      {
        stream = new System.IO.FileStream(filename,System.IO.FileMode.Open,System.IO.FileAccess.Read,System.IO.FileShare.Read);
        System.IO.BinaryReader binreader = new System.IO.BinaryReader(stream);


        hdr.ftflgs = binreader.ReadByte(); // ftflgs : not-evenly spaced data
        hdr.fversn = binreader.ReadByte(); // fversn : new version
        hdr.fexper = binreader.ReadByte(); // fexper : general experimental technique
        hdr.fexp   = binreader.ReadByte(); // fexp   : fractional scaling exponent (0x80 for floating point)

        hdr.fnpts  = binreader.ReadInt32(); // fnpts  : number of points

        hdr.ffirst = binreader.ReadDouble(); // ffirst : first x-value
        hdr.flast  = binreader.ReadDouble(); // flast : last x-value
        hdr.fnsub  = binreader.ReadInt32(); // fnsub : 1 (one) subfile only
      
        binreader.ReadByte(); //  Type of X axis units (see definitions below) 
        binreader.ReadByte(); //  Type of Y axis units (see definitions below) 
        binreader.ReadByte(); // Type of Z axis units (see definitions below)
        binreader.ReadByte(); // Posting disposition (see GRAMSDDE.H)

        binreader.Read(new byte[0x1E0],0,0x1E0); // rest of SPC header


        // ---------------------------------------------------------------------
        //   following the x-values array
        // ---------------------------------------------------------------------

        if(hdr.fversn!=0x4B)
        {
          if(hdr.fversn==0x4D)
            throw new System.FormatException(string.Format("This SPC file has the old format version of {0}, the only version supported here is the new version {1}",hdr.fversn,0x4B));
          else
            throw new System.FormatException(string.Format("This SPC file has a version of {0}, the only version recognized here is {1}",hdr.fversn,0x4B));
        }

        if(0!=(hdr.ftflgs & 0x80))
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = binreader.ReadSingle();
        }
        else if(0==hdr.ftflgs) // evenly spaced data
        {
          xvalues = new double[hdr.fnpts];
          for(int i=0;i<hdr.fnpts;i++)
            xvalues[i] = hdr.ffirst + i*(hdr.flast-hdr.ffirst)/(hdr.fnpts-1);
        }
        else
        {
          throw new System.FormatException("The SPC file must not be a multifile; only single file format is accepted!");
        }



        // ---------------------------------------------------------------------
        //   following the y SUBHEADER
        // ---------------------------------------------------------------------

        subhdr.subflgs = binreader.ReadByte(); // subflgs : always 0
        subhdr.subexp  = binreader.ReadByte(); // subexp : y-values scaling exponent (set to 0x80 means floating point representation)
        subhdr.subindx = binreader.ReadInt16(); // subindx :  Integer index number of trace subfile (0=first)

        subhdr.subtime = binreader.ReadSingle(); // subtime;   Floating time for trace (Z axis corrdinate) 
        subhdr.subnext = binreader.ReadSingle(); // subnext;   Floating time for next trace (May be same as beg) 
        subhdr.subnois = binreader.ReadSingle(); // subnois;   Floating peak pick noise level if high byte nonzero 

        subhdr.subnpts = binreader.ReadInt32(); // subnpts;  Integer number of subfile points for TXYXYS type 
        subhdr.subscan = binreader.ReadInt32(); // subscan; Integer number of co-added scans or 0 (for collect) 
        subhdr.subwlevel = binreader.ReadSingle();        // subwlevel;  Floating W axis value (if fwplanes non-zero) 
        subhdr.subresv   = binreader.ReadInt32(); // subresv[4];   Reserved area (must be set to zero) 


        // ---------------------------------------------------------------------
        //   following the y-values array
        // ---------------------------------------------------------------------
        yvalues = new double[hdr.fnpts];
        
        if(hdr.fexp==0x80) //floating point format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadSingle();
        }
        else // fixed exponent format
        {
          for(int i=0;i<hdr.fnpts;i++)
            yvalues[i] = binreader.ReadInt32()*Math.Pow(2,hdr.fexp-32);
        }
      }
      catch(Exception e)
      {
        xvalues = null;
        yvalues = null;
        return e.ToString();
      }
      finally
      {
        if(null!=stream)
          stream.Close();
      }
      
      return null;
    }