/// <summary> /// Compresses a byte array /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressBytes(this byte[] data) { // empty if null if (data.IsNullOrEmpty()) return null; using (MemoryStream msBZip2 = new MemoryStream()) { int size = data.Length; // Prepend the compressed data with the length of the uncompressed data (firs 4 bytes) using (BinaryWriter writer = new BinaryWriter(msBZip2)) { writer.Write(size); using (BZip2OutputStream BZip2OutStream = new BZip2OutputStream(msBZip2)) { BZip2OutStream.Write(data, 0, size); } } // return the compressed data return msBZip2.ToArray(); } }
public static void Main() { byte[] bytes; var values = new long[] { 0, 1, 0xFFFF, 0xFF00FF00FF00L, 12345678901234L, -0xFFFF, -0xFF00FF00FF00L }; long length; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { foreach (var value in values) { bw.Write(value); Console.WriteLine(value); } bw.Flush(); length = ms.Position; bytes = ms.GetBuffer(); } Util.PrintByteArray(bytes, (int)length); using (var ms = new MemoryStream(bytes, false)) using (var br = new BinaryReader(ms)) { for (int i = 0; i < values.Length; i++) { var value = br.ReadInt64(); Console.WriteLine(value); } } }
public GooBinaryRange(GooBinary pBinary, BinaryWriter pUnderlyingWriter, int pStart, int pLength) { _binary = pBinary; _writer = pUnderlyingWriter; Start = pStart; Length = pLength; }
public void Save(BinaryWriter Stream) { Stream.Write(PathTexture, true); Stream.Write(PathNormalmap, true); Stream.Write(ScaleTexture); Stream.Write(ScaleNormalmap); }
public static int Main () { MemoryStream mr = new MemoryStream(); BinaryWriter wr = new BinaryWriter(mr); wr.Write ((byte) 1); wr.Write ((int) 1); wr.Write ((int) -1); byte [] arr = mr.ToArray(); Console.Write ("Array (should be: 1 1 0 0 0 ff ff ff ff): "); for (int a = 0; a != arr.Length; a++) Console.Write(arr[a].ToString("x") + " "); Console.WriteLine(); if (arr.Length != 9) return 4; if (arr[0] != 1) return 1; if (arr[1] != 1 && arr[2] != 0 && arr[3] != 0 && arr[4] != 0) return 2; if (arr[5] != 0xff && arr[6] != 0xff && arr[7] != 0xff && arr[8] != 0xff) return 3; Console.WriteLine("test-ok"); return 0; }
public void GetMemberOrParent(string id) { IList<Hashtable> listMembers = bl.GetmemberInfo(id, 0); IList<Hashtable> list = null; string imgs = ""; if (listMembers != null) { list = bl.GetmemberInfo(id, 1); Hashtable htb = new Hashtable(); htb = listMembers[0]; if (htb["B_ATTACHMENT"] != null && htb["B_ATTACHMENT"].ToString() != "") { byte[] imgBytes = (byte[])(htb["B_ATTACHMENT"]); string filePath = "../Files/" + htb["T_USERID"] + ".jpg"; imgs = filePath; filePath = Server.MapPath(filePath); BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate)); bw.Write(imgBytes); bw.Close(); } } obj = new { img = imgs, list = list, }; string result = JsonConvert.SerializeObject(obj); Response.Write(result); Response.End(); }
public GameLogger() { DateTime now = DateTime.Now; string dir = ""; if(Application.platform == RuntimePlatform.Android) { dir = Application.persistentDataPath + "/logs/"; } else if(Application.platform == RuntimePlatform.IPhonePlayer) { dir = Application.persistentDataPath + "/logs/"; } else if(Application.platform == RuntimePlatform.WindowsPlayer) { dir = Application.dataPath + "/logs/"; } else return; if(!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } this.mFile = new FileStream(dir + "log_" + now.ToString("MM-dd_hh-mm-ss") + ".log",FileMode.Append); this.mFileWriter = new BinaryWriter(this.mFile); }
public void Write (float[] clipData, WaveFormatChunk format, FileStream stream) { WaveHeader header = new WaveHeader (); WaveDataChunk data = new WaveDataChunk (); data.shortArray = new short[clipData.Length]; for (int i = 0; i < clipData.Length; i++) data.shortArray [i] = (short)(clipData [i] * 32767); data.dwChunkSize = (uint)(data.shortArray.Length * (format.wBitsPerSample / 8)); BinaryWriter writer = new BinaryWriter (stream); writer.Write (header.sGroupID.ToCharArray ()); writer.Write (header.dwFileLength); writer.Write (header.sRiffType.ToCharArray ()); writer.Write (format.sChunkID.ToCharArray ()); writer.Write (format.dwChunkSize); writer.Write (format.wFormatTag); writer.Write (format.wChannels); writer.Write (format.dwSamplesPerSec); writer.Write (format.dwAvgBytesPerSec); writer.Write (format.wBlockAlign); writer.Write (format.wBitsPerSample); writer.Write (data.sChunkID.ToCharArray ()); writer.Write (data.dwChunkSize); foreach (short dataPoint in data.shortArray) { writer.Write (dataPoint); } writer.Seek (4, SeekOrigin.Begin); uint filesize = (uint)writer.BaseStream.Length; writer.Write (filesize - 8); writer.Close (); }
public void Write(BinaryWriter w) { //if (w == null) throw new ArgumentNullException("w"); w.Write(FResult.ToString()); w.Write(FSeparator); w.Write(FEmpty); }
/// <summary> /// Inspects all public primitive and serializable (non-reference) fields in the given object and writes them /// to the given BinaryWriter. /// </summary> /// <param name='type'> /// Type. /// </param> /// <param name='writer'> /// Writer. /// </param> public static void WriteToBinaryStream(Object targetObj, BinaryWriter writer) { System.Type objType = targetObj.GetType(); FieldInfo[] publicFields = objType.GetFields(BindingFlags.Instance | BindingFlags.Public); for(int i = 0; i < publicFields.Length; i++) { System.Type fieldType = publicFields[i].FieldType; if ((fieldType.IsValueType || fieldType == typeof(string)) && !System.Attribute.IsDefined(publicFields[i], typeof(System.NonSerializedAttribute)) ) { Debug.Log(targetObj.name + " -> " + publicFields[i].Name + " = " + publicFields[i].GetValue(targetObj)); } } Debug.Log("Public properties:"); PropertyInfo[] publicProp = objType.GetProperties(BindingFlags.Instance | BindingFlags.Public); for(int i = 0; i < publicProp.Length; i++) { System.Type propType = publicProp[i].PropertyType; if (propType.IsValueType || propType == typeof(string)) { Debug.Log(targetObj.name + " -> " + publicProp[i].Name + " = " + publicProp[i].GetValue(targetObj, null)); Debug.Log(publicProp[i].Name + " = " + propType.Name); } } }
public void WriteData(BinaryWriter resourceWriter) { if (fileReference == null) { try { using (Stream stream = streamProvider()) { if (stream == null) { throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); } var count = (int)(stream.Length - stream.Position); resourceWriter.WriteInt(count); var to = resourceWriter.BaseStream; var position = (int)to.Position; to.Position = (uint)(position + count); resourceWriter.Align(8); var buffer = to.Buffer; stream.Read(buffer, position, count); } } catch (Exception e) { throw new ResourceException(this.name, e); } } }
public static void InitLog(string FileName) { Errors = new List<string>(); try { if (File.Exists(FileName)) { if (File.Exists(FileName+"~")) { File.Delete(FileName+"~"); } File.Move(FileName,FileName+"~"); } } catch(Exception ex) { Log.LogError("Init log error at Delete "+FileName+"~ : "+ex.Message); } try { Writer=new BinaryWriter(new FileStream(FileName,FileMode.CreateNew)); } catch(Exception ex) { Log.LogError("Init log error: "+ex.Message); } if (Writer!=null && Writer.BaseStream.CanWrite) Writer.Write(" Log Started at : "+DateTime.Now.ToLongTimeString()+"\n"); }
public static bool SaveGame() { GameDataContainer data = new GameDataContainer (); data.Money = GameController.Instance.Money; for(int i = 0; i < (int)Products.Max; i++) { data.ProdList[i] = GameController.Instance.ProdList[(Products)i].Level; } using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("Data/SaveGame.dat"))) { bw.Write(new char[10]); byte[] money = Encoding.ASCII.GetBytes(data.Money.ToString()); bw.Write(money.Length); bw.Write(money); for (int i = 0; i < (int)Products.Max; i++) { bw.Write(data.ProdList[i]); } int upCount = UpgradeController.Instance.AcquiredUps.Count; bw.Write(upCount); for(int i = 0; i < upCount; i++) { bw.Write(UpgradeController.Instance.AcquiredUps[i]); } } return true; }
public static void Main() { Console.WriteLine("999 is 03e7 when big endian"); Console.WriteLine("999 = " + BitConverter.ToString(BitConverter.GetBytes(999))); Console.WriteLine("byteorder = " + (BitConverter.IsLittleEndian ? "little" : "big")); int x = (1 << 24) + (2 << 16) + (3 << 8) + 4; Console.WriteLine("int = " + x + " # " + BitConverter.ToString(BitConverter.GetBytes(x), 0)); using(var m = new MemoryStream()) { using(var w = new BinaryWriter(m)) { w.Write(x); m.Seek(0, SeekOrigin.Begin); var buf = m.GetBuffer(); Array.Resize(ref buf, 4); Console.WriteLine("write = " + BitConverter.ToInt32(buf, 0) + " # " + BitConverter.ToString(buf, 0)); using(var r = new BinaryReader(m)) { int y = r.ReadInt32(); Console.WriteLine("read = " +y + " # " + BitConverter.ToString(BitConverter.GetBytes(y))); } } } }
public override void Save(BinaryWriter bw) { base.Save(bw); bw.Write(dir == 1); bw.Write((byte)height); bw.Write(sin); bw.Write(sinSpeed); }
void CreatePhoto() { try { string strPhoto = Request.Form["imageData"]; //Get the image from flash file byte[] photo = Convert.FromBase64String(strPhoto); string dirUrl = "~/Uploads/cuc_Picture/"; string dirPath = Server.MapPath(dirUrl); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } FileStream fs = new FileStream(dirPath+"St_Pic.jpg", FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter br = new BinaryWriter(fs); br.Write(photo); br.Flush(); br.Close(); fs.Close(); string camimg = dirPath + "St_Pic.jpg"; Session["imagePath"] = camimg; } catch (Exception Ex) { } }
public void Load(int Index){ MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity(); CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType .Allow)); using(MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("bits", (long)Math.Ceiling(Length/8.0), MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable)){ using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { int Amount = (int)Math.Ceiling((double)(Length/Int32.MaxValue)); int Remainder = (int)(Length%Int32.MaxValue); int length = (int)(Amount==Index?Math.Ceiling(Remainder/8.0):Math.Ceiling(Int32.MaxValue/8.0)); byte[] buffer = BitArrayToByteArray(LoadedArray,0,LoadedArray.Length); stream.Position=(long)Math.Ceiling((Int32.MaxValue/8.0))*LoadedArrayIndex; BinaryWriter writer = new BinaryWriter(stream); writer.Write(buffer); stream.Position=0;//(long)Math.Ceiling((Int32.MaxValue/8.0))*Index; BinaryReader reader = new BinaryReader(stream); buffer = new byte[(int)Math.Ceiling((Int32.MaxValue/8.0))]; try{reader.Read(buffer,(int)Math.Ceiling((Int32.MaxValue/8.0))*Index,(int)Math.Ceiling((Int32.MaxValue/8.0)));} catch{LoadedArray = new BitArray((int)(length*8.0));} } } //int ElementIndex = (int)Math.Floor((double)(T/Int32.MaxValue)); //int Index = (int)(T%Int32.MaxValue); //Elements[ElementIndex][Index]=value; //} }
public void WriteBlock(Stream stream) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(Tag); writer.Write(Size); writer.Write(Data); }
public static void makeAtlas(Texture2D[] textures) { if (textures != null && textures.Length > 1) { // Make our atlas gameobject with a blank atlas script on it. GameObject go = new GameObject("TEST_ATLAS"); go.AddComponent<Atlas>(); // The blank texture is replaced with the packed texture. Texture2D tex = new Texture2D(2, 2); // Now pack the textures Rect[] UVs = tex.PackTextures(textures, 2, 4096); // Create out spriteAnimation components onto the atlas with height/width equal to the source. for (int i = 0; i < UVs.Length; i++) { SpriteAnimation anim = go.AddComponent<SpriteAnimation>(); anim.setData(textures[i].name, UVs[i]); } FileStream fs = new FileStream(Application.dataPath + "/Resources/Sprites/Atlas_Sprite.png", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(tex.EncodeToPNG()); bw.Close(); fs.Close(); //PrefabUtility.CreatePrefab(Application.dataPath + "/Resources/Atlases/" + go.name + ".prefab", go); } else { Debug.LogWarning("Given Textures are null or singular."); } }
public byte[] encode(ItemQuote item) { MemoryStream mem = new MemoryStream(); BinaryWriter output = new BinaryWriter(new BufferedStream(mem)); output.Write(IPAddress.HostToNetworkOrder(item.itemNumber)); output.Write(IPAddress.HostToNetworkOrder(item.quantity)); output.Write(IPAddress.HostToNetworkOrder(item.unitPrice)); byte flags = 0; if (item.discounted) flags |= ItemQuoteBinConst.DISCOUNT_FLAG; if (item.inStock) flags |= ItemQuoteBinConst.IN_STOCK_FLAG; output.Write(flags); byte[] encodedDesc = encoding.GetBytes(item.itemDescription); if (encodedDesc.Length > ItemQuoteBinConst.MAX_DESC_LEN) throw new IOException("Item Description exceeds encoded length limit"); output.Write((byte)encodedDesc.Length); output.Write(encodedDesc); output.Flush(); return mem.ToArray(); }
// Use this for initialization void Start() { var path = Application.dataPath + "/" + "ranki.txt"; if (!File.Exists(path)) { { FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryWriter writer = new BinaryWriter(fs); if (writer != null) { writer.Write(100000); writer.Close(); } } } { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(fs); if (reader != null) { var i = reader.ReadInt32(); reader.Close(); Debug.Log(i); } } }
IEnumerator ShareScreenshotInterface.ShareScreenshot(byte[] screenshot, bool isProcessing, string shareText, string gameLink, string subject) { isProcessing = true; string destination = Path.Combine(Application.persistentDataPath, "Screenshot.png"); FileStream fs = new FileStream(destination, FileMode.OpenOrCreate); BinaryWriter ww = new BinaryWriter(fs); ww.Write(screenshot); ww.Close(); fs.Close(); AndroidJavaClass intentClass = new AndroidJavaClass("android.content.Intent"); AndroidJavaObject intentObject = new AndroidJavaObject("android.content.Intent"); intentObject.Call<AndroidJavaObject>("setAction", intentClass.GetStatic<string>("ACTION_SEND")); AndroidJavaClass uriClass = new AndroidJavaClass("android.net.Uri"); AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject>("parse", "file://" + destination); intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_STREAM"), uriObject); intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_TEXT"), shareText + gameLink); intentObject.Call<AndroidJavaObject>("putExtra", intentClass.GetStatic<string>("EXTRA_SUBJECT"), subject); intentObject.Call<AndroidJavaObject>("setType", "image/png"); AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity"); currentActivity.Call("startActivity", intentObject); isProcessing = false; yield return new WaitForSeconds(1); }
public static byte[] Serialize(Account account) { using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { try { writer.Write(account.Email); writer.Write(account.Username); writer.Write((byte)account.Characters.Length); for (int i = 0; i < account.Characters.Length; i++) { byte[] bytes = Serialize(account.Characters[i]); writer.Write(bytes.Length); writer.Write(bytes); } return stream.ToArray(); } catch (Exception e) { Debug.Log("Exception at Serialization.Serialize: " + e.Message); return new byte[0]; } } }
public static void ExtractFile(ListViewFileItem lvi, string exeName, string outName) { //extract file in ListViewFileItem FileStream fsIn = null; BinaryReader brIn = null; FileStream fsOut = null; BinaryWriter bwOut = null; try { fsIn = new FileStream(exeName, FileMode.Open); brIn = new BinaryReader(fsIn); fsOut = new FileStream(outName, FileMode.Create); bwOut = new BinaryWriter(fsOut); fsIn.Seek(lvi.Offset, SeekOrigin.Begin); bwOut.Write(brIn.ReadBytes(lvi.Size)); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (brIn != null) brIn.Close(); if (fsIn != null) fsIn.Close(); if (bwOut != null) bwOut.Close(); if (fsOut != null) fsOut.Close(); } }
public static void SaveToDisk(string resourceName, string fileName) { // Get a reference to the running application. Assembly assy = Assembly.GetExecutingAssembly(); // Loop through each resource, looking for the image name (case-insensitive). foreach (string resource in assy.GetManifestResourceNames()) { if (resource.ToLower().IndexOf(resourceName.ToLower()) != -1) { // Get the embedded file from the assembly as a MemoryStream. using (System.IO.Stream resourceStream = assy.GetManifestResourceStream(resource)) { if (resourceStream != null) { using (BinaryReader reader = new BinaryReader(resourceStream)) { // Read the bytes from the input stream. byte[] buffer = reader.ReadBytes(Convert.ToInt32(resourceStream.Length)); using (FileStream outputStream = new FileStream(fileName, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(outputStream)) { // Write the bytes to the output stream. writer.Write(buffer); } } } } } break; // TODO: might not be correct. Was : Exit For } } }
public static void ExecuteSaveFontTexture() { Texture2D tex = Selection.activeObject as Texture2D; if (tex == null) { EditorUtility.DisplayDialog("No texture selected", "Please select a texture", "Cancel"); return; } if (tex.format != TextureFormat.Alpha8) { EditorUtility.DisplayDialog("Wrong format", "Texture must be in uncompressed Alpha8 format", "Cancel"); return; } // Convert Alpha8 texture to ARGB32 texture so it can be saved as a PNG var texPixels = tex.GetPixels(); var tex2 = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, false); tex2.SetPixels(texPixels); // Save texture (WriteAllBytes is not used here in order to keep compatibility with Unity iPhone) var texBytes = tex2.EncodeToPNG(); var fileName = EditorUtility.SaveFilePanel("Save font texture", "", "font Texture", "png"); if (fileName.Length > 0) { FileStream f = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter b = new BinaryWriter(f); for (var i = 0; i < texBytes.Length; i++) b.Write(texBytes[i]); b.Close(); } GameObject.DestroyImmediate(tex2); }
// read the BLOB into file "cs-parser2.cs" public static void ReadBlob (OracleConnection connection) { if (File.Exists(outfilename) == true) { Console.WriteLine("Filename already exists: " + outfilename); return; } OracleCommand rcmd = connection.CreateCommand (); rcmd.CommandText = "SELECT BLOB_COLUMN FROM BLOBTEST"; OracleDataReader reader2 = rcmd.ExecuteReader (); if (!reader2.Read ()) Console.WriteLine ("ERROR: RECORD NOT FOUND"); Console.WriteLine (" TESTING OracleLob OBJECT 2..."); OracleLob lob2 = reader2.GetOracleLob (0); Console.WriteLine (" LENGTH: {0}", lob2.Length); Console.WriteLine (" CHUNK SIZE: {0}", lob2.ChunkSize); byte[] lobvalue = (byte[]) lob2.Value; if (ByteArrayCompare(bytes1, lobvalue) == true) Console.WriteLine("bytes1 and bytes2 are equal: good"); else Console.WriteLine("bytes1 and bytes2 are not equal: bad"); FileStream fs = new FileStream(outfilename, FileMode.CreateNew); BinaryWriter w = new BinaryWriter(fs); w.Write(lobvalue); w.Close(); fs.Close(); lob2.Close (); reader2.Close (); }
public void RpcTellClientTime(int current_count) { current_count = 60 * 5 - current_count; int min = current_count / 60; int sec = current_count % 60; int ten_sec = sec / 10; int one_sec = sec % 10; score_.text = "ClearTime:" + min.ToString() + ":" + ten_sec.ToString() + one_sec.ToString(); score_.gameObject.SetActive(true); hi_score_text_.gameObject.SetActive(true); if (current_count > hi_score_) return; if (is_director_) return; is_director_ = true; { var path = Application.dataPath + "/" + "ranki.txt"; FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryWriter writer = new BinaryWriter(fs); if (writer != null) { writer.Write(current_count); writer.Close(); } } StartCoroutine(ChangeColor()); }
// Update is called once per frame void Update () { if (OpenFileChoose) { FolderPath = EditorUtility.SaveFolderPanel("フォルダ選択", " ", " "); OpenFileChoose = false; } if (FolderPath != null) { if (Savestart) { this.writer = new BinaryWriter(File.OpenWrite(FolderPath + @"\" + filename)); thread = new Thread(new ThreadStart(Save)); thread.Start(); Savestart = false; } } }
public Connection(Socket connection) { this.connection = connection; connection.NoDelay = true; writer = new BinaryWriter(new NetworkStream(connection)); reader = new BinaryReader(new NetworkStream(connection)); }
public override void Write(BinaryWriter file) => base.Write(file);
public override void Write(BinaryWriter writer, object obj) { writer.Write((bool)obj); }
public override void Write(BinaryWriter writer, object obj) { writer.Write((string)obj); }
public override void Write(BinaryWriter writer, object obj) { writer.Write(((DateTime)obj).Ticks); }
public override void Write(BinaryWriter writer, object obj) { writer.Write(((Color)obj).ToArgb()); }
/// <summary> /// Writes this object to a stream /// </summary> /// <param name="Writer">the output stream</param> public override void Serialize(BinaryWriter Writer) { base.Serialize(Writer); Writer.Write(_extraData); }
internal void Serialize(BinaryWriter writer) { byte[] sid_data = Sid.ToArray(); if (Type == AceType.AllowedCompound) { MemoryStream stm = new MemoryStream(); BinaryWriter sidwriter = new BinaryWriter(stm); sidwriter.Write((int)CompoundAceType.Impersonation); sidwriter.Write(ServerSid.ToArray()); sidwriter.Write(sid_data); sid_data = stm.ToArray(); } int total_length = 4 + 4 + sid_data.Length; if (ApplicationData != null) { total_length += ApplicationData.Length; } // Add a round up to 4 byte alignment. int padding = 4 - (total_length % 4); if (padding == 4) { padding = 0; } total_length += padding; ObjectAceFlags flags = ObjectAceFlags.None; if (IsObjectAce) { // For Flags total_length += 4; if (ObjectType.HasValue) { total_length += 16; flags |= ObjectAceFlags.ObjectTypePresent; } if (InheritedObjectType.HasValue) { total_length += 16; flags |= ObjectAceFlags.InheritedObjectTypePresent; } } if (total_length > ushort.MaxValue) { throw new ArgumentOutOfRangeException("Total ACE length greater than maximum"); } writer.Write((byte)Type); writer.Write(MapFromFlags(Type, Flags)); writer.Write((ushort)total_length); writer.Write(Mask.Access); if (IsObjectAce) { writer.Write((uint)flags); if (ObjectType.HasValue) { writer.Write(ObjectType.Value.ToByteArray()); } if (InheritedObjectType.HasValue) { writer.Write(InheritedObjectType.Value.ToByteArray()); } } writer.Write(sid_data); writer.Write(ApplicationData ?? new byte[0]); if (padding != 0) { writer.Write(new byte[padding]); } }
protected override void WriteItem(BinaryWriter writer, W3dShader item) { item.WriteTo(writer); }
public static void Write(this BinaryWriter br, Vector3 v) { br.Write(v.X); br.Write(v.Y); br.Write(v.Z); }
public override void Serialize(BinaryWriter writer) { base.Serialize(writer); writer.Write(Transactions); }
public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); bw.Write(chat_id); }
public static void Connect() { form.Log("connecting...", Color.DarkGray); string serverIP = form.textBoxServerIP.Text; int serverPort = (int)form.numericUpDownPort.Value; try { tcpToServer = new TcpClient() { NoDelay = true }; tcpToServer.Connect(serverIP, serverPort); udpToServer = new UdpClient(tcpToServer.Client.LocalEndPoint as IPEndPoint); udpToServer.Connect(serverIP, serverPort); } catch (SocketException) {//connection refused Close(); form.Log("failed\n", Color.Red); form.EnableButtons(); return; } form.Log("connected\n", Color.Green); Stream stream = tcpToServer.GetStream(); swriter = new BinaryWriter(stream); sreader = new BinaryReader(stream); form.Log("checking version...", Color.DarkGray); swriter.Write(Database.bridgeVersion); if (!sreader.ReadBoolean()) { form.Log("mismatch\n", Color.Red); form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick)); return; } form.Log("match\n", Color.Green); form.Log("logging in...", Color.DarkGray); swriter.Write(form.textBoxUsername.Text); swriter.Write(form.textBoxPassword.Text); swriter.Write(NetworkInterface.GetAllNetworkInterfaces().Where(nic => nic.OperationalStatus == OperationalStatus.Up).Select(nic => nic.GetPhysicalAddress().ToString()).FirstOrDefault()); switch ((AuthResponse)sreader.ReadByte()) { case AuthResponse.success: if (sreader.ReadBoolean()) //if banned { MessageBox.Show(sreader.ReadString()); //ban message form.Log("you are banned\n", Color.Red); goto default; } break; case AuthResponse.unknownUser: form.Log("unknown username\n", Color.Red); goto default; case AuthResponse.wrongPassword: form.Log("wrong password\n", Color.Red); goto default; default: form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick)); return; } form.Log("success\n", Color.Green); connected = true; swriter.Write((byte)0);//request query new Thread(new ThreadStart(ListenFromServerTCP)).Start(); new Thread(new ThreadStart(ListenFromServerUDP)).Start(); ListenFromClientTCP(); }
public static void Save(World world, string filename, bool resetTime = false) { try { OnProgressChanged(world, new ProgressChangedEventArgs(0, "Validating World...")); world.Validate(); } catch (ArgumentOutOfRangeException err) { string msg = "There is a problem in your world.\r\n" + $"{err.ParamName}\r\nThis world will not open in Terraria\r\n" + "Would you like to save anyways??\r\n"; if (MessageBox.Show(msg, "World Error", MessageBoxButton.YesNo, MessageBoxImage.Error) != MessageBoxResult.Yes) { return; } } lock (_fileLock) { if (resetTime) { OnProgressChanged(world, new ProgressChangedEventArgs(0, "Resetting Time...")); world.ResetTime(); } if (filename == null) { return; } string temp = filename + ".tmp"; using (var fs = new FileStream(temp, FileMode.Create)) { using (var bw = new BinaryWriter(fs)) { if (world.Version > 87) { SaveV2(world, bw); } else { SaveV1(world, bw); } bw.Close(); fs.Close(); // make a backup of current file if it exists if (File.Exists(filename)) { string backup = filename + "." + DateTime.Now.ToString("yyyyMMddHHmmss") + ".TEdit"; File.Copy(filename, backup, true); } // replace actual file with temp save file File.Copy(temp, filename, true); // delete temp save file File.Delete(temp); OnProgressChanged(null, new ProgressChangedEventArgs(0, "World Save Complete.")); } } world._lastSave = File.GetLastWriteTimeUtc(filename); } }
public static void WriteString(this BinaryWriter bw, string s) { bw.Write(s.ToCharArray()); }
static void Main() { int i, j; int retcode; int[] dev = new int[MAXDEVNUM]; int found = 0; int NumChannels = 0; StringBuilder LibVer = new StringBuilder(8); StringBuilder Serial = new StringBuilder(8); StringBuilder Errstr = new StringBuilder(40); StringBuilder Model = new StringBuilder(16); StringBuilder Partno = new StringBuilder(8); StringBuilder Version = new StringBuilder(16); StringBuilder Wtext = new StringBuilder(16384); int Mode = MODE_T2; //you can change this, adjust other settings accordingly! int Binning = 0; //you can change this, meaningful only in T3 mode, observe limits int Offset = 0; //you can change this, meaningful only in T3 mode, observe limits int Tacq = 10000; //Measurement time in millisec, you can change this, observe limits int SyncDivider = 1; //you can change this, usually 1 in T2 mode //TimeHarp 260 P only int SyncCFDZeroCross = -10; //you can change this, observe limits int SyncCFDLevel = -50; //you can change this, observe limits int InputCFDZeroCross = -10; //you can change this, observe limits int InputCFDLevel = -50; //you can change this, observe limits //TimeHarp 260 N only int SyncTrigEdge = 0; //you can change this, observe limits int SyncTrigLevel = -50; //you can change this, observe limits int InputTrigEdge = 0; //you can change this, observe limits int InputTrigLevel = -50; //you can change this, observe limits double Resolution = 0; int Syncrate = 0; int Countrate = 0; int ctcstatus = 0; int flags = 0; long Progress = 0; int nRecords = 0; int warnings = 0; uint[] buffer = new uint[TTREADMAX]; FileStream fs = null; BinaryWriter bw = null; Console.WriteLine("TimeHarp 260 TH260Lib Demo Application M. Wahl, PicoQuant GmbH, 2017"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); retcode = TH260_GetLibraryVersion(LibVer); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetLibraryVersion error {0}. Aborted.", Errstr); goto ex; } Console.WriteLine("TH260Lib Version is " + LibVer); if (LibVer.ToString() != TargetLibVersion) { Console.WriteLine("This program requires TH260Lib v." + TargetLibVersion); goto ex; } try { fs = File.Create("tttrmode.out"); bw = new BinaryWriter(fs); } catch (Exception) { Console.WriteLine("Error creating file"); goto ex; } Console.WriteLine("Searching for TimeHarp 260 devices..."); Console.WriteLine("Devidx Status"); for (i = 0; i < MAXDEVNUM; i++) { retcode = TH260_OpenDevice(i, Serial); if (retcode == 0) //Grab any HydraHarp we can open { Console.WriteLine(" {0} S/N {1}", i, Serial); dev[found] = i; //keep index to devices we want to use found++; } else { if (retcode == TH260_ERROR_DEVICE_OPEN_FAIL) { Console.WriteLine(" {0} no device", i); } else { TH260_GetErrorString(Errstr, retcode); Console.WriteLine(" {0} S/N {1}", i, Errstr); } } } //In this demo we will use the first device we find, i.e. dev[0]. //You can also use multiple devices in parallel. //You can also check for specific serial numbers, so that you always know //which physical device you are talking to. if (found < 1) { Console.WriteLine("No device available."); goto ex; } Console.WriteLine("Using device {0}", dev[0]); Console.WriteLine("Initializing the device..."); retcode = TH260_Initialize(dev[0], MODE_T2); //Histo mode if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_Initialize error {0}. Aborted.", Errstr); goto ex; } retcode = TH260_GetHardwareInfo(dev[0], Model, Partno, Version); //this is only for information if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetHardwareInfo error {0}. Aborted.", Errstr); goto ex; } else { Console.WriteLine("Found Model {0} Part no {1} Version {2}", Model, Partno, Version); } retcode = TH260_GetNumOfInputChannels(dev[0], ref NumChannels); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetNumOfInputChannels error {0}. Aborted.", Errstr); goto ex; } else { Console.WriteLine("Device has {0} input channels.", NumChannels); } retcode = TH260_SetSyncDiv(dev[0], SyncDivider); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetSyncDiv Error {0}. Aborted.", Errstr); goto ex; } if (Model.ToString() == "TimeHarp 260 P") { retcode = TH260_SetSyncCFD(dev[0], SyncCFDLevel, SyncCFDZeroCross); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetSyncCFD Error {0}. Aborted.", Errstr); goto ex; } for (i = 0; i < NumChannels; i++) // we use the same input settings for all channels { retcode = TH260_SetInputCFD(dev[0], i, InputCFDLevel, InputCFDZeroCross); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetInputCFD Error {0}. Aborted.", Errstr); goto ex; } } } else if (Model.ToString() == "TimeHarp 260 N") { retcode = TH260_SetSyncEdgeTrg(dev[0], SyncTrigLevel, SyncTrigEdge); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetSyncEdgeTrg Error {0}. Aborted.", Errstr); goto ex; } for (i = 0; i < NumChannels; i++) // we use the same input settings for all channels { retcode = TH260_SetInputEdgeTrg(dev[0], i, InputTrigLevel, InputTrigEdge); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetInputEdgeTrg Error {0}. Aborted.", Errstr); goto ex; } } } else { Console.WriteLine("Unknown hardware model: {0}. Aborted.", Model); goto ex; } retcode = TH260_SetSyncChannelOffset(dev[0], 0); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetSyncChannelOffset Error {0}. Aborted.", Errstr); goto ex; } for (i = 0; i < NumChannels; i++) // we use the same input settings for all channels { retcode = TH260_SetInputChannelOffset(dev[0], i, 0); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetInputChannelOffset Error {0}. Aborted.", Errstr); goto ex; } retcode = TH260_SetInputChannelEnable(dev[0], i, 1); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetInputChannelEnable Error {0}. Aborted.", Errstr); goto ex; } } if (Mode != MODE_T2) { retcode = TH260_SetBinning(dev[0], Binning); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetBinning Error {0}. Aborted.", Errstr); goto ex; } retcode = TH260_SetOffset(dev[0], Offset); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_SetOffset Error {0}. Aborted.", Errstr); goto ex; } } retcode = TH260_GetResolution(dev[0], ref Resolution); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetResolution Error {0}. Aborted.", Errstr); goto ex; } Console.WriteLine("Resolution is {0} ps", Resolution); // After Init allow 150 ms for valid count rate readings // Subsequently you get new values after every 100ms System.Threading.Thread.Sleep(150); retcode = TH260_GetSyncRate(dev[0], ref Syncrate); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetSyncRate Error {0}. Aborted.", Errstr); goto ex; } Console.WriteLine("Syncrate = {0}/s", Syncrate); for (i = 0; i < NumChannels; i++) // for all channels { retcode = TH260_GetCountRate(dev[0], i, ref Countrate); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetCountRate Error {0}. Aborted.", Errstr); goto ex; } Console.WriteLine("Countrate[{0}] = {1}/s", i, Countrate); } Console.WriteLine(); //After getting the count rates you can check for warnings retcode = TH260_GetWarnings(dev[0], ref warnings); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_GetWarnings Error {0}. Aborted.", Errstr); goto ex; } if (warnings != 0) { TH260_GetWarningsText(dev[0], Wtext, warnings); Console.WriteLine("{0}", Wtext); } Progress = 0; Console.Write("Progress: {0,12}", Progress); retcode = TH260_StartMeas(dev[0], Tacq); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine(); Console.WriteLine("TH260_StartMeas Error {0}. Aborted.", Errstr); goto ex; } while (true) { retcode = TH260_GetFlags(dev[0], ref flags); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine(); Console.WriteLine("TH260_GetFlags Error {0}. Aborted.", Errstr); goto ex; } if ((flags & FLAG_FIFOFULL) != 0) { Console.WriteLine(); Console.WriteLine("FiFo Overrun!"); goto stoptttr; } retcode = TH260_ReadFiFo(dev[0], buffer, TTREADMAX, ref nRecords); //may return less! if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine(); Console.WriteLine("TH260_GetFlags Error {0}. Aborted.", Errstr); goto ex; } if (nRecords > 0) { for (j = 0; j < nRecords; j++) { bw.Write(buffer[j]); } Progress += nRecords; Console.Write("\b\b\b\b\b\b\b\b\b\b\b\b{0,12}", Progress); } else { retcode = TH260_CTCStatus(dev[0], ref ctcstatus); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine(); Console.WriteLine("TH260_CTCStatus Error {0}. Aborted.", Errstr); goto ex; } if (ctcstatus > 0) { Console.WriteLine(); Console.WriteLine("Done"); goto stoptttr; } } //within this loop you can also read the count rates if needed. } stoptttr: Console.WriteLine(); retcode = TH260_StopMeas(dev[0]); if (retcode < 0) { TH260_GetErrorString(Errstr, retcode); Console.WriteLine("TH260_StopMeas Error {0}. Aborted.", Errstr); goto ex; } bw.Close(); fs.Close(); ex: for (i = 0; i < MAXDEVNUM; i++) //no harm to close all { TH260_CloseDevice(i); } Console.WriteLine("press RETURN to exit"); Console.ReadLine(); }
public void Write(BinaryWriter w) { w.Write(city1.ToString() + " - " + city2.ToString()); }
public override void Serialize(SubsetNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); WriteObjectNames(node.OriginalColumnNames, writer); WriteObjectNames(node.AliasColumnNames, writer); }
public override void WriteExtraData(BinaryWriter writer) { writer.Write((short)this.npc); }
public override void Serialize(SingleRowTableNode node, BinaryWriter writer) { }
public override void Serialize(LimitNode obj, BinaryWriter writer) { WriteChildNode(writer, obj.Child); writer.Write(obj.Offset); writer.Write(obj.Count); }
public override void Serialize(NaturalJoinNode node, BinaryWriter writer) { WriteChildNode(writer, node.Left); WriteChildNode(writer, node.Right); }
public override void Serialize(SortNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); WriteObjectNames(node.ColumnNames, writer); WriteArray(node.Ascending, writer, (b, binaryWriter) => binaryWriter.Write(b)); }
public override void Serialize(LogicalUnionNode node, BinaryWriter writer) { WriteChildNode(writer, node.Left); WriteChildNode(writer, node.Right); }
public override void Serialize(SimplePatternSelectNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); SqlExpression.Serialize(node.Expression, writer); }
public override void Serialize(ExhaustiveSelectNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); SqlExpression.Serialize(node.Expression, writer); }
public override void Serialize(MarkerNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); writer.Write(node.MarkName); }
public override void Serialize(CreateFunctionsNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); WriteExpressions(node.Functions, writer); WriteStrings(node.Names, writer); }
public override void Serialize(FetchViewNode node, BinaryWriter writer) { ObjectName.Serialize(node.ViewName, writer); ObjectName.Serialize(node.AliasName, writer); }
public override void Serialize(CachePointNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); writer.Write(node.Id); }
public override void Serialize(DistinctNode node, BinaryWriter writer) { WriteChildNode(writer, node.Child); WriteObjectNames(node.ColumnNames, writer); }