static object Deserialize(string filename,IFormatter formatter) { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); object obj = formatter.Deserialize(fs); fs.Close(); return obj; }
/// <summary> /// Clone a object with via Serializing/Deserializing /// using a implementation of IFormatter. /// <seealso cref="IFormatter"/> /// </summary> /// <param name="obj">Object to clone</param> /// <param name="formatter">IFormatter implementation in order to Serialize/Deserialize</param> /// <returns>Clone object</returns> public static object Clone(object obj, IFormatter formatter) { using (MemoryStream buffer = new MemoryStream()) { formatter.Serialize(buffer, obj); buffer.Position = 0; return formatter.Deserialize(buffer); } }
void Driver (IFormatter formatter, A a) { MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, a); stream.Position = 0; a.CheckSerializationStatus (); a = (A) formatter.Deserialize (stream); a.CheckDeserializationStatus (); }
public static object Deserialize (string s, IFormatter b) { if (s == null || s == string.Empty) return null; using (MemoryStream ms = new MemoryStream ()) { byte [] ba = HttpUtility.UrlDecodeToBytes (s); ms.Write (ba, 0, ba.Length); ms.Position = 0; try { return b.Deserialize (ms); } catch (Exception e) { throw; } } }
public MmTaskSolver(byte[] problemData) : base(problemData) { _formatter = new BinaryFormatter(); try { using (var memoryStream = new MemoryStream(problemData)) { _minMaxProblem = (MmProblem) _formatter.Deserialize(memoryStream); } State = TaskSolverState.OK; } catch (Exception) { State = TaskSolverState.Error; } }
private static Object[] obj_deserialize_int(byte [] in_bytes, Int32 asem_type, String assem, String atype, IFormatter bf) { Object [] ret = new Object[2]; System.IO.MemoryStream mem_strim = new System.IO.MemoryStream(); Type type = new VInvoke().get_type(asem_type, assem, atype); mem_strim.Seek(0, SeekOrigin.Begin); mem_strim.Write(in_bytes, 0, (int)in_bytes.Length); mem_strim.Seek(0, SeekOrigin.Begin); Object org_obj = bf.Deserialize(mem_strim); if (!(type.IsInstanceOfType(org_obj) || (org_obj != null && type == org_obj.GetType()))) { throw new Exception("The deserialized object is not an instance of " + type.FullName); } return(res_to_ptr(org_obj)); }
private void Run() { if (_disposed) { throw new ObjectDisposedException(""); } MessageEventArgs messaggio = null; try { while (!_shouldStop) { messaggio = (MessageEventArgs)_formatter.Deserialize(_stream); if (messaggio != null && _syncContext != null) { _syncContext.Post(SyncOutput, messaggio); } messaggio = null; } _shouldStop = false; } catch (ThreadAbortException) { if (_notifyDispose) { _syncContext.Post(SyncOutput, new SocketClosedMessageEventArgs(_remoteAddress)); } _remoteAddress = null; } catch (Exception e) { if (!_disposed && _syncContext != null) { if (_notifyDispose) { _syncContext.Post(SyncOutput, new SocketErrorMessageEventArgs(_remoteAddress)); } } } }
public MainEntryForm() { InitializeComponent(); Stream src = null; bool configLoaded = false; try { src = new FileStream("config.bin", FileMode.Open, FileAccess.Read); IFormatter form = (IFormatter) new BinaryFormatter(); m_config = form.Deserialize(src) as Configuration; src.Close(); excelFileLocation.Text = m_config.excelLocation; userName.Text = m_config.name; configLoaded = true; datePicker.Value = DateTime.Today; if (File.Exists(excelFileLocation.Text)) { FileInfo fi = new FileInfo(excelFileLocation.Text); m_outputDirectory = fi.Directory.ToString(); } } catch (FileNotFoundException) { } catch (SerializationException) { } catch (Exception ex) { MessageBox.Show("Oops! There was a problem loading config.bin, sorry!\n" + ex.Message); } finally { if (src != null) { src.Close(); } } if (configLoaded) { LoadSettingsFromExcel(); //m_outputExcelFile = new ExcelFile() } }
public virtual void Run() { while (_connected) { try { var request = (IRequest)_formatter.Deserialize(_stream); var response = HandleRequest(request); if (response != null) { SendResponse(response); } if (response is ErrorResponse && request is LoginRequest) { _connected = false; } } catch (Exception e) { if (!_connected) { break; } Console.WriteLine(e.StackTrace); } try { Thread.Sleep(10); } catch (Exception e) { if (!_connected) { break; } Console.WriteLine(e.StackTrace); } } }
private static T _readSetting <T>(string filename) { filename = filename.ToLower().Replace('/', '.'); if (File.Exists(filename)) { try { object obj = null; FileStream stream = null; try { stream = new FileStream(filename, FileMode.Open, FileAccess.Read); obj = _formatter.Deserialize(stream); } catch { } finally { if (stream != null) { stream.Dispose(); } } if (obj != null) { return((T)obj); } } catch { //Can't convert Setting. } } return(default(T)); }
private static void ReadCommand(Stream networkStream, IFormatter formatter, out int stageId, out string deserializerMode, out string serializerMode, out CSharpWorkerFunc workerFunc) { stageId = ReadDiagnosticsInfo(networkStream); deserializerMode = SerDe.ReadString(networkStream); logger.LogDebug("Deserializer mode: " + deserializerMode); serializerMode = SerDe.ReadString(networkStream); logger.LogDebug("Serializer mode: " + serializerMode); string runMode = SerDe.ReadString(networkStream); if ("R".Equals(runMode, StringComparison.InvariantCultureIgnoreCase)) { var compilationDumpDir = SerDe.ReadString(networkStream); if (Directory.Exists(compilationDumpDir)) { assemblyHandler.LoadAssemblies(Directory.GetFiles(compilationDumpDir, "ReplCompilation.*", SearchOption.TopDirectoryOnly)); } else { logger.LogError("Directory " + compilationDumpDir + " dose not exist."); } } byte[] command = SerDe.ReadBytes(networkStream); logger.LogDebug("command bytes read: " + command.Length); var stream = new MemoryStream(command); workerFunc = (CSharpWorkerFunc)formatter.Deserialize(stream); logger.LogDebug( "------------------------ Printing stack trace of workerFunc for ** debugging ** ------------------------------"); logger.LogDebug(workerFunc.StackTrace); logger.LogDebug( "--------------------------------------------------------------------------------------------------------------"); }
public virtual void Run() { while (_connected) { try { if (!stream.DataAvailable) { continue; } object request = formatter.Deserialize(stream); object response = HandleRequest((Request)request); if (response != null) { SendResponse((IResponse)response); } } catch (Exception e) { Console.WriteLine(e.Message); } try { Thread.Sleep(1000); } catch (Exception e) { Console.WriteLine(e.Message); } } try { stream.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine("Error " + e); } }
private void StartReceive() { while (m_socket.Connected) { //Bitmap buffer = (Bitmap)formatter.Deserialize(m_networkStream); byte[] buffer = (byte[])formatter.Deserialize(m_networkStream); Byte[] buffer = new Byte[4]; m_socket.Receive(buffer); int size = BitConverter.ToInt32(buffer, 0); buffer = new Byte[size]; m_socket.Receive(buffer); ms = new MemoryStream(buffer); MessageReceivedEventArgs messageArgs; //Read the command's Type. CommandType cmdType = (CommandType)(ReadNumber(4)); switch (cmdType) { case CommandType.ClientLogin: //Read ClientName size size = ReadNumber(4); //Read ClientName m_clientName = ReadString(size); ClientLogin(this, EventArgs.Empty); break; case CommandType.Message: //Read message type. MessageType msgType = (MessageType)(ReadNumber(4)); if (msgType == MessageType.Broadcast) { messageArgs = new MessageReceivedEventArgs(msgType, BitConverter.GetBytes(size).Concat(buffer).ToArray()); OnMessageReceived(messageArgs); } break; } } }
public virtual T ReadBinary <T>(string filePath) { T item = default(T); FileInfo fileInfo = new FileInfo(filePath); if (!fileInfo.Exists || fileInfo.Length == 0) { return(item); } IFormatter formatter = GetFormatter(); using (FileStream fileStream = new FileStream(fileInfo.FullName, FileMode.Open , FileAccess.Read, FileShare.ReadWrite)) { item = (T)formatter.Deserialize(fileStream); } return(item); }
/// <sumary> /// Loads a saved game from a file stream /// </sumary> /// <param name="file"> /// The source stream /// </param> public void loadBoard(Stream file) { try { IFormatter formatter = (IFormatter) new BinaryFormatter(); // Clear the selected moves, just in case selected.clear(); Invalidate(); reset(); // Deserializes the object graph to stream board = (CheckersBoard)formatter.Deserialize(file); // Create a new computer instace for this board computer = new Computer(board); } catch { MessageBox.Show("Error while loading", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public UnpackerState CreateMessageData(ref IMessageData message, Packet packet) { if (!packet.IsReady) { return(UnpackerState.NotReady); } message = null; using (MemoryStream stream = new MemoryStream(packet.GetData())) { try { message = formatter.Deserialize(stream) as IMessageData; } catch (Exception ex) { message = null; return(UnpackerState.NotParse); } } return(UnpackerState.Ok); }
public List <MPersonaje> ObtenerPersonaje() { List <MPersonaje> pjs = new List <MPersonaje>(); using (Stream fs = new FileStream("./per.dat", FileMode.OpenOrCreate, FileAccess.Read)) { try { pjs = (List <MPersonaje>)formatter.Deserialize(fs); foreach (var pj in pjs) { Console.WriteLine(pj.Nombre); } } catch (Exception) { Console.WriteLine("Error al serializar. Archivo vacío"); } } return(pjs); }
/// <summary> /// Tries to deserialise VMDPID from temp file into _vmdpid /// </summary> /// <returns>Success</returns> private static bool GetPidFromDisk() { if (!File.Exists(TempFile) || new FileInfo(TempFile).Length == 0) { return(false); } using (var fs = File.OpenRead(TempFile)) { try { _vmdpid = (VMDPID)Formatter.Deserialize(fs); } catch (Exception) { return(false); } } return(true); }
public static bool Load(out Session.Data sessionData) { EnsureDirectory(); try { using (Stream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read)) { sessionData = (Session.Data)formatter.Deserialize(stream); stream.Close(); return(true); } } catch (IOException e) { sessionData = null; return(false); } }
/// <inheritdoc/> protected internal override (bool, object) TryCopy(object source, DuplicatorChainer duplicator) { if (source == null) { return(true, null); } if (source is ISerializable && source.GetType().IsSerializable) { using (Stream stream = new MemoryStream()) { _Serializer.Serialize(stream, source); _ = stream.Seek(0, SeekOrigin.Begin); return(true, _Serializer.Deserialize(stream)); } } else { return(false, null); } }
public async Task <T> LoadAsync() { try { string raw = await localStorage.GetItemAsStringAsync(key); log.Debug($"Loaded '{raw}'."); if (String.IsNullOrEmpty(raw)) { return(null); } T model = formatter.Deserialize <T>(raw); return(model); } catch (Exception e) { log.Fatal(e); return(null); } }
public static bool Load(Chunk chunk) { saveFile = Path.Combine(SaveLocation, "chunks", FileName(chunk.pos)); if (!File.Exists(saveFile)) { return(false); } using (fileStream = new FileStream(saveFile, FileMode.Open)) { save = (Save)formatter.Deserialize(fileStream); foreach (var block in save.blocks) { chunk._blocks[Chunk.BlockIndex(block.Key.x, block.Key.y, block.Key.z)] = block.Value; } } return(true); }
public async Task <T> LoadAsync() { try { string raw = await jsRuntime.InvokeAsync <string>("window.localStorage.getItem", key); log.Debug($"Loaded '{raw}'."); if (String.IsNullOrEmpty(raw)) { return(null); } T model = formatter.Deserialize <T>(raw); return(model); } catch (Exception e) { log.Fatal(e); return(null); } }
public virtual void run() { while (connected) { try { object request = formatter.Deserialize(stream); object response = handleRequest((IRequest)request); if (response != null) { sendResponse((IResponse)response); } } catch (Exception e) { connected = false; Console.WriteLine(e.StackTrace); } try { Thread.Sleep(1000); } catch (Exception e) { connected = false; Console.WriteLine(e.StackTrace); } } try { stream.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine(e.StackTrace); } }
private static Type ParseOutHeader <T>(T msg, byte[] messageIDBytes, IFormatter formatter, out byte[] msgByteArray, out byte[] resultByteArray, out uint sizeOfMessage, out uint sizeOfResult) where T : IActorMessage { // <verstion-short> (always Zero for this type of serializedMessage) // 16byte.message.guid // <size.of.type.string.in.Bytes-short> // <bytes.of.type.string-bytearray> // <size.of.message-uint> // <bytes.of.message-bytearray> // <size.of.result-uint> // <bytes.of.result-bytearray> // <status.flags-uint> byte[] typeByteArray = null; uint flags = 0; uint serializationIndex = sizeof(ushort); //skip the version number byte[] seralizedMsg = (byte[])msg.Message; Array.Copy(seralizedMsg, serializationIndex, messageIDBytes, 0, 16); serializationIndex += (uint)messageIDBytes.Length; Guid messageID = new Guid(messageIDBytes); uint sizeOfType = BitConverter.ToUInt32(seralizedMsg, (int)serializationIndex); serializationIndex += sizeof(uint); typeByteArray = new byte[sizeOfType]; Array.Copy(seralizedMsg, serializationIndex, typeByteArray, 0, sizeOfType); serializationIndex += sizeOfType; sizeOfMessage = BitConverter.ToUInt32(seralizedMsg, (int)serializationIndex); serializationIndex += sizeof(uint); msgByteArray = new byte[sizeOfMessage]; Array.Copy(seralizedMsg, serializationIndex, msgByteArray, 0, sizeOfMessage); serializationIndex += sizeOfMessage; sizeOfResult = BitConverter.ToUInt32(seralizedMsg, (int)serializationIndex); serializationIndex += sizeof(uint); resultByteArray = new byte[sizeOfResult]; Array.Copy(seralizedMsg, serializationIndex, resultByteArray, 0, sizeOfResult); serializationIndex += sizeOfResult; flags = BitConverter.ToUInt32(seralizedMsg, (int)serializationIndex); serializationIndex += sizeof(uint); // I now know the type of the message I need to instantiate it. return(Type.GetType((string)formatter.Deserialize(new MemoryStream(typeByteArray)))); }
public void Run() { LOGGER.Info("running worker"); while (connected) { try { Request request = (Request)formatter.Deserialize(stream); LOGGER.InfoFormat("received request {0}", request); Response response = HandleRequest(request); LOGGER.InfoFormat("response for request {0}", response); if (response != null) { LOGGER.InfoFormat("sending response to client {0}", response); SendResponse(response); } } catch (Exception e) { if (connected) { LOGGER.Warn("running worker stopped with exception {0}", e); LOGGER.Warn(e.StackTrace); } break; } } LOGGER.Info("closing connection"); try { stream.Close(); connection.Close(); } catch (Exception e) { LOGGER.Warn("Error closing connection" + e); LOGGER.Warn(e.StackTrace); } }
public virtual void Run() { logger.Debug("Running client worker..."); while (connected) { try { object request = formatter.Deserialize(stream); logger.Debug("Receipt request " + request + " from client" + connection); object response = HandleRequest((Request)request); if (response != null) { SendResponse((Response)response); } } catch (Exception e) { logger.Error(e.Message + '\n' + e.StackTrace); } try { Thread.Sleep(1000); } catch (Exception e) { logger.Error(e.Message + '\n' + e.StackTrace); } } try { stream.Close(); connection.Close(); } catch (Exception e) { Console.WriteLine("Error " + e); } }
private void Load() { string[] objectFiles = Directory.GetFiles(this.directory, string.Format(objectFileMask, "*")); for (int i = 0; i < objectFiles.Length; i++) { try { using (FileStream file = File.OpenRead(objectFiles[i])) { BaseEntity entity = (BaseEntity)formatter.Deserialize(file); Trace.TraceInformation("Loading object {0} of type {1}.", entity.EntityKey, entity); this.InternalSet(entity); } } catch (Exception e) { Trace.TraceError("Cannot load the file {0}: {1}", objectFiles[i], e.Message); File.Delete(objectFiles[i]); } } }
public static T Clone <T>(this T source) { if (Attribute.GetCustomAttribute(typeof(T), typeof(ProtoBuf.ProtoContractAttribute)) == null) { throw new ArgumentException("Type has no ProtoContract!", "source"); } if (Object.ReferenceEquals(source, null)) { return(default(T)); } IFormatter formatter = ProtoBuf.Serializer.CreateFormatter <T>(); using (Stream stream = new MemoryStream()) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return((T)formatter.Deserialize(stream)); } }
void loadPlayerData() { if (File.Exists(_dataPath)) { IFormatter formatter = getDataFormatter(); FileStream file = File.Open(_dataPath, FileMode.Open); PlayerData data = formatter.Deserialize(file) as PlayerData; playerExist = data.playerExist; gameMusicVolume = data.gameMusicVolume; gameSoundEffectsVolume = data.gameSoundEffectsVolume; playerScore = data.playerScore; endlessLevelPlayedTime = data.endlessLevelPlayedTime; completedTutorial = data.completedTutorial; showReviewSuggestion = data.showReviewSuggestion; showJoinGroupSuggestion = data.showJoinGroupSuggestion; showInviteFriendsSuggestion = data.showInviteFriendsSuggestion; notNowPressed = data.notNowPressed; logInVk = data.logInVk; logInFb = data.logInFb; inVkGameGroup = data.inVkGameGroup; inFbGameGroup = data.inFbGameGroup; selectedFairyIndex = data.selectedFairyIndex; playerFairies = data.playerFairies; slowBonusCount = data.slowBonusCount; damageBonusCount = data.damageBonusCount; blockAdsInAppBought = data.blockAdsInAppBought; enableSoundsEffects = data.enableSoundsEffects; enableBackgroundSound = data.enableBackgroundSound; playerUsePromocode = data.playerUsePromocode; if (playerFairies == null) { playerFairies = new List <int>(); } file.Close(); } }
private static T Deserialize <T>(Stream stream, IFormatter formatter, string messageFormat, object[] messageArgs, GallioFunc <T> originalValueProvider) { if (formatter == null) { throw new ArgumentNullException("formatter"); } T deserializedValue = default(T); AssertionHelper.Verify(delegate { if (stream == null) { return(new AssertionFailureBuilder("Could not deserialize the value because the stream is null.") .SetMessage(messageFormat, messageArgs) .ToAssertionFailure()); } try { deserializedValue = (T)formatter.Deserialize(stream); } catch (Exception ex) { var failureBuilder = new AssertionFailureBuilder("Could not deserialize the value.") .SetMessage(messageFormat, messageArgs) .AddException(ex); if (originalValueProvider != null) { failureBuilder.AddRawLabeledValue("Value", originalValueProvider()); } return(failureBuilder.ToAssertionFailure()); } return(null); }); return(deserializedValue); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { StreamReader reader = new StreamReader("networkData.txt"); string targetCompName = reader.ReadLine(); int portNum = Int32.Parse(reader.ReadLine()); BackgroundWorker worker = (BackgroundWorker)sender; TcpListener listener; System.Net.IPAddress ipAddress = System.Net.Dns.GetHostEntry(targetCompName).AddressList[0]; listener = new TcpListener(ipAddress, portNum); listener.Start(); while (true) { System.Threading.Thread.Sleep(10); TcpClient client = listener.AcceptTcpClient(); orderInfo = (OrderInfo)formatter.Deserialize(client.GetStream()); worker.ReportProgress(0); } }
/// <summary> /// Generate a unique number /// </summary> /// <returns>int: unique number</returns> private int NumberGenerator() { //Number generator. If the serialization file exists - reads the value from it. //If value = 0 then 1, otherwise simply increments it. //If the serialization file does not exist - create it and value = 1 try { streamSerializable = new FileStream("number.dat", FileMode.Open, FileAccess.Read); getNumber = (CreateUniqueNumber)formatterSerializable.Deserialize(streamSerializable); getNumber.number = (getNumber.number == 0) ? 1 : ++getNumber.number; streamSerializable.Close(); } catch (FileNotFoundException) { getNumber.number = 1; streamSerializable = new FileStream("number.dat", FileMode.Create, FileAccess.Write); formatterSerializable.Serialize(streamSerializable, getNumber); streamSerializable.Close(); } return(getNumber.number); }
public void Evaluate(int SpreadMax) { FOutStatus.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { if (FInRead[i]) { try { var file = new FileStream(FInFilename[i], FileMode.Open); FOutIntrinsics[i] = (Intrinsics)FFormatter.Deserialize(file); FOutStatus[i] = "OK"; file.Close(); } catch (Exception e) { FOutStatus[i] = e.Message; } } } }
/// <summary> /// 二进制反序列化器 /// </summary> private void BinaryDeserialize() { FileStream fileStream = File.OpenRead(filePath); try { IFormatter formatter = (IFormatter)Activator.CreateInstance (typeof(BinaryFormatter)); formatter.Context = new StreamingContext (StreamingContextStates.File | StreamingContextStates.Persistence); fileStream.Position = 0; myImageObj = (CImageInfo)formatter.Deserialize(fileStream); } finally { if (fileStream != null) { fileStream.Dispose(); fileStream = null; } } }
public static object DeserializeItem(Stream stream, IFormatter formatter) { return formatter.Deserialize(stream); }
/// <summary> /// Deserializes the object tree from the underlying stream using the given formatter. /// </summary> /// <param name="formatter">The formatter to use when deserializing the object.</param> /// <returns>The deserialized object.</returns> public virtual Object ReadObjectTree(IFormatter formatter){ stream.Seek(0, SeekOrigin.Begin); return formatter.Deserialize(stream); }
//! Load the data. public void Load(IFormatter Formatter, Stream Stream_) { m_PositionX = (int)Formatter.Deserialize(Stream_); m_PositionY = (int)Formatter.Deserialize(Stream_); m_Tiles = (he.TerrainTile[])Formatter.Deserialize(Stream_); m_Properties = (Dictionary<ushort, he.TerrainTileProperty>)Formatter.Deserialize(Stream_); // Load mesh Mesh mesh = (Mesh)Resources.Load((string)Formatter.Deserialize(Stream_), typeof(Mesh)); GetComponent<MeshFilter>().mesh = mesh; GetComponent<MeshCollider>().sharedMesh = mesh; var mesh_renderer = GetComponent<MeshRenderer>(); // Set map material int materials_length = (int)Formatter.Deserialize(Stream_); for (int i = 0; i < materials_length; ++i) mesh_renderer.sharedMaterial = Resources.Load((string)Formatter.Deserialize(Stream_), typeof(Material)) as Material; // Load all non-moveables foreach (var it in m_Properties) { if (it.Value.nonMoveable != null) { // Get tile var tile = m_Tiles[it.Key]; GameObject non_moveable_go = utils.PrefabManager.Create("Items/Barrel"); var comp = non_moveable_go.GetComponent<NonMoveableObjectComponent>(); comp.Load(Formatter, Stream_); AssociateNonMoveable(tile.x, tile.y, comp); } } }
private void LoadDiagram(Stream fs, IFormatter formatter) { Diagram diagram; SurrogateSelector selector = new SurrogateSelector(); DiagramSerialize surrogate = new DiagramSerialize(); try { selector.AddSurrogate(typeof(Diagram),new StreamingContext(StreamingContextStates.All), surrogate); //Raise the deserialize event and allow subclasses to add/change the surrogate to their own surrogate OnDeserialize(formatter,selector); formatter.SurrogateSelector = selector; formatter.Binder = Component.Instance.DefaultBinder; diagram = (Diagram) formatter.Deserialize(fs); } catch (Exception ex) { if (ex.InnerException == null) { throw ex; } else { throw ex.InnerException; } } finally { } surrogate = Serialization.Serialize.GetSurrogate(diagram,selector); if (surrogate == null) throw new Exception("A deserialization surrogate could not be found."); //Update this object using the surrogate and the diagram surrogate.UpdateObjectReferences(); SuspendEvents = true; Suspend(); //Copy settings from deserialized object DiagramSize = diagram.DiagramSize; Zoom = diagram.Zoom; ShowTooltips = diagram.ShowTooltips; CheckBounds = diagram.CheckBounds; Paged = diagram.Paged; WorkspaceColor = diagram.WorkspaceColor; //Copy all layers across Layers.Clear(); foreach (Layer layer in surrogate.Layers) { Layers.Add(layer); } Layers.CurrentLayer = surrogate.Layers.CurrentLayer; //Copy shapes and lines accross Shapes.Clear(); foreach (Shape shape in surrogate.Shapes.Values) { Shapes.Add(shape.Key,shape); } Lines.Clear(); foreach (Line line in surrogate.Lines.Values) { Lines.Add(line.Key,line); } mNavigate = new Navigation.Navigate(this); Route = new Route(); Route.Container = this; Margin = new Margin(); //##margin needs to be serialized/deserialized //Raise the deserialize complete event OnDeserializeComplete(diagram, formatter, selector); Resume(); SuspendEvents = false; Refresh(); }
public void Load(IFormatter Formatter, Stream Stream_) { m_Instance = (NonMoveableObject)Formatter.Deserialize(Stream_); }
/// <summary> /// A general-purpose function to deserialize a list from a stream /// </summary> /// <param name="stream">The stream to read the data from</param> /// <param name="formatter">The formatter to use</param> /// <param name="list">The list to deserialize</param> private static void DeserializeList(Stream stream, IFormatter formatter, IList list) { int count = (int)formatter.Deserialize(stream); for (int idx = 0; idx != count; idx++) { list.Add(formatter.Deserialize(stream)); } if (count != list.Count) { throw new Exception("List did not deserialize to correct size"); } }
private static object GetRequestObject(Stream stream, IFormatter formatter, Type type) { try { return formatter.Deserialize(stream, type); } catch (Exception) { throw new RequestException("Parse request content to object error."); } }
/// <summary> /// Recreate this tree from a serialized version. /// </summary> /// <param name="stream">the stream that contains the serialized tree.</param> /// <param name="formatter">the formatter used to desrialize the stream.</param> public void Deserialize(Stream stream, IFormatter formatter) { // Clear our tree: this.Nodes.Clear(); KTreeView temp = formatter.Deserialize(stream) as KTreeView; if (temp != null) { // copy the nodes from the temp to our tree: foreach (TreeNode node in temp.Nodes) { this.Nodes.Add(KCommon.Utils.StreamCloner.Clone(node.Clone()) as TreeNode); } } }
void Method5(Stream stream, IFormatter formatter) { Console.WriteLine("Method5 Start : Заявка на выход из группы"); stream.Position = 0; if (stream.Length > 0) { ClaimToGroup claimToGroup = (ClaimToGroup)(formatter.Deserialize(stream)); foreach (MemberOfGroup mem in MemberOfGroupManager.MembersOfGroup) { if (mem.GroupID == claimToGroup.Group.Id && mem.UserID == claimToGroup.User.UserID) { MemberOfGroupManager.MembersOfGroup.Remove(mem); break; } } string query = string.Format("delete from MemeberOfGroups where UserID={0} and GroupID={1}", claimToGroup.User.UserID, claimToGroup.Group.Id); SqlCommand command = new SqlCommand(query, DataBase.Sql); command.ExecuteNonQuery(); Action<string> action = MessageToInfoStackAdd; string messa = String.Format("{1} вышел из группы {0}", claimToGroup.Group, claimToGroup.User); infoStack.Dispatcher.Invoke(action, messa); foreach (Socket socket in dictSocketUser.Keys) { bool member = false; foreach (MemberOfGroup mem in MemberOfGroupManager.MembersOfGroup) { if (dictSocketUser[socket].UserID == mem.UserID && mem.GroupID == claimToGroup.Group.Id) { member = true; break; } } if (member) { byte[] code2 = Encoding.UTF8.GetBytes("07"); socket.Send(code2); IFormatter formatter2 = new BinaryFormatter(); Stream stream2 = new MemoryStream(); formatter2.Serialize(stream2, String.Format("{0} вышел из группы {1}", claimToGroup.User, claimToGroup.Group)); byte[] buffer = new byte[1024]; stream2.Position = 0; while (stream2.Position < stream2.Length) { int readCount = stream2.Read(buffer, 0, 1024); socket.Send(buffer, readCount, 0); } } } } }
private void Form1_Load(object sender, EventArgs e) { if (isload)//是否为载入游戏 { #region 初始化棋盘 stackPoint = new Stack<Point>(); stackPictureBox = new Stack<string>(); r_count = 0; b_count = 0; lab_bCount.Text = b_count.ToString(); lab_rCount.Text = r_count.ToString(); pic_chessboard.Enabled = true; btn_TakeBack.Enabled = false; 悔棋ToolStripMenuItem.Enabled = false; whichside = 1; pic_whichside.Image = Image.FromFile(@"img\whichside_red.png"); r_mint = 0; b_mint = 0; lab_rTime.Text = "00:00:00"; lab_bTime.Text = "00:00:00"; p_array = new PictureBox[2, 16] { { pic_Bzu1, pic_Bzu2, pic_Bzu3, pic_Bzu4, pic_Bzu5, pic_Bpao1, pic_Bpao2, pic_Bju1, pic_Bju2, pic_Bma1, pic_Bma2, pic_Bxiang1, pic_Bxiang2, pic_Bshi1, pic_Bshi2, pic_Bjiang }, { pic_Rzu1, pic_Rzu2, pic_Rzu3, pic_Rzu4, pic_Rzu5, pic_Rpao1, pic_Rpao2, pic_Rju1, pic_Rju2, pic_Rma1, pic_Rma2, pic_Rxiang1, pic_Rxiang2, pic_Rshi1, pic_Rshi2, pic_Rjiang } }; //此数组纪录下所有棋,用于判断坐标 p_array[0,x]为黑棋 p_array[1,x]为红棋 /* ChessPieces[,] cp_array = new ChessPieces[2, 16] { { bzu1, bzu2, bzu3, bzu4, bzu5, bpao1, bpao2, bju1, bju2, bma1, bma2, bxiang1, bxiang2, bshi1, bshi2, bjiang }, { rzu1, rzu2, rzu3, rzu4, rzu5, rpao1, rpao2, rju1, rju2, rma1, rma2, rxiang1, rxiang2, rshi1, rshi2, rjiang } }; //此数组纪录下所有棋,用于判断坐标 cp_array[0,x]为黑棋 cp_array[1,x]为红棋 */ for (int i = 0; i != 2; i++)//将所有棋子的picturebox变为圆形 { for (int j = 0; j != 16; j++) { makePicRound(p_array[i, j]); } } //初始化黑棋,创建父类 bzu1 = new BZu(pic_Bzu1, pic_chessboard, p_array, pnl_RedDied, 43, 205, stackPoint, stackPictureBox); bzu2 = new BZu(pic_Bzu2, pic_chessboard, p_array, pnl_RedDied, 151, 205, stackPoint, stackPictureBox); bzu3 = new BZu(pic_Bzu3, pic_chessboard, p_array, pnl_RedDied, 259, 205, stackPoint, stackPictureBox); bzu4 = new BZu(pic_Bzu4, pic_chessboard, p_array, pnl_RedDied, 367, 205, stackPoint, stackPictureBox); bzu5 = new BZu(pic_Bzu5, pic_chessboard, p_array, pnl_RedDied, 475, 205, stackPoint, stackPictureBox); bpao1 = new BPao(pic_Bpao1, pic_chessboard, p_array, pnl_RedDied, 97, 151, stackPoint, stackPictureBox); bpao2 = new BPao(pic_Bpao2, pic_chessboard, p_array, pnl_RedDied, 421, 151, stackPoint, stackPictureBox); bju1 = new BJu(pic_Bju1, pic_chessboard, p_array, pnl_RedDied, 43, 43, stackPoint, stackPictureBox); bju2 = new BJu(pic_Bju2, pic_chessboard, p_array, pnl_RedDied, 475, 43, stackPoint, stackPictureBox); bma1 = new BMa(pic_Bma1, pic_chessboard, p_array, pnl_RedDied, 97, 43, stackPoint, stackPictureBox); bma2 = new BMa(pic_Bma2, pic_chessboard, p_array, pnl_RedDied, 421, 43, stackPoint, stackPictureBox); bxiang1 = new BXiang(pic_Bxiang1, pic_chessboard, p_array, pnl_RedDied, 151, 43, stackPoint, stackPictureBox); bxiang2 = new BXiang(pic_Bxiang2, pic_chessboard, p_array, pnl_RedDied, 367, 43, stackPoint, stackPictureBox); bshi1 = new BShi(pic_Bshi1, pic_chessboard, p_array, pnl_RedDied, 205, 43, stackPoint, stackPictureBox); bshi2 = new BShi(pic_Bshi2, pic_chessboard, p_array, pnl_RedDied, 313, 43, stackPoint, stackPictureBox); bjiang = new BJiang(pic_Bjiang, pic_chessboard, p_array, pnl_RedDied, 259, 43, stackPoint, stackPictureBox); //初始化红棋,创建父类 rzu1 = new RZu(pic_Rzu1, pic_chessboard, p_array, pnl_BlackDied, 43, 367, stackPoint, stackPictureBox); rzu2 = new RZu(pic_Rzu2, pic_chessboard, p_array, pnl_BlackDied, 151, 367, stackPoint, stackPictureBox); rzu3 = new RZu(pic_Rzu3, pic_chessboard, p_array, pnl_BlackDied, 259, 367, stackPoint, stackPictureBox); rzu4 = new RZu(pic_Rzu4, pic_chessboard, p_array, pnl_BlackDied, 367, 367, stackPoint, stackPictureBox); rzu5 = new RZu(pic_Rzu5, pic_chessboard, p_array, pnl_BlackDied, 475, 367, stackPoint, stackPictureBox); rpao1 = new RPao(pic_Rpao1, pic_chessboard, p_array, pnl_BlackDied, 97, 421, stackPoint, stackPictureBox); rpao2 = new RPao(pic_Rpao2, pic_chessboard, p_array, pnl_BlackDied, 421, 421, stackPoint, stackPictureBox); rju1 = new RJu(pic_Rju1, pic_chessboard, p_array, pnl_BlackDied, 43, 529, stackPoint, stackPictureBox); rju2 = new RJu(pic_Rju2, pic_chessboard, p_array, pnl_BlackDied, 475, 529, stackPoint, stackPictureBox); rma1 = new RMa(pic_Rma1, pic_chessboard, p_array, pnl_BlackDied, 97, 529, stackPoint, stackPictureBox); rma2 = new RMa(pic_Rma2, pic_chessboard, p_array, pnl_BlackDied, 421, 529, stackPoint, stackPictureBox); rxiang1 = new RXiang(pic_Rxiang1, pic_chessboard, p_array, pnl_BlackDied, 151, 529, stackPoint, stackPictureBox); rxiang2 = new RXiang(pic_Rxiang2, pic_chessboard, p_array, pnl_BlackDied, 367, 529, stackPoint, stackPictureBox); rshi1 = new RShi(pic_Rshi1, pic_chessboard, p_array, pnl_BlackDied, 205, 529, stackPoint, stackPictureBox); rshi2 = new RShi(pic_Rshi2, pic_chessboard, p_array, pnl_BlackDied, 313, 529, stackPoint, stackPictureBox); rjiang = new RJiang(pic_Rjiang, pic_chessboard, p_array, pnl_BlackDied, 259, 529, stackPoint, stackPictureBox); //s = new System.Media.SoundPlayer(@"sound\begin.WAV"); // s.Play(); tmr1.Start(); #endregion #region 重构棋盘 formatter = new BinaryFormatter(); stream = new FileStream(this.openFileName, FileMode.Open, FileAccess.Read, FileShare.Read); bzu1 = new BZu(pic_Bzu1, pic_chessboard, p_array, pnl_RedDied, 43, 205, stackPoint, stackPictureBox); bzu2 = new BZu(pic_Bzu2, pic_chessboard, p_array, pnl_RedDied, 151, 205, stackPoint, stackPictureBox); bzu3 = new BZu(pic_Bzu3, pic_chessboard, p_array, pnl_RedDied, 259, 205, stackPoint, stackPictureBox); bzu4 = new BZu(pic_Bzu4, pic_chessboard, p_array, pnl_RedDied, 367, 205, stackPoint, stackPictureBox); bzu5 = new BZu(pic_Bzu5, pic_chessboard, p_array, pnl_RedDied, 475, 205, stackPoint, stackPictureBox); bpao1 = new BPao(pic_Bpao1, pic_chessboard, p_array, pnl_RedDied, 97, 151, stackPoint, stackPictureBox); bpao2 = new BPao(pic_Bpao2, pic_chessboard, p_array, pnl_RedDied, 421, 151, stackPoint, stackPictureBox); bju1 = new BJu(pic_Bju1, pic_chessboard, p_array, pnl_RedDied, 43, 43, stackPoint, stackPictureBox); bju2 = new BJu(pic_Bju2, pic_chessboard, p_array, pnl_RedDied, 475, 43, stackPoint, stackPictureBox); bma1 = new BMa(pic_Bma1, pic_chessboard, p_array, pnl_RedDied, 97, 43, stackPoint, stackPictureBox); bma2 = new BMa(pic_Bma2, pic_chessboard, p_array, pnl_RedDied, 421, 43, stackPoint, stackPictureBox); bxiang1 = new BXiang(pic_Bxiang1, pic_chessboard, p_array, pnl_RedDied, 151, 43, stackPoint, stackPictureBox); bxiang2 = new BXiang(pic_Bxiang2, pic_chessboard, p_array, pnl_RedDied, 367, 43, stackPoint, stackPictureBox); bshi1 = new BShi(pic_Bshi1, pic_chessboard, p_array, pnl_RedDied, 205, 43, stackPoint, stackPictureBox); bshi2 = new BShi(pic_Bshi2, pic_chessboard, p_array, pnl_RedDied, 313, 43, stackPoint, stackPictureBox); bjiang = new BJiang(pic_Bjiang, pic_chessboard, p_array, pnl_RedDied, 259, 43, stackPoint, stackPictureBox); //初始化红棋,创建父类 rzu1 = new RZu(pic_Rzu1, pic_chessboard, p_array, pnl_BlackDied, 43, 367, stackPoint, stackPictureBox); rzu2 = new RZu(pic_Rzu2, pic_chessboard, p_array, pnl_BlackDied, 151, 367, stackPoint, stackPictureBox); rzu3 = new RZu(pic_Rzu3, pic_chessboard, p_array, pnl_BlackDied, 259, 367, stackPoint, stackPictureBox); rzu4 = new RZu(pic_Rzu4, pic_chessboard, p_array, pnl_BlackDied, 367, 367, stackPoint, stackPictureBox); rzu5 = new RZu(pic_Rzu5, pic_chessboard, p_array, pnl_BlackDied, 475, 367, stackPoint, stackPictureBox); rpao1 = new RPao(pic_Rpao1, pic_chessboard, p_array, pnl_BlackDied, 97, 421, stackPoint, stackPictureBox); rpao2 = new RPao(pic_Rpao2, pic_chessboard, p_array, pnl_BlackDied, 421, 421, stackPoint, stackPictureBox); rju1 = new RJu(pic_Rju1, pic_chessboard, p_array, pnl_BlackDied, 43, 529, stackPoint, stackPictureBox); rju2 = new RJu(pic_Rju2, pic_chessboard, p_array, pnl_BlackDied, 475, 529, stackPoint, stackPictureBox); rma1 = new RMa(pic_Rma1, pic_chessboard, p_array, pnl_BlackDied, 97, 529, stackPoint, stackPictureBox); rma2 = new RMa(pic_Rma2, pic_chessboard, p_array, pnl_BlackDied, 421, 529, stackPoint, stackPictureBox); rxiang1 = new RXiang(pic_Rxiang1, pic_chessboard, p_array, pnl_BlackDied, 151, 529, stackPoint, stackPictureBox); rxiang2 = new RXiang(pic_Rxiang2, pic_chessboard, p_array, pnl_BlackDied, 367, 529, stackPoint, stackPictureBox); rshi1 = new RShi(pic_Rshi1, pic_chessboard, p_array, pnl_BlackDied, 205, 529, stackPoint, stackPictureBox); rshi2 = new RShi(pic_Rshi2, pic_chessboard, p_array, pnl_BlackDied, 313, 529, stackPoint, stackPictureBox); rjiang = new RJiang(pic_Rjiang, pic_chessboard, p_array, pnl_BlackDied, 259, 529, stackPoint, stackPictureBox); r_count = (int)formatter.Deserialize(stream); b_count = (int)formatter.Deserialize(stream); lab_bCount.Text = b_count.ToString(); lab_rCount.Text = r_count.ToString(); pic_chessboard.Enabled = (bool)formatter.Deserialize(stream); whichside = (int)formatter.Deserialize(stream); if (whichside == 1) { pic_whichside.Image = Image.FromFile(@"img\whichside_red.png"); } else { pic_whichside.Image = Image.FromFile(@"img\whichside_black.png"); } r_mint = (int)formatter.Deserialize(stream); b_mint = (int)formatter.Deserialize(stream); //计时器重写 int h, m, s; string time; s = r_mint % 60; m = (int)r_mint / 60 % 60; h = (int)r_mint / 60 / 60; time = string.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s); lab_rTime.Text = time; s = b_mint % 60; m = (int)b_mint / 60 % 60; h = (int)b_mint / 60 / 60; time = string.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s); lab_bTime.Text = time; p_array = new PictureBox[2, 16] { { pic_Bzu1, pic_Bzu2, pic_Bzu3, pic_Bzu4, pic_Bzu5, pic_Bpao1, pic_Bpao2, pic_Bju1, pic_Bju2, pic_Bma1, pic_Bma2, pic_Bxiang1, pic_Bxiang2, pic_Bshi1, pic_Bshi2, pic_Bjiang }, { pic_Rzu1, pic_Rzu2, pic_Rzu3, pic_Rzu4, pic_Rzu5, pic_Rpao1, pic_Rpao2, pic_Rju1, pic_Rju2, pic_Rma1, pic_Rma2, pic_Rxiang1, pic_Rxiang2, pic_Rshi1, pic_Rshi2, pic_Rjiang } }; //此数组纪录下所有棋,用于判断坐标 p_array[0,x]为黑棋 p_array[1,x]为红棋 /* ChessPieces[,] cp_array = new ChessPieces[2, 16] { { bzu1, bzu2, bzu3, bzu4, bzu5, bpao1, bpao2, bju1, bju2, bma1, bma2, bxiang1, bxiang2, bshi1, bshi2, bjiang }, { rzu1, rzu2, rzu3, rzu4, rzu5, rpao1, rpao2, rju1, rju2, rma1, rma2, rxiang1, rxiang2, rshi1, rshi2, rjiang } }; //此数组纪录下所有棋,用于判断坐标 cp_array[0,x]为黑棋 cp_array[1,x]为红棋 */ for (int i = 0; i != 2; i++)//将所有棋子的picturebox变为圆形 { for (int j = 0; j != 16; j++) { makePicRound(p_array[i, j]); } } int ind; for (int i = 0; i != 2; i++) { for (int j = 0; j != 16; j++) { ind = (int)formatter.Deserialize(stream); if (ind == 1) { p_array[i, j].Parent = pic_chessboard; } else { string sn = p_array[i, j].Name; if (sn[4] == 'B') p_array[i, j].Parent = pnl_BlackDied; else p_array[i, j].Parent = pnl_RedDied; } p_array[i, j].Location = (Point)formatter.Deserialize(stream); } } stream.Close(); tmr1.Start(); stackPoint.Clear(); stackPictureBox.Clear(); btn_TakeBack.Enabled = false; 悔棋ToolStripMenuItem.Enabled = false; #endregion } else { #region 初始化棋盘 stackPoint = new Stack<Point>(); stackPictureBox = new Stack<string>(); r_count = 0; b_count = 0; lab_bCount.Text = b_count.ToString(); lab_rCount.Text = r_count.ToString(); pic_chessboard.Enabled = true; btn_TakeBack.Enabled = false; 悔棋ToolStripMenuItem.Enabled = false; whichside = 1; pic_whichside.Image = Image.FromFile(@"img\whichside_red.png"); r_mint = 0; b_mint = 0; lab_rTime.Text = "00:00:00"; lab_bTime.Text = "00:00:00"; p_array = new PictureBox[2, 16] { { pic_Bzu1, pic_Bzu2, pic_Bzu3, pic_Bzu4, pic_Bzu5, pic_Bpao1, pic_Bpao2, pic_Bju1, pic_Bju2, pic_Bma1, pic_Bma2, pic_Bxiang1, pic_Bxiang2, pic_Bshi1, pic_Bshi2, pic_Bjiang }, { pic_Rzu1, pic_Rzu2, pic_Rzu3, pic_Rzu4, pic_Rzu5, pic_Rpao1, pic_Rpao2, pic_Rju1, pic_Rju2, pic_Rma1, pic_Rma2, pic_Rxiang1, pic_Rxiang2, pic_Rshi1, pic_Rshi2, pic_Rjiang } }; //此数组纪录下所有棋,用于判断坐标 p_array[0,x]为黑棋 p_array[1,x]为红棋 /* ChessPieces[,] cp_array = new ChessPieces[2, 16] { { bzu1, bzu2, bzu3, bzu4, bzu5, bpao1, bpao2, bju1, bju2, bma1, bma2, bxiang1, bxiang2, bshi1, bshi2, bjiang }, { rzu1, rzu2, rzu3, rzu4, rzu5, rpao1, rpao2, rju1, rju2, rma1, rma2, rxiang1, rxiang2, rshi1, rshi2, rjiang } }; //此数组纪录下所有棋,用于判断坐标 cp_array[0,x]为黑棋 cp_array[1,x]为红棋 */ for (int i = 0; i != 2; i++)//将所有棋子的picturebox变为圆形 { for (int j = 0; j != 16; j++) { makePicRound(p_array[i, j]); } } //初始化黑棋,创建父类 bzu1 = new BZu(pic_Bzu1, pic_chessboard, p_array, pnl_RedDied, 43, 205, stackPoint, stackPictureBox); bzu2 = new BZu(pic_Bzu2, pic_chessboard, p_array, pnl_RedDied, 151, 205, stackPoint, stackPictureBox); bzu3 = new BZu(pic_Bzu3, pic_chessboard, p_array, pnl_RedDied, 259, 205, stackPoint, stackPictureBox); bzu4 = new BZu(pic_Bzu4, pic_chessboard, p_array, pnl_RedDied, 367, 205, stackPoint, stackPictureBox); bzu5 = new BZu(pic_Bzu5, pic_chessboard, p_array, pnl_RedDied, 475, 205, stackPoint, stackPictureBox); bpao1 = new BPao(pic_Bpao1, pic_chessboard, p_array, pnl_RedDied, 97, 151, stackPoint, stackPictureBox); bpao2 = new BPao(pic_Bpao2, pic_chessboard, p_array, pnl_RedDied, 421, 151, stackPoint, stackPictureBox); bju1 = new BJu(pic_Bju1, pic_chessboard, p_array, pnl_RedDied, 43, 43, stackPoint, stackPictureBox); bju2 = new BJu(pic_Bju2, pic_chessboard, p_array, pnl_RedDied, 475, 43, stackPoint, stackPictureBox); bma1 = new BMa(pic_Bma1, pic_chessboard, p_array, pnl_RedDied, 97, 43, stackPoint, stackPictureBox); bma2 = new BMa(pic_Bma2, pic_chessboard, p_array, pnl_RedDied, 421, 43, stackPoint, stackPictureBox); bxiang1 = new BXiang(pic_Bxiang1, pic_chessboard, p_array, pnl_RedDied, 151, 43, stackPoint, stackPictureBox); bxiang2 = new BXiang(pic_Bxiang2, pic_chessboard, p_array, pnl_RedDied, 367, 43, stackPoint, stackPictureBox); bshi1 = new BShi(pic_Bshi1, pic_chessboard, p_array, pnl_RedDied, 205, 43, stackPoint, stackPictureBox); bshi2 = new BShi(pic_Bshi2, pic_chessboard, p_array, pnl_RedDied, 313, 43, stackPoint, stackPictureBox); bjiang = new BJiang(pic_Bjiang, pic_chessboard, p_array, pnl_RedDied, 259, 43, stackPoint, stackPictureBox); //初始化红棋,创建父类 rzu1 = new RZu(pic_Rzu1, pic_chessboard, p_array, pnl_BlackDied, 43, 367, stackPoint, stackPictureBox); rzu2 = new RZu(pic_Rzu2, pic_chessboard, p_array, pnl_BlackDied, 151, 367, stackPoint, stackPictureBox); rzu3 = new RZu(pic_Rzu3, pic_chessboard, p_array, pnl_BlackDied, 259, 367, stackPoint, stackPictureBox); rzu4 = new RZu(pic_Rzu4, pic_chessboard, p_array, pnl_BlackDied, 367, 367, stackPoint, stackPictureBox); rzu5 = new RZu(pic_Rzu5, pic_chessboard, p_array, pnl_BlackDied, 475, 367, stackPoint, stackPictureBox); rpao1 = new RPao(pic_Rpao1, pic_chessboard, p_array, pnl_BlackDied, 97, 421, stackPoint, stackPictureBox); rpao2 = new RPao(pic_Rpao2, pic_chessboard, p_array, pnl_BlackDied, 421, 421, stackPoint, stackPictureBox); rju1 = new RJu(pic_Rju1, pic_chessboard, p_array, pnl_BlackDied, 43, 529, stackPoint, stackPictureBox); rju2 = new RJu(pic_Rju2, pic_chessboard, p_array, pnl_BlackDied, 475, 529, stackPoint, stackPictureBox); rma1 = new RMa(pic_Rma1, pic_chessboard, p_array, pnl_BlackDied, 97, 529, stackPoint, stackPictureBox); rma2 = new RMa(pic_Rma2, pic_chessboard, p_array, pnl_BlackDied, 421, 529, stackPoint, stackPictureBox); rxiang1 = new RXiang(pic_Rxiang1, pic_chessboard, p_array, pnl_BlackDied, 151, 529, stackPoint, stackPictureBox); rxiang2 = new RXiang(pic_Rxiang2, pic_chessboard, p_array, pnl_BlackDied, 367, 529, stackPoint, stackPictureBox); rshi1 = new RShi(pic_Rshi1, pic_chessboard, p_array, pnl_BlackDied, 205, 529, stackPoint, stackPictureBox); rshi2 = new RShi(pic_Rshi2, pic_chessboard, p_array, pnl_BlackDied, 313, 529, stackPoint, stackPictureBox); rjiang = new RJiang(pic_Rjiang, pic_chessboard, p_array, pnl_BlackDied, 259, 529, stackPoint, stackPictureBox); s = new System.Media.SoundPlayer(@"sound\begin.WAV"); s.Play(); tmr1.Start(); #endregion } #region 初始化背景音乐 wmp_background.currentPlaylist.appendItem(wmp_background.newMedia(@"sound\background\2.mp3")); wmp_background.currentPlaylist.appendItem(wmp_background.newMedia(@"sound\background\3.mp3")); wmp_background.currentPlaylist.appendItem(wmp_background.newMedia(@"sound\background\4.mp3")); wmp_background.currentPlaylist.appendItem(wmp_background.newMedia(@"sound\background\5.mp3")); wmp_background.currentPlaylist.appendItem(wmp_background.newMedia(@"sound\background\6.mp3")); wmp_background.settings.volume = 30; wmp_background.settings.playCount = 99; wmp_background.Ctlcontrols.play(); #endregion }
private void btn_load_Click(object sender, EventArgs e) { if (ofd1.ShowDialog() == DialogResult.OK) { openFileName = ofd1.FileName; formatter = new BinaryFormatter(); stream = new FileStream(this.openFileName, FileMode.Open, FileAccess.Read, FileShare.Read); #region 重构棋盘 //初始化黑棋,创建父类 bzu1 = new BZu(pic_Bzu1, pic_chessboard, p_array, pnl_RedDied, 43, 205, stackPoint, stackPictureBox); bzu2 = new BZu(pic_Bzu2, pic_chessboard, p_array, pnl_RedDied, 151, 205, stackPoint, stackPictureBox); bzu3 = new BZu(pic_Bzu3, pic_chessboard, p_array, pnl_RedDied, 259, 205, stackPoint, stackPictureBox); bzu4 = new BZu(pic_Bzu4, pic_chessboard, p_array, pnl_RedDied, 367, 205, stackPoint, stackPictureBox); bzu5 = new BZu(pic_Bzu5, pic_chessboard, p_array, pnl_RedDied, 475, 205, stackPoint, stackPictureBox); bpao1 = new BPao(pic_Bpao1, pic_chessboard, p_array, pnl_RedDied, 97, 151, stackPoint, stackPictureBox); bpao2 = new BPao(pic_Bpao2, pic_chessboard, p_array, pnl_RedDied, 421, 151, stackPoint, stackPictureBox); bju1 = new BJu(pic_Bju1, pic_chessboard, p_array, pnl_RedDied, 43, 43, stackPoint, stackPictureBox); bju2 = new BJu(pic_Bju2, pic_chessboard, p_array, pnl_RedDied, 475, 43, stackPoint, stackPictureBox); bma1 = new BMa(pic_Bma1, pic_chessboard, p_array, pnl_RedDied, 97, 43, stackPoint, stackPictureBox); bma2 = new BMa(pic_Bma2, pic_chessboard, p_array, pnl_RedDied, 421, 43, stackPoint, stackPictureBox); bxiang1 = new BXiang(pic_Bxiang1, pic_chessboard, p_array, pnl_RedDied, 151, 43, stackPoint, stackPictureBox); bxiang2 = new BXiang(pic_Bxiang2, pic_chessboard, p_array, pnl_RedDied, 367, 43, stackPoint, stackPictureBox); bshi1 = new BShi(pic_Bshi1, pic_chessboard, p_array, pnl_RedDied, 205, 43, stackPoint, stackPictureBox); bshi2 = new BShi(pic_Bshi2, pic_chessboard, p_array, pnl_RedDied, 313, 43, stackPoint, stackPictureBox); bjiang = new BJiang(pic_Bjiang, pic_chessboard, p_array, pnl_RedDied, 259, 43, stackPoint, stackPictureBox); //初始化红棋,创建父类 rzu1 = new RZu(pic_Rzu1, pic_chessboard, p_array, pnl_BlackDied, 43, 367, stackPoint, stackPictureBox); rzu2 = new RZu(pic_Rzu2, pic_chessboard, p_array, pnl_BlackDied, 151, 367, stackPoint, stackPictureBox); rzu3 = new RZu(pic_Rzu3, pic_chessboard, p_array, pnl_BlackDied, 259, 367, stackPoint, stackPictureBox); rzu4 = new RZu(pic_Rzu4, pic_chessboard, p_array, pnl_BlackDied, 367, 367, stackPoint, stackPictureBox); rzu5 = new RZu(pic_Rzu5, pic_chessboard, p_array, pnl_BlackDied, 475, 367, stackPoint, stackPictureBox); rpao1 = new RPao(pic_Rpao1, pic_chessboard, p_array, pnl_BlackDied, 97, 421, stackPoint, stackPictureBox); rpao2 = new RPao(pic_Rpao2, pic_chessboard, p_array, pnl_BlackDied, 421, 421, stackPoint, stackPictureBox); rju1 = new RJu(pic_Rju1, pic_chessboard, p_array, pnl_BlackDied, 43, 529, stackPoint, stackPictureBox); rju2 = new RJu(pic_Rju2, pic_chessboard, p_array, pnl_BlackDied, 475, 529, stackPoint, stackPictureBox); rma1 = new RMa(pic_Rma1, pic_chessboard, p_array, pnl_BlackDied, 97, 529, stackPoint, stackPictureBox); rma2 = new RMa(pic_Rma2, pic_chessboard, p_array, pnl_BlackDied, 421, 529, stackPoint, stackPictureBox); rxiang1 = new RXiang(pic_Rxiang1, pic_chessboard, p_array, pnl_BlackDied, 151, 529, stackPoint, stackPictureBox); rxiang2 = new RXiang(pic_Rxiang2, pic_chessboard, p_array, pnl_BlackDied, 367, 529, stackPoint, stackPictureBox); rshi1 = new RShi(pic_Rshi1, pic_chessboard, p_array, pnl_BlackDied, 205, 529, stackPoint, stackPictureBox); rshi2 = new RShi(pic_Rshi2, pic_chessboard, p_array, pnl_BlackDied, 313, 529, stackPoint, stackPictureBox); rjiang = new RJiang(pic_Rjiang, pic_chessboard, p_array, pnl_BlackDied, 259, 529, stackPoint, stackPictureBox); r_count = (int)formatter.Deserialize(stream); b_count = (int)formatter.Deserialize(stream); lab_bCount.Text = b_count.ToString(); lab_rCount.Text = r_count.ToString(); pic_chessboard.Enabled = (bool)formatter.Deserialize(stream); whichside = (int)formatter.Deserialize(stream); if (whichside == 1) { pic_whichside.Image = Image.FromFile(@"img\whichside_red.png"); } else { pic_whichside.Image = Image.FromFile(@"img\whichside_black.png"); } r_mint = (int)formatter.Deserialize(stream); b_mint = (int)formatter.Deserialize(stream); //计时器重写 int h, m, s; string time; s = r_mint % 60; m = (int)r_mint / 60 % 60; h = (int)r_mint / 60 / 60; time = string.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s); lab_rTime.Text = time; s = b_mint % 60; m = (int)b_mint / 60 % 60; h = (int)b_mint / 60 / 60; time = string.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s); lab_bTime.Text = time; p_array = new PictureBox[2, 16] { { pic_Bzu1, pic_Bzu2, pic_Bzu3, pic_Bzu4, pic_Bzu5, pic_Bpao1, pic_Bpao2, pic_Bju1, pic_Bju2, pic_Bma1, pic_Bma2, pic_Bxiang1, pic_Bxiang2, pic_Bshi1, pic_Bshi2, pic_Bjiang }, { pic_Rzu1, pic_Rzu2, pic_Rzu3, pic_Rzu4, pic_Rzu5, pic_Rpao1, pic_Rpao2, pic_Rju1, pic_Rju2, pic_Rma1, pic_Rma2, pic_Rxiang1, pic_Rxiang2, pic_Rshi1, pic_Rshi2, pic_Rjiang } }; //此数组纪录下所有棋,用于判断坐标 p_array[0,x]为黑棋 p_array[1,x]为红棋 /* ChessPieces[,] cp_array = new ChessPieces[2, 16] { { bzu1, bzu2, bzu3, bzu4, bzu5, bpao1, bpao2, bju1, bju2, bma1, bma2, bxiang1, bxiang2, bshi1, bshi2, bjiang }, { rzu1, rzu2, rzu3, rzu4, rzu5, rpao1, rpao2, rju1, rju2, rma1, rma2, rxiang1, rxiang2, rshi1, rshi2, rjiang } }; //此数组纪录下所有棋,用于判断坐标 cp_array[0,x]为黑棋 cp_array[1,x]为红棋 */ for (int i = 0; i != 2; i++)//将所有棋子的picturebox变为圆形 { for (int j = 0; j != 16; j++) { makePicRound(p_array[i, j]); } } int ind; for (int i = 0; i != 2; i++) { for (int j = 0; j != 16; j++) { ind = (int)formatter.Deserialize(stream); if (ind == 1) { p_array[i, j].Parent = pic_chessboard; } else { string sn = p_array[i, j].Name; if (sn[4] == 'B') p_array[i, j].Parent = pnl_BlackDied; else p_array[i, j].Parent = pnl_RedDied; } p_array[i, j].Location = (Point)formatter.Deserialize(stream); } } stream.Close(); tmr1.Start(); stackPoint.Clear(); stackPictureBox.Clear(); btn_TakeBack.Enabled = false; 悔棋ToolStripMenuItem.Enabled = false; #endregion } }
/// <summary> /// Load activity from the given stream /// </summary> /// <param name="stream">stream with serialized activity</param> /// <param name="formatter">formatter to be used during deserialization</param> /// <returns>deserialized activity</returns> public static Activity Load (Stream stream, Activity outerActivity, IFormatter formatter) { if (stream == null) throw new ArgumentNullException ("stream"); if (formatter == null) throw new ArgumentNullException ("formatter"); return (Activity)formatter.Deserialize (stream); }
private static Object[] obj_deserialize_int (byte [] in_bytes, Int32 asem_type, String assem, String atype, IFormatter bf) { Object [] ret = new Object[2]; System.IO.MemoryStream mem_strim = new System.IO.MemoryStream (); Type type = new VInvoke().get_type (asem_type, assem, atype); mem_strim.Seek(0, SeekOrigin.Begin); mem_strim.Write (in_bytes, 0, (int) in_bytes.Length); mem_strim.Seek(0, SeekOrigin.Begin); Object org_obj = bf.Deserialize(mem_strim); if (!(type.IsInstanceOfType (org_obj) || (org_obj != null && type == org_obj.GetType()))) throw new Exception ("The deserialized object is not an instance of " + type.FullName); return res_to_ptr (org_obj); }
public static Author DeserializeItem(string fileName, IFormatter formatter) { FileStream s = new FileStream(fileName, FileMode.Open); return (Author)formatter.Deserialize(s); }
static object DeserializeObject(IFormatter serializer, XmlNode element) { using (var memoryStream = new MemoryStream()) using (var xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(memoryStream)) { element.WriteContentTo(xmlDictionaryWriter); xmlDictionaryWriter.Flush(); memoryStream.Position = 0; var deserializedObject = serializer.Deserialize(memoryStream); return deserializedObject; } }
/// <summary> /// /// </summary> /// <param name="resultMessage"></param> /// <param name="returnType"></param> /// <param name="formatter"></param> /// <returns></returns> protected virtual object GetResult(IResponseMessage resultMessage, Type returnType, IFormatter formatter) { if (resultMessage.IsSuccess) { if (resultMessage.Result == null || returnType == null) return null; var objType = returnType; try { var resultObj = formatter.Deserialize(resultMessage.Result, objType); return resultObj; } catch (Exception ex) { throw new ServiceException("parse data received error", ex); } finally { resultMessage.Dispose(); } } if (resultMessage.Headers.Count == 0) throw new ServiceException("service url is not a service address"); var exceptionAssembly = resultMessage.Headers[HeaderName.ExceptionAssembly]; var exceptionTypeName = resultMessage.Headers[HeaderName.ExceptionType]; if (string.IsNullOrWhiteSpace(exceptionAssembly) || string.IsNullOrWhiteSpace(exceptionTypeName)) { throw new ClientException("exception occored, but no ExceptionAssembly and ExceptionType returned"); } Type exceptionType; try { #if NETCORE var asm = Assembly.Load(new AssemblyName(exceptionAssembly)); #else var asm = Assembly.Load(exceptionAssembly); #endif exceptionType = asm.GetType(exceptionTypeName); } catch (Exception ex) { LogHelper.Error("can't find exception type " + exceptionTypeName, ex); exceptionType = typeof(Exception); } object exObj; try { //var buf = new byte[8192]; //var readLength = resultMessage.Result.Read(buf, 0, buf.Length); //var json = Encoding.UTF8.GetString(buf); exObj = formatter.SupportException ? formatter.Deserialize(resultMessage.Result, exceptionType) : Activator.CreateInstance(exceptionType); } catch (Exception ex) { throw new ClientException("Deserialize Response failed", ex); } if (exObj != null) throw (Exception)exObj; //return default(TResult); throw new ServiceException("exception occored but no exception data transported"); }
public static object Deserialize( this Stream sm, IFormatter formatter ) { if( formatter == null ) throw new ArgumentNullException( "formatter", "IFormatter cannot be null." ); object obj = formatter.Deserialize( sm ); return obj; }
void Method3(Stream stream, IFormatter formatter) { Console.WriteLine("Method3 Start : UnBan User To User"); stream.Position = 0; if (stream.Length > 0) { BanPair bP = (BanPair)(formatter.Deserialize(stream)); foreach (BanPair bPair in BanPairManager.BanPairs) { if (bPair.Id1 == bP.Id1 && bPair.Id2 == bP.Id2) { BanPairManager.BanPairs.Remove(bPair); break; } } string query = string.Format("delete from BanList where UserID1={0} and UserID2={1}", bP.Id1, bP.Id2); SqlCommand command = new SqlCommand(query, DataBase.Sql); command.ExecuteNonQuery(); Dictionary<Socket, ChatInfoDAL.User>.ValueCollection valUser = dictSocketUser.Values; int numBanned; bool online = false; for (numBanned = 0; numBanned < valUser.Count; numBanned++) { if (valUser.ElementAt(numBanned).UserID == bP.Id2) { online = true; break; } } string nameBan = string.Empty; foreach (ChatInfoDAL.User us in UserManager.Users) { if (us.UserID == bP.Id1) { nameBan = us.NickName; break; } } string nameBan2 = string.Empty; foreach (ChatInfoDAL.User us in UserManager.Users) { if (us.UserID == bP.Id2) { nameBan2 = us.NickName; break; } } Action<string> action = MessageToInfoStackAdd; string messa = String.Format("{0} разбанил {1}", nameBan, nameBan2); infoStack.Dispatcher.Invoke(action, messa); if (online) { Socket sctBanned = dictSocketUser.ElementAt(numBanned).Key; byte[] code = Encoding.UTF8.GetBytes("07"); sctBanned.Send(code); IFormatter formatter2 = new BinaryFormatter(); Stream stream2 = new MemoryStream(); string messageBan = String.Format("Пользователь {0} вас разбанил", nameBan); formatter2.Serialize(stream2, messageBan); byte[] buffer2 = new byte[1024]; stream2.Position = 0; while (stream2.Position < stream2.Length) { int readCount = stream2.Read(buffer2, 0, 1024); sctBanned.Send(buffer2, readCount, 0); } } else { ChatInfoDAL.User userToSend = null; foreach (ChatInfoDAL.User us in UserManager.Users) { if (us.UserID == bP.Id2) { userToSend = us; break; } } messInQueue.Add(new MessageQueue(userToSend, String.Format("Пользователь {0} вас разбанил", nameBan))); } } }
public static void DeserializeItem( string fileName, IFormatter formatter ) { System.IO.FileStream s = new System.IO.FileStream( fileName, FileMode.Open ); MyItemType t = ( MyItemType )formatter.Deserialize( s ); Console.WriteLine( t.MyProperty ); }
void Method1(Stream stream, IFormatter formatter) { Console.WriteLine("Method1 Start : Сообщение от клиента"); //stream.Flush(); stream.Position = 0; if (stream.Length > 0) { Message message = (Message)(formatter.Deserialize(stream)); ChatInfoDAL.User user = null; foreach (ChatInfoDAL.User us in UserManager.Users) { if (us.UserID == message.UserID) { user = us; break; } } if (user.Ban > DateTime.Now) { Action<string> action = MessageToInfoStackAdd; string messa = String.Format("{0} забанен и не может отправлять сообщения", user.NickName); infoStack.Dispatcher.Invoke(action, messa); } else { string query = string.Format("insert into Messagese (GroupID, Texts, UserID, TimeMes) values ({0}, '{1}', {2}, '{3}')", message.GroupID, message.Text, message.UserID, message.DT); SqlCommand command = new SqlCommand(query, DataBase.Sql); command.ExecuteNonQuery(); string queryNewID = string.Format("select IDENT_CURRENT('Messagese') as ID_cur"); SqlCommand commandNewID = new SqlCommand(queryNewID, DataBase.Sql); SqlDataReader readerNewID = commandNewID.ExecuteReader(); readerNewID.Read(); int id = int.Parse(readerNewID["ID_cur"].ToString()); readerNewID.Close(); message.MessageID = id; MessageManager.Messages.Add(message); Action<string> action = MessageToInfoStackAdd; string messa = String.Format("{0} отправил сообщение : {1}", user.NickName, message.Text); infoStack.Dispatcher.Invoke(action, messa); SendingMessage(message); } } stream.Close(); }
private static void ReadCommand(Stream networkStream, IFormatter formatter, out int stageId, out string deserializerMode, out string serializerMode, out CSharpWorkerFunc workerFunc) { stageId = ReadDiagnosticsInfo(networkStream); deserializerMode = SerDe.ReadString(networkStream); logger.LogDebug("Deserializer mode: " + deserializerMode); serializerMode = SerDe.ReadString(networkStream); logger.LogDebug("Serializer mode: " + serializerMode); string runMode = SerDe.ReadString(networkStream); if ("R".Equals(runMode, StringComparison.InvariantCultureIgnoreCase)) { var compilationDumpDir = SerDe.ReadString(networkStream); if (Directory.Exists(compilationDumpDir)) { assemblyHandler.LoadAssemblies(Directory.GetFiles(compilationDumpDir, "ReplCompilation.*", SearchOption.TopDirectoryOnly)); } else { logger.LogError("Directory " + compilationDumpDir + " dose not exist."); } } byte[] command = SerDe.ReadBytes(networkStream); logger.LogDebug("command bytes read: " + command.Length); var stream = new MemoryStream(command); workerFunc = (CSharpWorkerFunc)formatter.Deserialize(stream); if (!logger.IsDebugEnabled) return; var sb = new StringBuilder(Environment.NewLine); sb.AppendLine( "------------------------ Printing stack trace of workerFunc for ** debugging ** ------------------------------"); sb.AppendLine(workerFunc.StackTrace); sb.AppendLine( "--------------------------------------------------------------------------------------------------------------"); logger.LogDebug(sb.ToString()); }
/// <summary> /// Apply the dialog settings that have previously been serialized /// </summary> /// <param name="stream">The stream to apply the settings from</param> /// <param name="formatter">The formatter to use</param> private void ApplyRestoreData(Stream stream, IFormatter formatter) { Bounds = (Rectangle)formatter.Deserialize(stream); ignoreCaseCheckBox.Checked = (bool)formatter.Deserialize(stream); searchTypeComboBox.SelectedIndex = (int)formatter.Deserialize(stream); searchHistoryComboBox.Text = (string)formatter.Deserialize(stream); DeserializeList(stream, formatter, searchHistoryComboBox.Items); replaceHistoryComboBox.Text = (string)formatter.Deserialize(stream); DeserializeList(stream, formatter, replaceHistoryComboBox.Items); replaceModeCheckBox.Checked = (bool)formatter.Deserialize(stream); }
/// <summary> /// The read external. /// </summary> /// <param name="formatter"> /// The formatter. /// </param> /// <param name="stream"> /// The stream. /// </param> /// <returns> /// The <see cref="KeyValueImpl"/> . /// </returns> public static KeyValueImpl ReadExternal(IFormatter formatter, Stream stream) { return (KeyValueImpl)formatter.Deserialize(stream); }
public void Benchmark(IFormatter formatter) { var ms = new MemoryStream(); Console.WriteLine(formatter.ToString()); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 5000; i++) { formatter.Serialize(ms, _graph); ms.Position = 0; } Console.WriteLine("Size: " + ms.Length); Console.WriteLine("Serialization: " + sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < 5000; i++) { formatter.Deserialize(ms); ms.Position = 0; } Console.WriteLine("Deserialization: " + sw.Elapsed); }
void Method4(Stream stream, IFormatter formatter) { Console.WriteLine("Method4 Start : Заявка на вступление в группу"); stream.Position = 0; if (stream.Length > 0) { ClaimToGroup claimToGroup = (ClaimToGroup)(formatter.Deserialize(stream)); Action<ClaimToGroup> claimer = SetNewClaimToList; listBox2.Dispatcher.Invoke(claimer, claimToGroup); Action<string> action = MessageToInfoStackAdd; string messa = String.Format("{0} прислал заявку на вступление в группу {1}", claimToGroup.User, claimToGroup.Group); infoStack.Dispatcher.Invoke(action, messa); } }