Exemple #1
0
 public static string Serialize(object o)
 {
     BinaryFormatter bf = new BinaryFormatter();
     MemoryStream m = new MemoryStream();
     bf.Serialize(m, o);
     return System.Convert.ToBase64String(m.GetBuffer());
 }
Exemple #2
0
    public void CargarMapa(string nombre)
    {
        BinaryFormatter bf = new BinaryFormatter();

        if (File.Exists(Application.persistentDataPath + "/" + nombre + ".map"))
        {
            FileStream mapa = File.Open(Application.persistentDataPath + "/" + nombre + ".map", FileMode.Open);

            MapData mapData = bf.Deserialize(mapa) as MapData;

            Debug.Log(mapData.id.Count);

            GameObject[] objetos = GameObject.FindGameObjectsWithTag("Objeto");

            foreach(GameObject ano in objetos)
            {
                Destroy(ano);
            }

            for (int i = 0; i < mapData.id.Count; i++)
            {
                GameObject bloque = Instantiate(prefabObjeto, new Vector3(mapData.xPos[i], mapData.yPos[i], 0f), Quaternion.identity) as GameObject;
                bloque.GetComponent<SpriteRenderer>().sprite = listaObjetos.objetos[mapData.id[i]].sprite;
                bloque.GetComponent<ID>().id = mapData.id[i];
                bloque.transform.SetParent(objetosMapa);
            }

            mapa.Close();
        }
        else
        {
            Debug.LogError("'" + nombre + ".dat' no encontrado");
        }
    }
 public PlayerData LoadData()
 {
     PlayerData data;
     if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat",FileMode.Open);
         data = (PlayerData)bf.Deserialize(file);
         file.Close();
     }
     else
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
         data = new PlayerData();
         data.highestScore = 0;
         data.totalScore = 0;
         data.cubesDestroyed = 0;
         data.lastScore = 0;
         data.purpleCubes = 0;
         data.blueCubes = 0;
         data.redCubes = 0;
         data.yellowCubes = 0;
         data.greenCubes = 0;
         data.isHighScore = false;
         bf.Serialize(file, data);
         file.Close();
     }
     return data;
 }
    public GameObject Load(int codigo1, int codigo2)
    {
        saveAtual = GameObject.FindObjectOfType<SaveAtual>();
        if (File.Exists(Application.persistentDataPath+"/" + saveAtual.getSaveAtualId() + "" + codigo1 + "" +codigo2+ "MapaData.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/" + saveAtual.getSaveAtualId() + "" + codigo1 + "" + codigo2 + "MapaData.dat",FileMode.Open);

            MapaData mapaData = (MapaData)bf.Deserialize(file);
            file.Close();
            this.largura.position = mapaData.largura.V3;
            this.altura.position = mapaData.altura.V3;
            this.comprado = mapaData.comprado;
            celulasLosango = new ArrayList();
            foreach (CelulaData celulas in mapaData.celulasLosango)
            {
                GameObject celula  = GameObject.Instantiate(LosangoBase) as GameObject;
                celula.transform.position = celulas.posicaoCelula.V3;
                celula.GetComponent<Celula>().recurso.setRecurso(celulas.Recurso, celulas.recursoLv);
                celula.GetComponent<Celula>().recurso.setTempoDecorrido(celulas.tempoDecorrido);
                celula.GetComponent<Celula>().recurso.compradoPeloJogador = celulas.compradoPeloJogador;
                celulasLosango.Add(celula);
                celula.transform.parent = this.gameObject.transform;
            }
            return this.gameObject;
        }
        return null;
    }
    // Takes the data that is in the save file and gives it to GameControler
	private void Load (){

		// Only loads if there is a file to load from, and this is in the level menu scene
		if (SceneManager.GetActiveScene().buildIndex == LEVEL_SELECT_SCENE_INDEX){ 
			using(FileStream file = File.Open(Application.persistentDataPath + levelStateDataFileEndAddress,FileMode.Open))
			{
				BinaryFormatter bf = new BinaryFormatter();

				LevelStateData data = (LevelStateData) bf.Deserialize(file);

                LevelInfoHolder[] levelInfo;

                if (data.LevelStatusArray.Length <= 0){ // If there isnt stored information on the level status array in the file, make a new default array
                    levelInfo = GameControler.GetDefaultLevelCompleteArray();
                }
				else {
                    // There is information on the file, so we want to pass it on to GameControler
                    levelInfo = data.LevelStatusArray;
                }

                // The save file is currently open so we can't and don't want to save 
                GameControler.SetLevelCompleteArrayWithoutSaving(levelInfo);

                file.Close();
				Debug.Log("Loaded");			
			}
		}
	}
Exemple #6
0
    public static bool Load(Chunk chunk)
    {

        string saveFile = SaveLocation(chunk.world.worldName);
        saveFile += FileName(chunk.pos);

        if (!File.Exists(saveFile))
            return false;
        try
        {

            IFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(saveFile, FileMode.Open);

            Save save = (Save)formatter.Deserialize(stream);

            //Once the blocks in the save are added they're marked as unmodified so
            //as not to trigger a new save on unload unless new blocks are added.
            for (int i =0; i< save.blocks.Length; i++)
            {
                Block placeBlock = save.blocks[i];
                placeBlock.modified = false;
                chunk.SetBlock(save.positions[i], placeBlock, false);
            }

            stream.Close();
        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }


        return true;
    }
    public void Save(int score, int cubesDestroyed, int purpleCubes, int blueCubes, int redCubes, int yellowCubes, int greenCubes)
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
        PlayerData data = new PlayerData();

        if (score > data.highestScore)
        {
            data.highestScore = score;
            data.isHighScore = true;
        }
        else
            data.isHighScore = false;

        data.totalScore += score;
        data.cubesDestroyed += cubesDestroyed;
        data.lastScore = score;
        data.purpleCubes = purpleCubes;
        data.blueCubes = blueCubes;
        data.redCubes = redCubes;
        data.yellowCubes = yellowCubes;
        data.greenCubes = greenCubes;


        bf.Serialize(file, data);
        file.Close();
    }
 public static void Save()
 {
     BinaryFormatter bf = new BinaryFormatter();
     FileStream file = File.Create (Application.persistentDataPath + "/player.gd");
     bf.Serialize(file, SaveSelectedPlayer.player);
     file.Close();
 }
Exemple #9
0
    public User LoadUserFriendsFromLocalMemory()
    {
        BinaryFormatter bf = null;
        FileStream file = null;
        User user = new User();
        try{
            FilePath = Application.persistentDataPath + FRIENDS_LOCAL_FILE_NAME;
            Debug.Log("loadUserFromLocalMemory():FilePath " + FilePath);
            if(File.Exists(FilePath)){
                Debug.Log("Yes File.Exists.....@ " + FilePath);
                bf = new BinaryFormatter();
                file = File.Open(FilePath,FileMode.Open);
                user = (User)bf.Deserialize(file);
            }
        }

        catch (FileNotFoundException  ex)
        {
            Debug.Log("FileNotFoundException:ex " + ex.ToString());
        }
        catch (IOException ex)
        {
            Debug.Log("IOException:ex " + ex.ToString());
        }
        catch (Exception ex){
            Debug.Log("Exception:ex " + ex.ToString());
        }
        finally
        {
            if (file != null)
                file.Close();
        }
        return user;
    }
 public void Save()
 {
     BinaryFormatter bf = new BinaryFormatter();
     FileStream file = File.Create (Application.persistentDataPath + "/savedPlayers.gd");
     bf.Serialize(file, savedPlayers);
     file.Close();
 }
Exemple #11
0
    public void LoadLevel(int levelNumber)
    {
        Debug.Log("loading");
        var formatter = new BinaryFormatter();
        FileStream stream = File.OpenRead(datapath + levelNumber + ".lvl");
        var ballList = (BallInfo[]) formatter.Deserialize(stream);
        stream.Close();

        var bf = FindObjectOfType<BallFactory>();
        var bfIterator = 1;

        foreach (var ball in ballList)
        {
            if (bf != null)
            {
                if (ball.isBogus)
                {
                    bf.Instantiate(ball, -1);
                }
                else
                {
                    bf.Instantiate(ball, bfIterator);
                    bfIterator++;
                }
            }
        }
    }
Exemple #12
0
	/*
	 * Tries to open a save file for the current player.
	 * If it can't, it creates a new save file.
	 * In the future, this may need to consider an player
	 * name so we can have multiple save files.
	 */
	public void load() {
		if (File.Exists(pathname)) {
			//Debug.Log("Loading file at " + pathname);
			string fullPath = pathname;

			BinaryFormatter binForm = new BinaryFormatter ();
			FileStream saveFile = File.Open (fullPath, FileMode.Open);

			MetaPhoto saveData = (MetaPhoto)binForm.Deserialize (saveFile);
			saveFile.Close ();

			balanceValue = saveData.balan;
			spacingValue = saveData.spaci;
			interestingnessValue = saveData.inter;
			containsFox = saveData.containsFox;
			containsOwl = saveData.containsOwl;
			containsDeer = saveData.containsDeer;
			containsPosingAnimal = saveData.containsPosingAnimal;
			takenWithTelephoto = saveData.takenWithTelephoto;
			takenWithWide = saveData.takenWithWide;
			takenWithFilter = saveData.takenWithFilter;
			comments = saveData.comments;
		} else {
			Debug.Log("Save file does not exist! Creating an empty one...");
			createProfile ();
		}
	}
Exemple #13
0
	/*
	 * Tries to write to a save file for the current player.
	 * In the future, this may need to consider a player
	 * name so we can have multiple save files.
	 */
	public void save() {
		//Debug.Log("Saving file to " + pathname);

		BinaryFormatter binForm = new BinaryFormatter ();

		FileStream saveFile;
		if (File.Exists (pathname)) {
			saveFile = File.Open (pathname, FileMode.Open);
		} else saveFile = File.Create (pathname);

		MetaPhoto saveData = new MetaPhoto ();
		saveData.balan = balanceValue;
		saveData.spaci = spacingValue;
		saveData.inter = interestingnessValue;
        saveData.containsFox = containsFox;
        saveData.containsOwl = containsOwl;
        saveData.containsDeer = containsDeer;
        saveData.containsPosingAnimal = containsPosingAnimal;
        saveData.takenWithTelephoto = takenWithTelephoto;
        saveData.takenWithWide = takenWithWide;
		saveData.takenWithFilter = takenWithFilter;
		saveData.comments = comments;

		binForm.Serialize (saveFile, saveData);
		saveFile.Close ();
	}
 public static byte[] GetBytes(Level data)
 {
     IFormatter formatter = new BinaryFormatter();
     MemoryStream stream = new MemoryStream();
     formatter.Serialize(stream, data);
     return stream.ToArray();
 }
 public static void SaveToFile(Level data, string fileName)
 {
     IFormatter formatter = new BinaryFormatter();
     Stream stream = new FileStream(string.Format("{0}.level", fileName), FileMode.Create, FileAccess.Write, FileShare.Write);
     formatter.Serialize(stream, data);
     stream.Close();
 }
Exemple #16
0
    public static object byteToObject(byte[] src)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream(src);

        return bf.Deserialize(ms);
    }
Exemple #17
0
    Messages Deserialize(byte[] bytes)
    {
        MemoryStream stream = new MemoryStream(bytes);
        BinaryFormatter b = new BinaryFormatter();

        return (Messages)b.Deserialize(stream);
    }
Exemple #18
0
    public static object DeserializeObjectFromFile(string filePath)
    {
        if (!File.Exists(filePath)) {
            return null;
        }

        EasySerializer.SetEnvironmentVariables();

        Stream stream = null;

        try {
            stream = File.Open(filePath, FileMode.Open);
        }

        catch(FileNotFoundException e) {
            UnityEngine.Debug.LogError(e);
            return null;
        }

        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Binder = new VersionDeserializationBinder();
        object o = formatter.Deserialize(stream);

        stream.Close();

        return o;
    }
Exemple #19
0
    public static bool LoadData()
    {
        string path = Path.Combine(Application.persistentDataPath, filename);
        if (File.Exists(path) == false)
        {
            Debug.Log("No Save Exists");
            return false;
        }

        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(path, FileMode.Open);
            Data data = bf.Deserialize(file) as Data;

            Coins.total = data.coins;
            CellHandler.turns = data.turns;
            GameObject[,] cells = sCell.getCellArray(data.cells);
            CellHandler.singleton.setParentForCells(cells);
            CellValue.SwordTotal = data.SwordPower;
            CellValue.MonsterTotal = data.MonsterPower;
            file.Close();
            Debug.Log("Game Loaded");
            return true;
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            return false;
        }
    }
Exemple #20
0
 //Funcion para guardar los datos durante el juego
 public static void setUserGameStatus(UserGameStatus gameStatus)
 {
     BinaryFormatter bf = new BinaryFormatter ();
     FileStream file = File.Create (Application.persistentDataPath + "/UserGameStatus.dat");
     bf.Serialize (file, gameStatus);
     file.Close ();
 }
Exemple #21
0
 // Loads the progress the player made so far
 public static void loadProgress()
 {
     if (File.Exists(Application.persistentDataPath + "/progress.sg"))
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Open(Application.persistentDataPath + "/progress.sg", FileMode.Open);
         int[] scores = (int[])bf.Deserialize(file);
         score = scores[0];
         darkEnergy = scores[1];
         lightEnergy = scores[2];
         if (scores[3] == -1)
         {
             isDark = true;
             isLight = false;
         }
         else if (scores[3] == 1)
         {
             isDark = false;
             isLight = true;
         }
         else
         {
             isDark = false;
             isLight = false;
         }
         file.Close();
     }
 }
    // Serialize object
    public void OnBeforeSerialize()
    {
        // No need to serialize if the object is null
        // or declared nonserializable
        if (unserializable || unserializedObject == null)
            return;

        // Possible to loop over fields for serialization of (unity) non serializables
        // This will prevent this method from blowing up when the serializer hits non serializable fields
        // Possibly store all the fields in a dictionary of some kind? (increased memory usage, but more stable)
        // For now just check one type
        Type objType = unserializedObject.GetType();

        // Check surrogates for non serializable types
        if (!objType.IsSerializable)
        {
            if (!SurrogateHandler.GetSurrogate(ref unserializedObject))
            {
                Debug.Log("SerializableObject.Serialization: " + objType.ToString() + " is not a serializable type and has no surrogate");
                unserializable = true;
                return;
            }
        }

        // Serialize
        using(var stream = new MemoryStream())
        {
            var serializer = new BinaryFormatter();

            serializer.Serialize(stream, unserializedObject);
            byteArray = stream.ToArray();
        }

        //Debug.Log("Serialized Type: " + unserializedObject.GetType() + " | Value: " + unserializedObject.ToString());
    }
Exemple #23
0
    public void serialize()
    {
        height = GetComponent<Background>().height;
        width = GetComponent<Background>().width;
        start = GetComponent<Background>().start;
        end = GetComponent<Background>().end;

        dangerMap = GetComponent<DangerMap>().getDangerMap();
        var = GetComponent<DangerMap>().var;

        enemies = GetComponent<Enemies>().getEnemy();

        trace = GetComponent<Player>().getTrace();
        filteredTrace_a = GetComponent<Player>().get_filteredTrace_a();
        filteredTrace_b = GetComponent<Player>().get_filteredTrace_b();
        stepsize = GetComponent<Player>().stepsize;

        forecast_d = GetComponent<Forecast>().get_forecast_d();
        angle = GetComponent<Forecast>().angle;

        SerialObject obj = new SerialObject(width, height, start, end,
                                            dangerMap, var, enemies, trace,
                                            filteredTrace_a, filteredTrace_b, stepsize,
                                            forecast_d, angle);

        string file = dir + filePrefix + "_serial.xml";
        Stream stream = File.Open(file, FileMode.Create);

        BinaryFormatter formatter = new BinaryFormatter();

        formatter.Serialize(stream, obj);
        stream.Close();
    }
 //overwrites the file with a fresh save
 public void SaveGameData()
 {
     bf = new BinaryFormatter();
     fs = File.Create(Application.persistentDataPath + GAME_DATA_FILE);
     bf.Serialize(fs, gd);
     fs.Close();
 }
Exemple #25
0
	public static void MenuSavePbObject()
	{
		pb_Object[] selection = pbUtil.GetComponents<pb_Object>(Selection.transforms);
		int len = selection.Length;

		if(len < 1) return;

		string path = "";

		if(len == 1)
			path = EditorUtility.SaveFilePanel("Save ProBuilder Object", "", selection[0].name, "pbo");// "Save ProBuilder Object to File.");
		else
			path = EditorUtility.SaveFolderPanel("Save ProBuilder Objects to Folder", "", "");

		foreach(pb_Object pb in selection)
		{
			//Creates a new pb_SerializableObject object.
			pb_SerializableObject obj = new pb_SerializableObject(pb);

			//Opens a file and serializes the object into it in binary format.
			Stream stream = File.Open( len == 1 ? path : path + pb.name + ".pbo", FileMode.Create);

			BinaryFormatter formatter = new BinaryFormatter();

			formatter.Serialize(stream, obj);
			
			stream.Close();			
		}
	}
Exemple #26
0
    public void LoadInventory()
    {
        if(File.Exists(Application.persistentDataPath + "Inventory.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file_loc = File.Open(Application.persistentDataPath + "Inventory.dat",FileMode.Open);

            Inventory_Item_Info Inven = (Inventory_Item_Info)bf.Deserialize(file_loc);

            file_loc.Close();
            print (Inven.AllItems.Count);

            for(int i = 0; i < Inven.AllItems.Count; ++i)
            {
                print ("item Loaded:" + i);
                if(LoadItem(Inven.AllItems[i]))
                {
                    Inventory.Inven.AddExisingItem(LoadItem(Inven.AllItems[i]));
                }
                else
                {

                }
            }
        }
    }
Exemple #27
0
  public static void Main(String[] args) 
  {
    Console.WriteLine ("Fill MyList object with content\n");
    MyList l = new MyList();
    for (int x=0; x< 10; x++) 
    {
      Console.WriteLine (x);
      l.Add (x);
    } // end for
    Console.WriteLine("\nSerializing object graph to file {0}", FILENAME);
    Stream outFile = File.Open(FILENAME, FileMode.Create, FileAccess.ReadWrite);
    BinaryFormatter outFormat = new BinaryFormatter();
    outFormat.Serialize(outFile, l);
    outFile.Close();
    Console.WriteLine("Finished\n");

    Console.WriteLine("Deserializing object graph from file {0}", FILENAME);
    Stream inFile = File.Open(FILENAME, FileMode.Open, FileAccess.Read);
    BinaryFormatter inFormat = new BinaryFormatter();
    MyList templist = (MyList)inFormat.Deserialize(inFile);
    Console.WriteLine ("Finished\n");
    
    foreach (MyListItem mli in templist) 
    {
      Console.WriteLine ("List item number {0}, square root {1}", mli.Number, mli.Sqrt);
    } //foreach

    inFile.Close();
  } // end main
    private static object DeserializeObject(byte[] bytes)
    {
        var BinaryFormatter = new BinaryFormatter();
        var MemoryStream = new MemoryStream(bytes);

        return BinaryFormatter.Deserialize(MemoryStream);
    }
Exemple #29
0
    public void LoadHero()
    {
        HeroScript = Hero_Data.Hero.GetComponent<Hero_Data>();
        if(File.Exists(Application.persistentDataPath + "HeroInfo.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file_loc = File.Open(Application.persistentDataPath + "HeroInfo.dat",FileMode.Open);

            Hero_Info Hero = (Hero_Info)bf.Deserialize(file_loc);

            file_loc.Close();

            HeroScript.m_dGold = Hero.m_dGold;
            HeroScript.m_fAttack_Speed = Hero.m_fAttack_Speed;
            HeroScript.m_fDamage = Hero.m_fDamage;
            HeroScript.m_fHealth = Hero.m_fHealth;
            HeroScript.m_fHealth_Regen = Hero.m_fHealth_Regen;
            HeroScript.m_fMana = Hero.m_fMana;
            HeroScript.m_fMana_Regen = Hero.m_fMana_Regen;
            HeroScript.m_fMax_Health = Hero.m_fMax_Health;
            HeroScript.m_fMax_Mana = Hero.m_fMax_Mana;
            HeroScript.m_iCurrnet_Exp = Hero.m_iCurrnet_Exp;
            HeroScript.m_iExp_To_Level = Hero.m_iExp_To_Level;
            HeroScript.m_iStatPoints = Hero.m_iStatPoints;
        }
        else
        {

        }
    }
    // Button Assignment
    public void LoadButtonAssignment()
    {
        // Check if the file exists before proceeding
        if (File.Exists(Application.persistentDataPath + "/buttonAssignment.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/buttonAssignment.dat", FileMode.Open);

            // Deserialize creates a generic object that we must cast as ButtonData
            // This allows us to pull the data out of the file
            ButtonData data = (ButtonData)bf.Deserialize(file);
            // Close the file
            file.Close();

            left = data.GetButtonLeft();
            right = data.GetButtonRight();
            up = data.GetButtonUp();
            down = data.GetButtonDown();
            jump = data.GetButtonJump();
            fire1 = data.GetButtonFire1();
            fire2 = data.GetButtonFire2();
            fire3 = data.GetButtonFire3();
            quickFire = data.GetButtonQuickFire();
            submit = data.GetButtonSubmit();
            cancel = data.GetButtonCancel();
        }
    }
Exemple #31
0
        /// <summary>
        /// Creates a mesh from the specified data stream.
        /// </summary>
        /// <param name="stream">A Stream object that contains the data for this HalfedgeMesh object.</param>
        /// <returns>The mesh object this method creates.</returns>
        public static Mesh <TEdgeTraits, TFaceTraits, THalfedgeTraits, TVertexTraits> FromStream(Stream stream)
        {
            IFormatter formatter = new BinaryFormatter();

            return((Mesh <TEdgeTraits, TFaceTraits, THalfedgeTraits, TVertexTraits>)formatter.Deserialize(stream));
        }
Exemple #32
0
 public static object Deserialize(MemoryStream stream)
 {
     var binaryFormatter = new BinaryFormatter();
     stream.Seek(0, SeekOrigin.Begin);
     return binaryFormatter.Deserialize(stream);
 }
Exemple #33
0
        public static object GetObject(byte[] serializedObject)
        {
            BinaryFormatter serializer = new BinaryFormatter();

            return(serializer.Deserialize(new MemoryStream(serializedObject)));
        }
Exemple #34
0
        static void Main(string[] args)
        {
            Type type = Type.GetType(typeof(Flower).FullName);
            CustomSerealizble <Flower> serealiz = new CustomSerealizble <Flower>();
            Flower fl1 = new Flower();

            serealiz.Serializable("Binary.Binary", fl1, "Binary");
            Flower fl2 = (Flower)serealiz.DeSerializable("Binary.Binary", fl1, "Binary");

            serealiz.Serializable("SOAP.SOAP", fl1, "SOAP");
            fl2 = (Flower)serealiz.DeSerializable("SOAP.SOAP", fl1);
            serealiz.Serializable("JSON.JSON", fl1, "JSON");
            fl2 = (Flower)serealiz.DeSerializable("JSON.JSON", fl1, "JSON");
            serealiz.Serializable("XML.XML", fl1, "XML");
            fl2 = (Flower)serealiz.DeSerializable("XML.XML", fl1, "XML");
            DateTime newDate1 = new DateTime(2016, 12, 20);
            DateTime newDate2 = new DateTime(2017, 12, 20);
            DateTime newDate3 = new DateTime(2018, 12, 20);
            DateTime newDate4 = new DateTime(2019, 12, 20);

            Flower[] fl3 = new Flower[]
            {
                new Flower(newDate1),
                new Flower(newDate2),
                new Flower(newDate3),
                new Flower(newDate1),
            };
            Flower[] fl4 = new Flower[]
            {
                new Flower(),
                new Flower(),
                new Flower(),
                new Flower(),
            };
            List <Flower> list = new List <Flower>();

            foreach (var flow in fl3)
            {
                list.Add(flow);
            }
            List <Flower> list2     = new List <Flower>();
            SoapFormatter formatter = new SoapFormatter();

            using (FileStream file = new FileStream("SOAP.SOAP", FileMode.OpenOrCreate))
            {
                formatter.Serialize(file, fl3);

                file.Close();
            }
            using (FileStream file = new FileStream("SOAP.SOAP", FileMode.Open))
            {
                Flower[] fl5 = (Flower[])formatter.Deserialize(file);
                file.Close();
            }
            BinaryFormatter formatter2 = new BinaryFormatter();

            using (FileStream file = new FileStream("Binary.Binary", FileMode.Create))
            {
                formatter2.Serialize(file, fl3);
                file.Close();
            }
            using (FileStream file = new FileStream("Binary.Binary", FileMode.Open))
            {
                fl4 = (Flower[])formatter2.Deserialize(file);
                file.Close();
            }
            XmlSerializer xmlF = new XmlSerializer(typeof(Flower[]));

            using (FileStream file = new FileStream("XML2.txt", FileMode.OpenOrCreate))
            {
                xmlF.Serialize(file, fl3);
                file.Close();
            }
            using (FileStream file = new FileStream("XML2.txt", FileMode.Open))
            {
                fl4 = (Flower[])xmlF.Deserialize(file);
                file.Close();
            }
            using (StreamWriter writefile = new StreamWriter("json.json"))
            {
                writefile.Write(JsonConvert.SerializeObject(fl3));
                writefile.Close();
            }

            fl4 = JsonConvert.DeserializeObject <Flower[]>(File.ReadAllText("json.json"));



            // XPath
            XmlDocument doc = new XmlDocument();

            doc.Load("XPath.xml");

            XmlNodeList nodeList;
            XmlNode     root = doc.DocumentElement;

            nodeList = root.SelectNodes("descendant::book[author/last-name]");

            //Change the price on the books.
            foreach (XmlNode book in nodeList)
            {
                Console.WriteLine(book["author"].FirstChild.InnerText);
            }

            ///ling to xml

            XElement flowers = new XElement("Flowers"
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "2"), new XElement("Title", "Rose1"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "3"), new XElement("Title", "Rose2"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "5"), new XElement("Title", "Rose3"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "8"), new XElement("Title", "Rose4")));


            var res = flowers.Descendants("Flower").Where(x => Int32.Parse(x.Element("Age").Value) >= 5).Select(x => x.Element("Title").Value);

            foreach (var item in res)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
Exemple #35
0
        /// <summary>
        /// Loads in inventory cache file into the inventory structure. Note only valid to call after login has been successful.
        /// </summary>
        /// <param name="filename">Name of the cache file to load</param>
        /// <returns>The number of inventory items sucessfully reconstructed into the inventory node tree</returns>
        public int RestoreFromDisk(string filename)
        {
            List <InventoryNode> nodes = new List <InventoryNode>();
            int item_count             = 0;

            try
            {
                if (!File.Exists(filename))
                {
                    return(-1);
                }

                using (Stream stream = File.Open(filename, FileMode.Open))
                {
                    BinaryFormatter bformatter = new BinaryFormatter();

                    while (stream.Position < stream.Length)
                    {
                        OpenMetaverse.InventoryNode node = (InventoryNode)bformatter.Deserialize(stream);
                        nodes.Add(node);
                        item_count++;
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log("Error accessing inventory cache file :" + e.Message, Helpers.LogLevel.Error);
                return(-1);
            }

            Logger.Log("Read " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info);

            item_count = 0;
            List <InventoryNode> del_nodes     = new List <InventoryNode>(); //nodes that we have processed and will delete
            List <UUID>          dirty_folders = new List <UUID>();          // Tainted folders that we will not restore items into

            // Because we could get child nodes before parents we must itterate around and only add nodes who have
            // a parent already in the list because we must update both child and parent to link together
            // But sometimes we have seen orphin nodes due to bad/incomplete data when caching so we have an emergency abort route
            int stuck = 0;

            while (nodes.Count != 0 && stuck < 5)
            {
                foreach (InventoryNode node in nodes)
                {
                    InventoryNode pnode;
                    if (node.ParentID == UUID.Zero)
                    {
                        //We don't need the root nodes "My Inventory" etc as they will already exist for the correct
                        // user of this cache.
                        del_nodes.Add(node);
                        item_count--;
                    }
                    else if (Items.TryGetValue(node.Data.UUID, out pnode))
                    {
                        //We already have this it must be a folder
                        if (node.Data is InventoryFolder)
                        {
                            InventoryFolder cache_folder  = (InventoryFolder)node.Data;
                            InventoryFolder server_folder = (InventoryFolder)pnode.Data;

                            if (cache_folder.Version != server_folder.Version)
                            {
                                Logger.DebugLog("Inventory Cache/Server version mismatch on " + node.Data.Name + " " + cache_folder.Version.ToString() + " vs " + server_folder.Version.ToString());
                                pnode.NeedsUpdate = true;
                                dirty_folders.Add(node.Data.UUID);
                            }
                            else
                            {
                                pnode.NeedsUpdate = false;
                            }

                            del_nodes.Add(node);
                        }
                    }
                    else if (Items.TryGetValue(node.ParentID, out pnode))
                    {
                        if (node.Data != null)
                        {
                            // If node is folder, and it does not exist in skeleton, mark it as
                            // dirty and don't process nodes that belong to it
                            if (node.Data is InventoryFolder && !(Items.ContainsKey(node.Data.UUID)))
                            {
                                dirty_folders.Add(node.Data.UUID);
                            }

                            //Only add new items, this is most likely to be run at login time before any inventory
                            //nodes other than the root are populated. Don't add non existing folders.
                            if (!Items.ContainsKey(node.Data.UUID) && !dirty_folders.Contains(pnode.Data.UUID) && !(node.Data is InventoryFolder))
                            {
                                Items.Add(node.Data.UUID, node);
                                node.Parent = pnode;                   //Update this node with its parent
                                pnode.Nodes.Add(node.Data.UUID, node); // Add to the parents child list
                                item_count++;
                            }
                        }

                        del_nodes.Add(node);
                    }
                }

                if (del_nodes.Count == 0)
                {
                    stuck++;
                }
                else
                {
                    stuck = 0;
                }

                //Clean up processed nodes this loop around.
                foreach (InventoryNode node in del_nodes)
                {
                    nodes.Remove(node);
                }

                del_nodes.Clear();
            }

            Logger.Log("Reassembled " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info);
            return(item_count);
        }
Exemple #36
0
        static void Main(string[] args)
        {
            DateTime    date1 = new DateTime(1995, 1, 01);
            DateTime    date2 = new DateTime(2004, 1, 01);
            DateTime    date3 = new DateTime(2015, 1, 01);
            List <Book> books = new List <Book>();

            Book book = new Book
            {
                Name       = "1001 рецепт готовки бананов",
                Price      = 4000,
                AuthorName = "Д.Грин",
                Year       = date1
            };
            Book book2 = new Book
            {
                Name       = "Лом против всего",
                Price      = 10000,
                AuthorName = "Роберт Прайс",
                Year       = date2
            };
            Book book3 = new Book
            {
                Name       = "Как не угодить в яму",
                Price      = 3000,
                AuthorName = "М.Шельман",
                Year       = date3
            };

            books.Add(book);
            books.Add(book2);
            books.Add(book3);

            string driveName = "";

            DriveInfo[] drives = DriveInfo.GetDrives();


            for (int i = 0; i < drives.Length; i++)
            {
                Console.WriteLine($"{i}.{drives[i].Name}");
            }

            Console.WriteLine("Введите номер диска, на который будет записан файл");

            string driveNumberAsString = Console.ReadLine();

            int driveNumber = 0;

            if (!int.TryParse(driveNumberAsString, out driveNumber))
            {
                Console.WriteLine("Ошибка ввода, будет произведена запись на первый указанный диск.");
            }
            driveName = drives[driveNumber].Name;

            BinaryFormatter formatter = new BinaryFormatter();

            if (!Directory.Exists(driveName + @"/data"))
            {
                Directory.CreateDirectory(driveName + @"/data");
            }
            using (FileStream stream = File.Create(driveName + @"/data/book.bin"))
            {
                formatter.Serialize(stream, books);
            }

            using (FileStream stream = File.OpenRead(driveName + @"/data/book.bin"))
            {
                var resultPerson = formatter.Deserialize(stream) as List <Book>;
                int count        = 1;
                foreach (var element in resultPerson)
                {
                    Console.WriteLine(count + ". Название книги: " + element.Name);
                    Console.WriteLine("   Цена книги: " + element.Price);
                    Console.WriteLine("   Автор книги: " + element.AuthorName);
                    Console.WriteLine("   Год книги: " + element.Year.Year + "\n");
                    count++;
                }
            }


            Console.ReadLine();
        }
Exemple #37
0
        /// <summary>
        ///     Deserializes an object from file and returns a reference.
        /// </summary>
        /// <param name="fileName">name of the file to serialize to</param>
        /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param>
        /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param>
        /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param>
        /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns>
        public static object DeSerializeObject(string fileName, Type objectType, bool binarySerialization, bool throwExceptions)
        {
            object instance = null;

            if (!binarySerialization)
            {
                XmlReader     reader     = null;
                XmlSerializer serializer = null;
                FileStream    fs         = null;
                try
                {
                    // Create an instance of the XmlSerializer specifying type and namespace.
                    serializer = new XmlSerializer(objectType);

                    // A FileStream is needed to read the XML document.
                    fs     = new FileStream(fileName, FileMode.Open);
                    reader = new XmlTextReader(fs);

                    instance = serializer.Deserialize(reader);
                }
                catch (Exception ex)
                {
                    if (throwExceptions)
                    {
                        throw;
                    }

                    var message = ex.Message;
                    return(null);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }

                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
            else
            {
                BinaryFormatter serializer = null;
                FileStream      fs         = null;

                try
                {
                    serializer = new BinaryFormatter();
                    fs         = new FileStream(fileName, FileMode.Open);
                    instance   = serializer.Deserialize(fs);
                }
                catch
                {
                    return(null);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }

            return(instance);
        }
Exemple #38
0
        public override void Bad()
        {
            long data;

            data = long.MinValue; /* Initialize data */
            /* read input from WebClient */
            {
                WebClient    client = new WebClient();
                StreamReader sr     = null;
                try
                {
                    sr = new StreamReader(client.OpenRead("http://www.example.org/"));
                    /* FLAW: Read data from a web server with WebClient */

                    /* This will be reading the first "line" of the response body,
                     * which could be very long if there are no newlines in the HTML */
                    string stringNumber = sr.ReadLine();
                    if (stringNumber != null) // avoid NPD incidental warnings
                    {
                        try
                        {
                            data = long.Parse(stringNumber.Trim());
                        }
                        catch (FormatException exceptNumberFormat)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    /* clean up stream reading objects */
                    try
                    {
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing StreamReader");
                    }
                }
            }
            /* serialize data to a byte array */
            byte[] dataSerialized = null;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                using (var ms = new MemoryStream())
                {
                    bf.Serialize(ms, data);
                    dataSerialized = ms.ToArray();
                }
                CWE197_Numeric_Truncation_Error__long_NetClient_to_byte_75b.BadSink(dataSerialized);
            }
            catch (SerializationException exceptSerialize)
            {
                IO.Logger.Log(NLog.LogLevel.Warn, "Serialization exception in serialization", exceptSerialize);
            }
        }
Exemple #39
0
        /// <summary>
        /// Gets the next batch in a sequence.
        /// </summary>
        /// <param name="batchCode">Batch code value</param>
        /// <param name="nextBatchSequenceNumber">Sequence number of the next batch</param>
        /// <returns>Batch information</returns>
        public Batch GetNextBatch(Guid batchCode, Guid nextBatchSequenceNumber)
        {
            // Create the batch directory.
            var path = Path.Combine(_batchSpoolDirectory, batchCode.ToString());

            if (!Directory.Exists(path))
            {
                // no batch found.
                return(null);
            }

            string      headerFilePath = Path.Combine(path, BATCH_HEADER_FILENAME);
            BatchHeader header         = null;

            if (File.Exists(headerFilePath))
            {
                var headerFormatter = new BinaryFormatter();
                using (var fileStream = new FileStream(headerFilePath, FileMode.Open, FileAccess.Read))
                {
                    header = headerFormatter.Deserialize(fileStream) as BatchHeader;
                }
            }

            if (null == header)
            {
                // no header
                return(null);
            }

            // Get the batch file name from the header.
            string batchFile = header.BatchFileNames.Where(b => new Guid(b) == nextBatchSequenceNumber).FirstOrDefault();

            if (String.IsNullOrEmpty(batchFile))
            {
                // missing batch file.
                return(null);
            }

            string batchFilePath = Path.Combine(path, batchFile);
            Batch  batch         = null;

            if (File.Exists(batchFilePath))
            {
                var formatter = new BinaryFormatter();
                using (var fileStream = new FileStream(batchFilePath, FileMode.Open, FileAccess.Read))
                {
                    batch = formatter.Deserialize(fileStream) as Batch;
                }
            }

            if (null != batch)
            {
                string filePath = Path.Combine(path, batch.FileName);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                if (batch.IsLastBatch)
                {
                    // If this is the last batch then try to cleanup the directory.
                    CleanupBatchDirectory(path, headerFilePath, header);
                }
            }

            return(batch);
        }
Exemple #40
0
        /// <summary>
        /// Saves the mesh object to the specified stream.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> where the mesh will be saved.</param>
        public void Save(Stream stream)
        {
            IFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, this);
        }
 public static void Serialize(Stream stream, BinaryFormatter formatter)
 {
     lock (_lockObject) {
         formatter.Serialize(stream, _messages);
     }
 }
Exemple #42
0
        public override void OnLoadData()
        {
            if ((TrafficMod.Options & OptionsManager.ModOptions.RoadCustomizerTool) == OptionsManager.ModOptions.None)
                return;
                

            Logger.LogInfo("Loading road data. Time: " + Time.realtimeSinceStartup);
            byte[] data = serializableDataManager.LoadData(LANE_DATA_ID);
            if (data == null)
            {
                Logger.LogInfo("No road data to load.");
                return;
            }

            MemoryStream memStream = new MemoryStream();
            memStream.Write(data, 0, data.Length);
            memStream.Position = 0;

            BinaryFormatter binaryFormatter = new BinaryFormatter()
            {
                Binder = new LaneSerializationBinder()
            };
            try
            {
                LaneManager.sm_lanes = (Lane[]) binaryFormatter.Deserialize(memStream);
                    
                FastList<ushort> nodesList = new FastList<ushort>();
                foreach (Lane lane in LaneManager.sm_lanes)
                {
                    if (lane == null)
                        continue;

                    lane.UpdateArrows();
                    if (lane.ConnectionCount() > 0)
                        nodesList.Add(lane.m_nodeId);

                    if (lane.m_speed == 0)
                    {
                        NetSegment segment = NetManager.instance.m_segments.m_buffer[NetManager.instance.m_lanes.m_buffer[lane.m_laneId].m_segment];
                        NetInfo info = segment.Info;
                        uint l = segment.m_lanes;
                        int n = 0;
                        while (l != lane.m_laneId && n < info.m_lanes.Length)
                        {
                            l = NetManager.instance.m_lanes.m_buffer[l].m_nextLane;
                            n++;
                        }

                        if (n < info.m_lanes.Length)
                            lane.m_speed = info.m_lanes[n].m_speedLimit;
                    }

                }

                RoadCustomizerTool customizerTool = ToolsModifierControl.GetTool<RoadCustomizerTool>();
                foreach (ushort nodeId in nodesList)
                    customizerTool.SetNodeMarkers(nodeId);

                Logger.LogInfo("Finished loading road data. Time: " + Time.realtimeSinceStartup);
            }
            catch (Exception e)
            {
                Logger.LogError("Unexpected " + e.GetType().Name + " loading road data.");
            }
            finally
            {
                memStream.Close();
            }
        }
Exemple #43
0
 public TgcSocketSendMsg()
 {
     binaryFormatter = new BinaryFormatter();
     data            = new List <byte[]>();
 }
Exemple #44
0
        /// <summary>
        /// 获取客户端发送过来的数据
        /// </summary>
        /// <param name="obj"></param>
        private void GetRecieveData(object obj)
        {
            try
            {
                //客户端套接字
                if (obj is Socket)
                {
                    Socket clientSocket = obj as Socket;
                    //连接状态
                    while (clientSocket != null &&
                           clientSocket.Connected)
                    {
                        //IPEndPoint remoteEndPoint = (IPEndPoint)client.RemoteEndPoint;//服务器对客户端操作的地址加端口
                        //PC客户端所传数据
                        ConferenceClientAccept clientIncordingEntity = null;

                        List <byte> lists = new List <byte>();
callBack:
                        byte[] buffer = new byte[BUFFER_SIZE];

                        int count = clientSocket.Receive(buffer);//挂起操作


                        if (count == 0)
                        {
                            //客户端与服务器端断开连接
                            break;
                        }
                        if (count == BUFFER_SIZE)
                        {
                            lists.AddRange(buffer);
                        }

                        else if (count < BUFFER_SIZE)
                        {
                            byte[] dataless = new byte[count];
                            Array.Copy(buffer, dataless, count);
                            lists.AddRange(dataless);
                        }
                        if (clientSocket.Available != 0)
                        {
                            goto callBack;
                        }
                        byte[] data = lists.ToArray();
                        lists.Clear();
                        lists = null;

                        if (TCPDataAccroiding != null)
                        {
                            string MobilePhoneIM = Encoding.UTF8.GetString(buffer, 0, count);

                            this.TCPDataAccroiding(MobilePhoneIM, new Action <bool, string, string>((successed, conferenceName, selfUri) =>
                            {
                                if (successed)
                                {
                                    clientIncordingEntity = new ConferenceClientAccept()
                                    {
                                        ConferenceClientAcceptType = ConferenceClientAcceptType.ConferenceAudio, ConferenceName = conferenceName, SelfUri = "_" + selfUri
                                    };

                                    if (this.TCPDataArrival != null)
                                    {
                                        this.TCPDataArrival(new TcpDateEvent(clientSocket, clientIncordingEntity), SocketClientType.Android);
                                    }
                                }
                                else
                                {
                                    using (MemoryStream stream = new MemoryStream(data))
                                    {
                                        stream.Position           = 0;
                                        BinaryFormatter formatter = new BinaryFormatter();
                                        formatter.Binder          = new UBinder();
                                        var result = formatter.Deserialize(stream);
                                        Type type  = result.GetType();
                                        if (type.Equals(typeof(ConferenceClientAccept)))
                                        {
                                            clientIncordingEntity = result as ConferenceClientAccept;
                                            if (this.TCPDataArrival != null)
                                            {
                                                this.TCPDataArrival(new TcpDateEvent(clientSocket, clientIncordingEntity), SocketClientType.PC);
                                            }
                                        }
                                        stream.Flush();
                                    }
                                }
                            }));
                        }
                        else
                        {
                            using (MemoryStream stream = new MemoryStream(data))
                            {
                                stream.Position = 0;
                                BinaryFormatter formatter = new BinaryFormatter();
                                formatter.Binder = new UBinder();
                                var  result = formatter.Deserialize(stream);
                                Type type   = result.GetType();
                                if (type.Equals(typeof(ConferenceClientAccept)))
                                {
                                    clientIncordingEntity = result as ConferenceClientAccept;
                                    if (this.TCPDataArrival != null)
                                    {
                                        this.TCPDataArrival(new TcpDateEvent(clientSocket, clientIncordingEntity), SocketClientType.PC);
                                    }
                                }
                                stream.Flush();
                            }
                        }
                        Array.Clear(data, 0, data.Length);
                        data = null;
                    }
                    try
                    {
                        if (clientSocket != null)
                        {
                            //if (this.TCPDataArrival != null)
                            //{
                            //    this.TCPDataArrival(new TcpDateEvent(clientSocket, new PackageBase() { head = EPackageHead.Discon }));
                            //}
                            //服务器端释放已经断开的客户端连接Socket对象资源
                            Thread.Sleep(300);
                            if (clientSocket.Poll(10, SelectMode.SelectRead))
                            {
                                clientSocket.Shutdown(SocketShutdown.Both);
                            }
                            clientSocket.Close();
                            clientSocket = null;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManage.WriteLog(this.GetType(), ex);
                    }
                }
            }
            catch (Exception ex)
            {
                //LogManage.WriteLog(this.GetType(), ex);
            }
        }
Exemple #45
0
        static void Main(string[] args)
        {
            Console.WriteLine("\tTask 1");

            Console.WriteLine("---BinaryFormatter---");

            Figure figure = new Figure("black", false);

            //сериализация через бинарный формат
            BinaryFormatter formatter = new BinaryFormatter();

            //получаем поток, куда будем записывать сериализованный объект
            using (FileStream fs = new FileStream("figure.dat", FileMode.OpenOrCreate))
            {
                formatter.Serialize(fs, figure);
                Console.WriteLine("object is serialized");
            }

            //десериализация из файла figure.dat
            using (FileStream fs = new FileStream("figure.dat", FileMode.OpenOrCreate))
            {
                Figure newFigure = (Figure)formatter.Deserialize(fs);
                Console.WriteLine("object is deserialized");
                Console.WriteLine($"Objects color: {newFigure.Color} and stroke: {newFigure.Stroke}");
            }

            Console.WriteLine("---Json---");

            Decoration decoration = new Decoration(true, "pink");

            //сериализация через json формат
            DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Decoration));

            using (FileStream fs = new FileStream("decoration.json", FileMode.OpenOrCreate))
            {
                jsonFormatter.WriteObject(fs, decoration);
                Console.WriteLine("object is serialized");
            }
            //десериализация
            using (FileStream fs = new FileStream("decoration.json", FileMode.OpenOrCreate))
            {
                Decoration newDecoration = (Decoration)jsonFormatter.ReadObject(fs);
                Console.WriteLine("object is deserialized");
                Console.WriteLine($"Objects have decorations: {newDecoration.Decor} and Background-color: {newDecoration.BackgroundColor}");
            }



            Console.WriteLine("---XML---");

            Decoration decoration2 = new Decoration(false, "white");

            //сериализация через xml формат
            XmlSerializer xmlFormatter = new XmlSerializer(typeof(Decoration));

            using (FileStream fs = new FileStream("decoration.xml", FileMode.OpenOrCreate))
            {
                xmlFormatter.Serialize(fs, decoration2);
                Console.WriteLine("object is serialized");
            }
            //десериализация
            using (FileStream fs = new FileStream("decoration.xml", FileMode.OpenOrCreate))
            {
                Decoration newDecoration2 = xmlFormatter.Deserialize(fs) as Decoration;
                Console.WriteLine("object is deserialized");
                Console.WriteLine($"Objects have decorations: {newDecoration2.Decor} and Background-color: {newDecoration2.BackgroundColor}");
            }



            Console.WriteLine("---SOAP---");

            Decoration decoration3 = new Decoration(true, "black");

            //сериализация через soap формат
            SoapFormatter soapFormatter = new SoapFormatter();

            using (FileStream fs = new FileStream("decoration.soap", FileMode.OpenOrCreate))
            {
                soapFormatter.Serialize(fs, decoration3);
                Console.WriteLine("object is serialized");
            }
            // десериализация
            using (FileStream fs = new FileStream("decoration.soap", FileMode.OpenOrCreate))
            {
                Decoration newDecoration3 = (Decoration)soapFormatter.Deserialize(fs);
                Console.WriteLine("object is deserialized");
                Console.WriteLine($"Objects have decorations: {newDecoration3.Decor} and Background-color: {newDecoration3.BackgroundColor}");
            }



            Console.WriteLine("\n\tTask 2");

            //сериализация/десериализация массива объектов
            Figure figure2 = new Figure("white", true);
            Figure figure3 = new Figure("gray", true);
            Figure figure4 = new Figure("blue", false);

            Figure[] array = new Figure[] { figure2, figure3, figure4 };

            //сериализация через бинарный формат
            BinaryFormatter formatterArrays = new BinaryFormatter();

            //получаем поток, куда будем записывать сериализованный объект
            using (FileStream fs = new FileStream("array.dat", FileMode.OpenOrCreate))
            {
                formatterArrays.Serialize(fs, array);
                Console.WriteLine("objects is serialized");
            }

            //десериализация из файла array.dat
            using (FileStream fs = new FileStream("array.dat", FileMode.OpenOrCreate))
            {
                Figure[] newFigureArray = (Figure[])formatterArrays.Deserialize(fs);
                Console.WriteLine("objects is deserialized");
                foreach (Figure fig in newFigureArray)
                {
                    Console.WriteLine($"Objects color: {fig.Color} and stroke: {fig.Stroke}");
                }
            }


            Console.WriteLine("\n\tTask 3");

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load("decoration.xml");
            XmlElement xRoot = xDoc.DocumentElement;

            //выбор всех дочерних узлов
            XmlNodeList childnodes = xRoot.SelectNodes("*");

            foreach (XmlNode n in childnodes)
            {
                Console.WriteLine(n.OuterXml);
            }


            Console.WriteLine("\n\tTask 4");

            XDocument xdoc = new XDocument();

            //создаем первый элемент
            XElement student1 = new XElement("student");
            //создаем атрибуты
            XAttribute studentsNameAttr   = new XAttribute("name", "Yana");
            XAttribute studentsCourseAttr = new XAttribute("course", 2);

            //добавляем атрибуты в первый элемент
            student1.Add(studentsNameAttr);
            student1.Add(studentsCourseAttr);

            //создаем второй элемент
            XElement student2 = new XElement("student");
            //создаем атрибуты
            XAttribute students2NameAttr   = new XAttribute("name", "Yuliana");
            XAttribute students2CourseAttr = new XAttribute("course", 3);

            //добавляем атрибуты во второй элемент
            student2.Add(students2NameAttr);
            student2.Add(students2CourseAttr);


            //создаем корневой элемент
            XElement students = new XElement("students");

            //добавляем в корневой элемент
            students.Add(student1);
            students.Add(student2);
            //добавляем корневой элемент в документ
            xdoc.Add(students);
            //сохраняем документ
            xdoc.Save("students.xml");

            XDocument xdoc2 = XDocument.Load("students.xml");
            var       items = from st in xdoc2.Element("students").Elements("student")
                              where st.Attribute("course").Value == "2"
                              select new Student
            {
                name   = st.Attribute("name").Value,
                course = st.Attribute("course").Value
            };

            foreach (var item in items)
            {
                Console.WriteLine($"Student: {item.name} Course: {item.course}");
            }
        }
Exemple #46
0
 private static T Deserialize<T>(Stream stream)
 {
     IFormatter formatter = new BinaryFormatter();
     stream.Position = 0;
     return (T)formatter.Deserialize(stream);
 }
Exemple #47
0
        public void ReCalcNodeSRDH_Test()
        {
            int    numWD = 16;
            string DB_Load_LC_Before_Met = testingFolder + "\\Test_Load_LC_Before_Met.cfm";
            string DB_Load_LC_After_Met  = testingFolder + "\\Test_Load_LC_After_Met.cfm";

            NodeCollection  nodeList   = new NodeCollection();
            BinaryFormatter bin        = new BinaryFormatter();
            string          connBefore = nodeList.GetDB_ConnectionString(DB_Load_LC_Before_Met);
            string          connAfter  = nodeList.GetDB_ConnectionString(DB_Load_LC_After_Met);

            Nodes[] LC_Load_Before_Met = new Nodes[0]; // array of Nodes with SRDH calcs from model where Land Cover was loaded before the met import and map generation
            Nodes[] LC_Load_After_Met  = new Nodes[0]; // same as above but from model where Land Cover was loaded after the met import and map generation

            // Grab all Nodes with SRDH calcs from 'LC Load Before' model
            using (var context = new Continuum_EDMContainer(connBefore))
            {
                var node_db = from N in context.Node_table.Include("expo") select N;

                foreach (var N in node_db)
                {
                    int numRadii = N.expo.Count;

                    for (int i = 0; i < numRadii; i++)
                    {
                        if (N.expo.ElementAt(i).SR_Array != null)
                        {
                            int numNodes = LC_Load_Before_Met.Length;
                            Array.Resize(ref LC_Load_Before_Met, numNodes + 1);
                            LC_Load_Before_Met[numNodes]      = new Nodes();
                            LC_Load_Before_Met[numNodes].UTMX = N.UTMX;
                            LC_Load_Before_Met[numNodes].UTMY = N.UTMY;
                            LC_Load_Before_Met[numNodes].elev = N.elev;

                            MemoryStream MS3 = new MemoryStream(N.expo.ElementAt(i).SR_Array);
                            LC_Load_Before_Met[numNodes].AddExposure(N.expo.ElementAt(i).radius, N.expo.ElementAt(i).exponent, 1, numWD);
                            LC_Load_Before_Met[numNodes].expo[0].SR = new double[numWD];
                            LC_Load_Before_Met[numNodes].expo[0].SR = (double[])bin.Deserialize(MS3);

                            MS3 = new MemoryStream(N.expo.ElementAt(i).DH_Array);
                            LC_Load_Before_Met[numNodes].expo[0].dispH = new double[numWD];
                            LC_Load_Before_Met[numNodes].expo[0].dispH = (double[])bin.Deserialize(MS3);
                        }
                    }
                }
            }

            // Grab all Nodes with SRDH calcs from 'LC Load After' model
            using (var context = new Continuum_EDMContainer(connAfter))
            {
                var node_db = from N in context.Node_table.Include("expo") select N;

                foreach (var N in node_db)
                {
                    int numRadii = N.expo.Count;

                    for (int i = 0; i < numRadii; i++)
                    {
                        if (N.expo.ElementAt(i).SR_Array != null)
                        {
                            int numNodes = LC_Load_After_Met.Length;
                            Array.Resize(ref LC_Load_After_Met, numNodes + 1);
                            LC_Load_After_Met[numNodes]      = new Nodes();
                            LC_Load_After_Met[numNodes].UTMX = N.UTMX;
                            LC_Load_After_Met[numNodes].UTMY = N.UTMY;
                            LC_Load_After_Met[numNodes].elev = N.elev;

                            MemoryStream MS3 = new MemoryStream(N.expo.ElementAt(i).SR_Array);
                            LC_Load_After_Met[numNodes].AddExposure(N.expo.ElementAt(i).radius, N.expo.ElementAt(i).exponent, 1, numWD);
                            LC_Load_After_Met[numNodes].expo[0].SR = new double[numWD];
                            LC_Load_After_Met[numNodes].expo[0].SR = (double[])bin.Deserialize(MS3);

                            MS3 = new MemoryStream(N.expo.ElementAt(i).DH_Array);
                            LC_Load_After_Met[numNodes].expo[0].dispH = new double[numWD];
                            LC_Load_After_Met[numNodes].expo[0].dispH = (double[])bin.Deserialize(MS3);
                        }
                    }
                }
            }

            // Loop through nodes LC_Load_Before_Met and find same coords in LC_Load_After_Met and compare SR/DH
            for (int i = 0; i < LC_Load_Before_Met.Length; i++)
            {
                for (int j = 0; j < LC_Load_After_Met.Length; j++)
                {
                    if (LC_Load_Before_Met[i].UTMX == LC_Load_After_Met[j].UTMX && LC_Load_Before_Met[i].UTMY == LC_Load_After_Met[j].UTMY && LC_Load_Before_Met[i].expo[0].radius == LC_Load_After_Met[j].expo[0].radius)
                    {
                        for (int k = 0; k < numWD; k++)
                        {
                            Assert.AreEqual(LC_Load_Before_Met[i].expo[0].SR[k], LC_Load_After_Met[j].expo[0].SR[k], 0.00001, "Different SR" + LC_Load_Before_Met[i].UTMX.ToString() + "," + LC_Load_Before_Met[i].UTMY.ToString());
                            Assert.AreEqual(LC_Load_Before_Met[i].expo[0].dispH[k], LC_Load_After_Met[j].expo[0].dispH[k], 0.00001, "Different SR" + LC_Load_Before_Met[i].UTMX.ToString() + "," + LC_Load_Before_Met[i].UTMY.ToString());
                        }
                        break;
                    }
                }
            }
        }
Exemple #48
0
 static void Serialize(ref BinaryFormatter bf, ref FileStream file, int version, bool save)
 {
     SerializeGameController(ref bf, ref file, version, save);
     SerializeDungeonSceneController(ref bf, ref file, version, save);
     SerializeStatisticKeeper(ref bf, ref file, version, save);
 }
        //Export excel as json
        public byte[] ExportFileAsJson(byte[] file)
        {
            try
            {
                Node startNode = new Node(), aux, lastNode = startNode, endNode = null;
                startNode.name = "ROOT";

                byte[]        bin       = file;
                List <string> excelData = new List <string>();


                //create a new Excel package in a memorystream
                using (MemoryStream stream = new MemoryStream(bin))
                    using (ExcelPackage excelPackage = new ExcelPackage(stream))
                    {
                        //loop all worksheets
                        foreach (ExcelWorksheet worksheet in excelPackage.Workbook.Worksheets)
                        {
                            //loop all rows
                            for (int i = 2; i <= worksheet.Dimension.End.Row; i++)
                            {
                                //loop all columns in a row
                                for (int j = worksheet.Dimension.Start.Column; j <= worksheet.Dimension.End.Column; j++)
                                {
                                    //add the cell data to the List
                                    if (worksheet.Cells[i, j].Value != null)
                                    {
                                        string[] rowReader;
                                        //check if first or second column
                                        if (j % 2 != 0)
                                        {
                                            //split first row by '.'
                                            rowReader = worksheet.Cells[i, j].Value.ToString().Split('.');

                                            for (int k = 0; k < rowReader.Length; k++)
                                            {
                                                if (!lastNode.childs.ContainsKey(rowReader[k]))
                                                {
                                                    aux           = new Node();
                                                    aux.name      = rowReader[k];
                                                    aux.parent    = lastNode;
                                                    aux.height    = aux.parent.height + 1;
                                                    aux.getNumber = lastNode.childsNumber + 1;
                                                    lastNode.childs.Add(aux.name, aux);
                                                    lastNode.childsNumber++;
                                                    lastNode = aux;
                                                    endNode  = aux;
                                                }
                                                else
                                                {
                                                    lastNode = lastNode.childs[rowReader[k]];
                                                    endNode  = lastNode;
                                                }
                                            }

                                            lastNode = startNode;
                                        }
                                        else
                                        {
                                            endNode.value = worksheet.Cells[i, j].Value.ToString();
                                        }
                                    }
                                }
                            }
                        }
                    }

                // Set a variable to the Documents path.
                string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                BinaryFormatter bf = new BinaryFormatter();
                using (var convertByte = new MemoryStream())
                {
                    string testFail = PrintTree(startNode, true, startNode.childsNumber);
                    Console.WriteLine(testFail);
                    //Convert tree to json in string
                    //Convert the string to json object
                    JObject o = JObject.Parse(PrintTree(startNode, true, startNode.childsNumber));

                    bf.Serialize(convertByte, JsonConvert.SerializeObject(o));
                    return(convertByte.ToArray());
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error! Something went wrong!" + e);
            }
        }
Exemple #50
0
        static void Main(string[] args)
        {
            //---task1
            Sapper          sp1 = new Sapper(true, false, "arcada", "9.0", 235, 500, 211);
            BinaryFormatter bf  = new BinaryFormatter();

            using (FileStream fs = new FileStream("Serl1.dat", FileMode.OpenOrCreate))
            {
                bf.Serialize(fs, sp1);
            }

            using (FileStream fs = new FileStream("Serl1.dat", FileMode.Open, FileAccess.Read))
            {
                Sapper sp2 = (Sapper)bf.Deserialize(fs);
            }

            SoapFormatter sf = new SoapFormatter();

            using (FileStream fs = new FileStream("Serl2.soap", FileMode.OpenOrCreate))
            {
                sf.Serialize(fs, sp1);
            }

            using (FileStream fs = new FileStream("Serl2.soap", FileMode.OpenOrCreate))
            {
                Sapper s3 = (Sapper)sf.Deserialize(fs);
            }


            XmlSerializer xs = new XmlSerializer(typeof(Sapper));

            using (FileStream fs = new FileStream("Serl3.xml", FileMode.OpenOrCreate))
            {
                xs.Serialize(fs, sp1);
            }

            using (FileStream fs = new FileStream("Serl3.xml", FileMode.OpenOrCreate))
            {
                Sapper s4 = (Sapper)xs.Deserialize(fs);
            }

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Sapper));

            using (FileStream fs = new FileStream("Serl4.json", FileMode.OpenOrCreate))
            {
                js.WriteObject(fs, sp1);
            }

            using (FileStream fs = new FileStream("Serl4.json", FileMode.OpenOrCreate))
            {
                Sapper sp4 = (Sapper)js.ReadObject(fs);
            }

            //---task2

            List <Sapper> spcl = new List <Sapper>()
            {
                new Sapper(true, false, "arcada", "9.0", 235, 500, 211),
                new Sapper(true, false, "arcada", "11.0", 400, 500, 211),
                new Sapper(true, false, "arcada", "8.0", 235, 1500, 211),
                new Sapper(true, false, "arcada", "18.0", 235, 500, 211)
            };

            DataContractJsonSerializer jsn = new DataContractJsonSerializer(typeof(List <Sapper>));

            using (FileStream fs = new FileStream("Serl5.json", FileMode.OpenOrCreate))
            {
                jsn.WriteObject(fs, spcl);
            }

            using (FileStream fs = new FileStream("Serl5.json", FileMode.OpenOrCreate))
            {
                List <Sapper> sp4 = (List <Sapper>)jsn.ReadObject(fs);
            }

            //---task3

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load("Serl3.xml");
            XmlElement  root  = xDoc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("*");

            foreach (XmlNode i in nodes)
            {
                Console.WriteLine(i);
            }
            Console.WriteLine();
            XmlNodeList nodes2 = root.SelectNodes("fieldSize");

            foreach (XmlNode i in nodes2)
            {
                Console.WriteLine(i);
            }

            //---task4

            XDocument  xdoc  = new XDocument();
            XElement   book  = new XElement("Book");
            XAttribute name  = new XAttribute("name", "Чистый код");
            XElement   price = new XElement("Price", "1200");

            book.Add(name);
            book.Add(price);

            XElement xroot = new XElement("lib");

            xroot.Add(book);
            xdoc.Add(xroot);
            xdoc.Save("data.xml");

            var result = from c in xdoc.Descendants("book") select new { title = c.Attribute("title").Value, c.Element("price").Value };

            Console.Read();
        }
Exemple #51
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["LoginCookie"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
            }

            if (!IsPostBack && Session["SettingsObject"] != null)
            {
                Byte[] byteArray = (Byte[])Session["SettingsObject"];

                BinaryFormatter deSerializer = new BinaryFormatter();

                MemoryStream memStream = new MemoryStream(byteArray);



                SettingsOBJ settingsOBJ = (SettingsOBJ)deSerializer.Deserialize(memStream);

                ddLoginSettings.SelectedValue     = settingsOBJ.Login;
                ddPhotosSettings.SelectedValue    = settingsOBJ.Photos;
                ddPProfileSettings0.SelectedValue = settingsOBJ.Profile;
                ddContactSettings.SelectedValue   = settingsOBJ.Personal;
            }
            else if (!IsPostBack && Session["SettingsObject"] == null)
            {
                HttpCookie myCookie = Request.Cookies["LoginCookie"];
                GetAllSettings.CommandType = CommandType.StoredProcedure;
                GetAllSettings.CommandText = "TP_GetAllSettings";
                string a = myCookie.Values["Email"].ToString();
                GetAllSettings.Parameters.AddWithValue("@Email", myCookie.Values["Email"].ToString());
                SqlParameter outputPar1 = new SqlParameter("@LoginSetting", SqlDbType.VarChar, 100);
                outputPar1.Direction = ParameterDirection.Output;
                GetAllSettings.Parameters.Add(outputPar1);
                SqlParameter outputPar2 = new SqlParameter("@ProfileSetting", SqlDbType.VarChar, 100);
                outputPar2.Direction = ParameterDirection.Output;
                GetAllSettings.Parameters.Add(outputPar2);
                SqlParameter outputPar3 = new SqlParameter("@PhotoSetting", SqlDbType.VarChar, 100);
                outputPar3.Direction = ParameterDirection.Output;
                GetAllSettings.Parameters.Add(outputPar3);
                SqlParameter outputPar4 = new SqlParameter("@PersonalSetting", SqlDbType.VarChar, 100);
                outputPar4.Direction = ParameterDirection.Output;
                GetAllSettings.Parameters.Add(outputPar4);
                objDB.GetDataSetUsingCmdObj(GetAllSettings);

                // Serialize the CreditCard object
                SettingsOBJ settings = new SettingsOBJ();
                settings.Login                    = GetAllSettings.Parameters["@LoginSetting"].Value.ToString();
                settings.Photos                   = GetAllSettings.Parameters["@PhotoSetting"].Value.ToString();
                settings.Profile                  = GetAllSettings.Parameters["@ProfileSetting"].Value.ToString();
                settings.Personal                 = GetAllSettings.Parameters["@PersonalSetting"].Value.ToString();
                ddLoginSettings.SelectedValue     = GetAllSettings.Parameters["@LoginSetting"].Value.ToString();
                ddPhotosSettings.SelectedValue    = GetAllSettings.Parameters["@PhotoSetting"].Value.ToString();
                ddPProfileSettings0.SelectedValue = GetAllSettings.Parameters["@ProfileSetting"].Value.ToString();
                ddContactSettings.SelectedValue   = GetAllSettings.Parameters["@PersonalSetting"].Value.ToString();
                BinaryFormatter serializer = new BinaryFormatter();
                MemoryStream    memStream  = new MemoryStream();
                Byte[]          byteArray;
                serializer.Serialize(memStream, settings);
                byteArray = memStream.ToArray();
                Session["SettingsObject"] = byteArray;
            }
        }
Exemple #52
0
        public static Player Load(out bool newP)
        {
            newP = false;
            Console.Clear();
            string[]      paths   = Directory.GetDirectories("saves");
            List <Player> players = new List <Player>();
            int           idCount = 0;

            BinaryFormatter binForm = new BinaryFormatter();

            foreach (string p in paths)
            {
                FileStream file   = File.Open(p, FileMode.Open);
                Player     player = (Player)binForm.Deserialize(file); // problem
                file.Close();
                players.Add(player);
            }

            idCount = players.Count;

            while (true)
            {
                Console.Clear();
                Print("Choose your Saved Player: ");

                foreach (Player p in players)
                {
                    Console.WriteLine(p.id + ": " + p.name);
                }

                Print("Please input player name or ID (ID:# or playername) Additionally. 'create' will start a new save!");
                string[] data = Console.ReadLine().Split(':');

                try
                {
                    if (data[0] == "ID")
                    {
                        if (int.TryParse(data[1], out int id))
                        {
                            foreach (Player player in players)
                            {
                                if (player.id == id)
                                {
                                    return(player);
                                }
                            }
                            Console.WriteLine("There is no player with that ID!");
                            Console.ReadKey();
                        }
                        else
                        {
                            Console.WriteLine("Your ID needs to be a number! Press any key to try again.");
                            Console.ReadKey();
                        }
                    }
                    else if (data[0] == "create")
                    {
                        Player newPlayer = NewStart(idCount);
                        newP = true;
                        return(newPlayer);
                    }
                    else
                    {
                        foreach (Player player in players)
                        {
                            if (player.name == data[0])
                            {
                                return(player);
                            }
                        }
                        Console.WriteLine("There is no player with that name!");
                        Console.ReadKey();
                    }
                }
                catch (IndexOutOfRangeException)
                {
                    Console.WriteLine("Your ID needs to be a number! Press any key to try again.");
                    Console.ReadKey();
                }
            }
        }
Exemple #53
0
        static void Main(string[] args)
        {
            var timer   = new Stopwatch();
            var logic   = new RedisLogic();
            var dataGen = new RandomData();

            //logic.SetStringData("basicCall", "Hello world");

            //var x = logic.GetData<string>("basicCall");

            //Console.WriteLine(x);

            //x = logic.GetData<string>("basicCall");

            //Console.WriteLine(x);

            //var y = logic.GetAllKeys();

            //Console.WriteLine(string.Join(", ", y));

            var data     = dataGen.GetRandomData(10);
            var saveData = (from d in data
                            select JsonConvert.SerializeObject(d)).ToList();

            //timer.Start();
            //logic.SetListData("people", saveData);
            //timer.Stop();
            //Console.WriteLine($"Adding {saveData.Count} rows took {timer.ElapsedMilliseconds}ms.");

            //timer.Restart();
            //var z = logic.GetListData("people");
            //timer.Stop();

            //Console.WriteLine($"Getting {z.Count} rows took {timer.ElapsedMilliseconds}ms.");

            ////Check speed of geting list data
            //for (int i = 0; i < 10; i++)
            //{
            //    data = dataGen.GetRandomData(2000);
            //    saveData = (from d in data
            //                select JsonConvert.SerializeObject(d)).ToList();

            //    logic.SetListData("people", saveData);

            //    timer.Restart();
            //    z = logic.GetListData("people");
            //    timer.Stop();

            //    Console.WriteLine($"Getting {z.Count} rows took {timer.ElapsedMilliseconds}ms.");
            //}

            //var u = new List<string>();
            ////Check speed of geting hash data
            //for (int i = 0; i < 10; i++)
            //{
            //    var junk = dataGen.RandomHashData(2000);
            //    logic.SetHashData("junk", junk);

            //    timer.Restart();
            //    u = logic.GetHashValues("junk");
            //    timer.Stop();

            //    Console.WriteLine($"Getting {u.Count} hash values took {timer.ElapsedMilliseconds}ms.");
            //}

            //timer.Restart();
            //var q = logic.GetHashKeys("junk");
            //timer.Stop();

            //Console.WriteLine($"Getting {q.Count} hash keys took {timer.ElapsedMilliseconds}ms.");

            //timer.Restart();
            //var e = logic.GetSingleHashValue("junk", q.First());
            //timer.Stop();
            //Console.WriteLine($"Getting specific hash value took {timer.ElapsedMilliseconds}ms.");

            //saveData.Clear();

            //Testing pipelinging speed
            //for (int i = 0; i < 1; i++)
            //{
            //    data = dataGen.GetRandomData(2000);
            //    saveData.AddRange((from d in data
            //                       select JsonConvert.SerializeObject(d)).ToList());
            //}

            //timer.Restart();
            //logic.SetListData("pipe", saveData.GetRange(0, 3));
            //timer.Stop();

            //Console.WriteLine($"Adding {saveData.Count} rows took {timer.ElapsedMilliseconds}ms.");
            //logic.SetListPipeline("reg", saveData);
            //logic.SetListPipelineAsParallel("para", saveData);

            //var reg = new List<long>();
            //var asParallels = new List<long>();
            //for (int i = 0; i < 10; i++)
            //{
            //    timer.Restart();
            //    logic.SetListPipeline("reg", saveData);
            //    timer.Stop();
            //    reg.Add(timer.ElapsedMilliseconds);

            //    timer.Restart();
            //    logic.SetListPipelineAsParallel("para", saveData);
            //    timer.Stop();
            //    asParallels.Add(timer.ElapsedMilliseconds);
            //}

            //Console.WriteLine($"Adding {saveData.Count} rows regular took {reg.Average()}ms.");
            //Console.WriteLine($"Adding {saveData.Count} rows asParallel took {asParallels.Average()}ms.");

            //timer.Restart();
            //var w = logic.GetListData("pipe");
            //timer.Stop();

            //Console.WriteLine($"Getting {w.Count} rows pipelined took {timer.ElapsedMilliseconds}ms.");

            var seraldata = new List <PersonData>();

            Parallel.For(0, 10, i =>
            {
                seraldata.AddRange(dataGen.RandomPersonData(2000));
            });

            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream    ms = new MemoryStream();

            byte[] Array;
            bf.Serialize(ms, seraldata);
            Array = ms.ToArray();
            int startSize = Array.Length;

            var l4Time  = new List <long>();
            var l4Size  = new List <long>();
            var msgTime = new List <long>();
            var msgSize = new List <long>();

            for (int i = 0; i < 100; i++)
            {
                timer.Restart();
                var lv4 = LZ4MessagePackSerializer.Serialize(seraldata);
                timer.Stop();
                l4Time.Add(timer.ElapsedMilliseconds);
                l4Size.Add(lv4.LongLength);

                timer.Restart();
                var megPak = MessagePackSerializer.Serialize(seraldata);
                timer.Stop();
                msgTime.Add(timer.ElapsedMilliseconds);
                msgSize.Add(megPak.LongLength);
            }
            Console.WriteLine($"Stating size {(startSize / 1024) / 1024} mb");
            Console.WriteLine($"Lz4 serialization took {l4Time.Average()}ms and a size of {(l4Size.Average() / 1024) / 1024} mb");
            Console.WriteLine($"Messagepack serialization took {msgTime.Average()}ms and a size of {(msgSize.Average() / 1024) / 1024} mb");
            Console.WriteLine($"lz4 took { msgTime.Average() - l4Time.Average()} less time.");
            Console.WriteLine($"Lz4 is {((msgSize.Average() - l4Size.Average()) / 1024) / 1024} smaller.");
            Console.WriteLine($"Lz4 shunk in size by {(l4Size.Average() / startSize) * 100} %");
            Console.WriteLine($"MsgPack shunk in size by {(msgSize.Average() / startSize) * 100} %");

            timer.Restart();
            var ser = seraldata.AsParallel().Select((x, i) => new { Index = i, Value = MessagePackSerializer.Serialize(x) }).ToList();

            timer.Stop();
            Console.WriteLine($"Serializing {ser.Count} rows in plinq took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            ser = seraldata.Select((x, i) => new { Index = i, Value = MessagePackSerializer.Serialize(x) }).ToList();
            timer.Stop();
            Console.WriteLine($"Serializing {ser.Count} rows in linq took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            logic.SetHastPipeline("serial", seraldata);
            timer.Stop();
            Console.WriteLine($"Setting {seraldata.Count} rows using serialization took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            logic.SetHashPipeline("pipehash", seraldata);
            timer.Stop();
            Console.WriteLine($"Setting {seraldata.Count} rows hash took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            logic.SetHastAsParallelPipeline("serialMulti", seraldata);
            timer.Stop();
            Console.WriteLine($"Setting {seraldata.Count} rows parallazied serialization took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            var serializedData = logic.GetHashSerialValues("serial");
            var deserial       = serializedData.AsParallel().Select(x => MessagePackSerializer.Deserialize <PersonData>(x));

            timer.Stop();
            Console.WriteLine($"Deserializing {seraldata.Count} rows plinq took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            var sdata = logic.GetHashPersonValues("serialMulti");

            timer.Stop();
            Console.WriteLine($"Deserializing {sdata.Count} rows inline took {timer.ElapsedMilliseconds}ms.");

            timer.Restart();
            //cleanup
            logic.DeleteData("basicCall");
            logic.DeleteData("people");
            logic.DeleteData("junk");
            logic.DeleteData("pipe");
            logic.DeleteData("para");
            logic.DeleteData("reg");
            logic.DeleteData("serial");
            logic.DeleteData("pipehash");
            logic.DeleteData("serialMulti");
            logic.DeleteData("parallel");
            timer.Stop();
            Console.WriteLine($"Clean up took {timer.ElapsedMilliseconds}ms.");
            Console.WriteLine($"Press enter to exit.");
            var t = Console.ReadLine();
        }
Exemple #54
0
    /// <summary>
    /// Saves the current game
    /// </summary>
    public static void Save()
    {
        SaveGameData data = new SaveGameData();
        string       path = null;

        if (player != null)
        {
            data.playerPosX = player.transform.position.x;
            data.playerPosY = player.transform.position.y;
            data.playerPosZ = player.transform.position.z;
        }
        if (invCon != null)
        {
            data.playerInventory      = invCon.GetInventory();
            data.playerInventoryCount = invCon.GetInventoryCount();
        }
        if (grid != null)
        {
            //int[,] ground = grid.map;
            //for (int i = 0; i < ground.Length; i++)
            //{
            //    //for (int j = 0; j < ground.GetLength(i); j++)
            //    //{
            //    //    //For this to work at all I need either a multidimensional array using
            //    //    //a gameobject array or I need a way to get the tile from the JDGroundSpawner class!!

            //    //    //get the type of each tile
            //    //    //make a switch statement to switch each type to a string
            //    //}
            //}
        }

        if (save1)
        {
            path = "save1.zenMoon";
        }
        else if (save2)
        {
            path = "save2.zenMoon";
        }

        FileStream fs = null;

        try
        {
            fs = new FileStream(path, FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, data);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
    }
        private void ProcessCallbackRequest(object socket)
        {
            logger.LogInfo("new thread created to process callback request");

            try
            {
                using (Socket sock = (Socket)socket)
                    using (var s = new NetworkStream(sock))
                    {
                        while (true)
                        {
                            try
                            {
                                string cmd = SerDe.ReadString(s);
                                if (cmd == "close")
                                {
                                    logger.LogInfo("receive close cmd from Scala side");
                                    break;
                                }
                                else if (cmd == "callback")
                                {
                                    int numRDDs = SerDe.ReadInt(s);
                                    var jrdds   = new List <JvmObjectReference>();
                                    for (int i = 0; i < numRDDs; i++)
                                    {
                                        jrdds.Add(new JvmObjectReference(SerDe.ReadObjectId(s)));
                                    }
                                    double time = SerDe.ReadDouble(s);

                                    IFormatter formatter = new BinaryFormatter();
                                    object     func      = formatter.Deserialize(new MemoryStream(SerDe.ReadBytes(s)));

                                    string        deserializer = SerDe.ReadString(s);
                                    RDD <dynamic> rdd          = null;
                                    if (jrdds[0].Id != null)
                                    {
                                        rdd = new RDD <dynamic>(new RDDIpcProxy(jrdds[0]), sparkContext, (SerializedMode)Enum.Parse(typeof(SerializedMode), deserializer));
                                    }

                                    if (func is Func <double, RDD <dynamic>, RDD <dynamic> > )
                                    {
                                        JvmObjectReference jrdd = (((Func <double, RDD <dynamic>, RDD <dynamic> >)func)(time, rdd).RddProxy as RDDIpcProxy).JvmRddReference;
                                        SerDe.Write(s, (byte)'j');
                                        SerDe.Write(s, jrdd.Id);
                                    }
                                    else if (func is Func <double, RDD <dynamic>, RDD <dynamic>, RDD <dynamic> > )
                                    {
                                        string             deserializer2 = SerDe.ReadString(s);
                                        RDD <dynamic>      rdd2          = new RDD <dynamic>(new RDDIpcProxy(jrdds[1]), sparkContext, (SerializedMode)Enum.Parse(typeof(SerializedMode), deserializer2));
                                        JvmObjectReference jrdd          = (((Func <double, RDD <dynamic>, RDD <dynamic>, RDD <dynamic> >)func)(time, rdd, rdd2).RddProxy as RDDIpcProxy).JvmRddReference;
                                        SerDe.Write(s, (byte)'j');
                                        SerDe.Write(s, jrdd.Id);
                                    }
                                    else
                                    {
                                        ((Action <double, RDD <dynamic> >)func)(time, rdd);
                                        SerDe.Write(s, (byte)'n');
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                //log exception only when callback socket is not shutdown explicitly
                                if (!callbackSocketShutdown)
                                {
                                    logger.LogException(e);
                                }
                            }
                        }
                    }
            }
            catch (Exception e)
            {
                logger.LogException(e);
            }

            logger.LogInfo("thread to process callback request exit");
        }
Exemple #56
0
        public int InsertProjectInfoDb(Project objProjectInfoBlob)
        {
            int val = 0;


            SqlString = "INSERT into ProjectInfo (SystemID,ProjectID,ProjectName,ActiveFlag,LastUpdateDate,Version,DBVersion,Measure,Location,SoldTo,ShipTo,OrderNo,ContractNo,Region,Office,Engineer,YINO,DeliveryDate,OrderDate,Remarks,ProjectType,Vendor,ProjectBlob,SystemBlob,SQBlob) Values(@SystemID, @ProjectID,@ProjectName,@ActiveFlag,@LastUpdateDate,@Version,@DBVersion,@Measure,@Location,@SoldTo,@ShipTo,@OrderNo,@ContractNo,@Region,@Office, @Engineer, @YINO,@DeliveryDate, @OrderDate,@Remarks,@ProjectType, @Vendor, @ProjectBlob,@SystemBlob,@SqBlob)";

            byte[]          ProjectBlob = null;
            MemoryStream    objstream   = new MemoryStream();
            BinaryFormatter bf          = new BinaryFormatter();

            bf.Serialize(objstream, objProjectInfoBlob);
            ProjectBlob = objstream.ToArray();

            JCHVRF.Model.New.Project objProjectInfo = new JCHVRF.Model.New.Project();

            #region SaveDataInDb

            try
            {
                using (OleDbConnection conn = new OleDbConnection(connectionString))

                {
                    using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))

                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@SystemID", objProjectInfoBlob.objProjectInfo.SystemID);
                        cmd.Parameters.AddWithValue("@ProjectID", 10);
                        cmd.Parameters.AddWithValue("@ProjectName", objProjectInfoBlob.objProjectInfo.ProjectName);
                        cmd.Parameters.AddWithValue("@ActiveFlag", 1);
                        cmd.Parameters.AddWithValue("@LastUpdateDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@Version", objProjectInfoBlob.objProjectInfo.Version);
                        cmd.Parameters.AddWithValue("@DBVersion", objProjectInfoBlob.objProjectInfo.DBVersion);
                        cmd.Parameters.AddWithValue("@Measure", objProjectInfoBlob.objProjectInfo.Measure);
                        cmd.Parameters.AddWithValue("@Location", objProjectInfoBlob.objProjectInfo.Location);
                        cmd.Parameters.AddWithValue("@SoldTo", objProjectInfoBlob.objProjectInfo.SoldTo);
                        cmd.Parameters.AddWithValue("@ShipTo", objProjectInfoBlob.objProjectInfo.ShipTo);
                        cmd.Parameters.AddWithValue("@OrderNo", objProjectInfoBlob.objProjectInfo.OrderNo);
                        cmd.Parameters.AddWithValue("@ContractNo", objProjectInfoBlob.objProjectInfo.ContractNo);
                        cmd.Parameters.AddWithValue("@Region", objProjectInfoBlob.objProjectInfo.Region);
                        cmd.Parameters.AddWithValue("@Office", objProjectInfoBlob.objProjectInfo.Office);
                        cmd.Parameters.AddWithValue("@Engineer", objProjectInfoBlob.objProjectInfo.Engineer);
                        cmd.Parameters.AddWithValue("@YINO", objProjectInfoBlob.objProjectInfo.YINo);
                        cmd.Parameters.AddWithValue("@DeliveryDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@OrderDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@Remarks", objProjectInfoBlob.objProjectInfo.Remarks);
                        cmd.Parameters.AddWithValue("@ProjectType", objProjectInfoBlob.objProjectInfo.ProjectType);
                        cmd.Parameters.AddWithValue("@Vendor", objProjectInfoBlob.objProjectInfo.Vendor);
                        cmd.Parameters.AddWithValue("@ProjectBlob", ProjectBlob);
                        cmd.Parameters.AddWithValue("@SystemBlob", DbType.Binary);
                        cmd.Parameters.AddWithValue("@SqBlob", DbType.Binary);
                        val = cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
            }


            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(val);
        }
        private static void SerializeFields(StateManager stateManager, object instance, ref IStateObject viewModel, BinaryWriter writer, Type logicObjectType, IList <FieldInfo> fieldList, string fieldPrefix = "")
        {
            var formatter = new BinaryFormatter();

            foreach (var field in fieldList)
            {
#if DEBUG
                Trace.WriteLine(string.Format("Serializing promise field {0}.{1}", fieldPrefix, field.Name));
#endif
                var objValue = field.GetValue(instance);
                if (objValue == null)
                {
                    continue;                   //We do not need to save null fields
                }
                ///The delegate can be an instance method. We are looking to determine if there is a reference to the "this instance"
                if (IsThisTheThisField(stateManager, instance, field, logicObjectType, objValue, writer, fieldPrefix, ref viewModel))
                {
                    continue;
                }
                if (field.Name.Contains("locals"))
                {
                    var parentSurrogate = stateManager.surrogateManager.GetSurrogateFor(instance, generateIfNotFound: false);
                    if (parentSurrogate == null)
                    {
                        throw new InvalidOperationException("A parent surrogate is needed");
                    }
                    var localsSurrogate = stateManager.surrogateManager.GetSurrogateFor(objValue, generateIfNotFound: false);
                    if (localsSurrogate == null) //There was not a previous surrogate!! Ok we need a lastminute one
                    {
                        throw new Exception("Invalid condition. Surrogate dependency should have been reported previously");
                        //RegisterSurrogateForDisplayClass(field.FieldType, objValue,parentSurrogate.UniqueID);

                        //localsSurrogate = stateManager.surrogateManager.GetSurrogateFor(objValue, generateIfNotFound: true, parentSurrogate: parentSurrogate.UniqueID);
                        //stateManager.surrogateManager.AddSurrogateReference(localsSurrogate, parentSurrogate.UniqueID);
                    }
                    writer.Write(field.Name);
                    writer.Write(localsSurrogate.UniqueID);
                    continue;
                }
                //If we have a value we need to serialize
                //We will write the fieldName + Value
                bool isSerializable = false;
                if (objValue is IStateObject || IsInterfaceThatMightBeAnStateObject(objValue))
                {
                    //For IStateObject only the UniqueID is needed for the other we would use the ISerialize
                    var value = (IStateObject)objValue;
                    //If this field is not the this then we are goint to save its value
                    writer.Write(fieldPrefix + field.Name);
                    var orphanHolder = stateManager.AdoptionInformation.GetOrphanHolder(instance, value, field.Name);
                    if (orphanHolder == null)
                    {
                        writer.Write(value.UniqueID);
                    }
                    else
                    {
                        writer.Write(orphanHolder.UniqueID);
                    }
                }
                else if (objValue is ILogicWithViewModel <IStateObject> )
                {
                    var value = (ILogicWithViewModel <IStateObject>)objValue;
                    Debug.Assert(value.ViewModel != null);
                    writer.Write(fieldPrefix + field.Name);
                    writer.Write(value.ViewModel.UniqueID);
                }
                else if ((isSerializable = (field.FieldType.IsSerializable || objValue.GetType().IsSerializable)) && objValue is MulticastDelegate)
                {
                    SerializeDelegate(stateManager, instance, writer, fieldPrefix, field, objValue);
                }
                else if (SurrogatesDirectory.IsSurrogateRegistered(field.FieldType))
                {
                    var surrogate = stateManager.surrogateManager.GetSurrogateFor(objValue, generateIfNotFound: true);
                    if (surrogate == null)
                    {
                        // Something is wrong here, throw an exception
                        throw new InvalidOperationException("Error getting the surrogate for field " + field.Name + " with type " + field.FieldType.FullName + " inside object of type " + instance.GetType().FullName);
                    }
                    var parentSurrogate = stateManager.surrogateManager.GetSurrogateFor(instance, generateIfNotFound: false);
                    stateManager.surrogateManager.AddSurrogateReference(surrogate, parentSurrogate);
                    writer.Write(field.Name);
                    writer.Write(surrogate.UniqueID);
                }
                else if (isSerializable)
                {
                    writer.Write(fieldPrefix + field.Name);
                    formatter.Serialize(writer.BaseStream, objValue);
                }
                else
                {
                    throw new NotSupportedException("Error serializing field " + field.Name + " with type " + field.FieldType.FullName + " inside object of type " + instance.GetType().FullName);
                }
            }
        }
    public static PlayerData load(GameManager gameManager)
    {
        string path = Application.persistentDataPath + "/player.dat";

        if (hasLoadedFile())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream      stream    = new FileStream(path, FileMode.Open);
            stream.Position = 0;
            Debug.Log("LOAD");

            PlayerData data = (PlayerData)formatter.Deserialize(stream);

            gameManager.gold            = data.gold;
            gameManager.year            = data.year;
            gameManager.wood            = data.wood;
            gameManager.stone           = data.stone;
            gameManager.yearlyExpenses  = data.yearlyExpenses;
            gameManager.taxPercent      = data.taxPercent;
            gameManager.happiness       = data.happiness;
            gameManager.popIncome       = data.popIncome;
            gameManager.population      = data.population;
            gameManager.leather         = data.leather;
            gameManager.soldierCount    = data.soldierCount;
            gameManager.soldierStrength = data.soldierStrength;
            gameManager.ownsBarracks    = data.ownsBarracks;
            gameManager.ownsMarket      = data.ownsMarket;
            gameManager.ownsTavern      = data.ownsTavern;
            gameManager.ownsWatchtower  = data.ownsWatchtower;
            gameManager.ownsGarrison    = data.ownsGarrison;
            gameManager.ownsDruid       = data.ownsDruid;
            gameManager.tradeRym        = data.tradeRym;
            gameManager.tradeJalonn     = data.tradeJalonn;
            gameManager.tradeCobeth     = data.tradeCobeth;
            gameManager.tradeGalerd     = data.tradeGalerd;
            gameManager.isAtWar         = data.isAtWar;
            gameManager.warStatus       = data.warStatus;
            gameManager.conqueredStatus = data.conqueredStatus;
            gameManager.puppetStates    = data.puppetStates;

            gameManager.relationsWithCobeth = data.relationsWithCobeth;
            gameManager.relationsWithGalerd = data.relationsWithGalerd;
            gameManager.relationsWithJalonn = data.relationsWithJalonn;
            gameManager.relationsWithRym    = data.relationsWithRym;

            gameManager.woodValue    = data.woodValue;
            gameManager.stoneValue   = data.stoneValue;
            gameManager.leatherValue = data.leatherValue;

            GameObject canvas = GameObject.FindGameObjectWithTag("Canvas");
            canvas.GetComponent <ResourceUI>().updateResourceText();

            foreach (GameManager.Kingdom k in gameManager.warStatus.Keys)
            {
                gameManager.updateTradeStatus(k);
            }


            stream.Close();

            return(data);
        }
        else
        {
            Debug.Log("Save file not found.");
            return(null);
        }
    }
        internal static void DeserializeStateForDelegate(BinaryReader reader, Type delegateClassType, object instance, ref string fieldName, string prefix = null)
        {
            var formatter = new BinaryFormatter();
            var fieldList = delegateClassType.Fields(BindingFlags.Public | BindingFlags.Instance);

            foreach (var field in fieldList)
            {
                if (fieldName == null)
                {
                    if (reader.BaseStream.Position == reader.BaseStream.Length)
                    {/*No more data*/
                        return;
                    }
                    fieldName = reader.ReadString();
                    if (prefix != null)
                    {
                        if (fieldName.StartsWith(prefix, StringComparison.Ordinal))
                        {
                            fieldName = fieldName.Substring(prefix.Length);
                        }
                    }

                    TraceUtil.WriteLine(string.Format("Setting value for field {0}", fieldName));
                }
                //Skip until find matching field
                if (!fieldName.Equals(field.Name, StringComparison.Ordinal))
                {
                    continue;
                }

                if (field.Name.Contains("<>") && field.Name.Contains("locals"))
                {
                    //Is it in locals??
                    //Check if still goes here.
                    var surrogateUID    = reader.ReadString();
                    var localsSurrogate = (StateObjectSurrogate)StateManager.Current.GetObject(surrogateUID);
                    var localsInstance  = localsSurrogate.Value;
                    field.SetValue(instance, localsInstance);
                    fieldName = null;
                    continue;
                }
                //Is not locals.mmm ok is it an StateObject
                if (typeof(IStateObject).IsAssignableFrom(field.FieldType) ||
                    (field.FieldType.IsGenericType &&
                     (typeof(IList <>).IsAssignableFrom(field.FieldType.GetGenericTypeDefinition()) ||
                      typeof(IDictionary <,>).IsAssignableFrom(field.FieldType.GetGenericTypeDefinition()))
                    ))
                {
                    var uid = reader.ReadString();
                    if (!String.IsNullOrWhiteSpace(uid))
                    {
                        var fieldValue = StateManager.Current.GetObject(uid);
                        var surrogate  = fieldValue as StateObjectSurrogate;
                        if (surrogate != null)
                        {
                            fieldValue = surrogate.Value as IStateObject;
                        }
                        field.SetValue(instance, fieldValue);
                    }
                    fieldName = null;
                }
                else if (typeof(ILogicWithViewModel <IStateObject>).IsAssignableFrom(field.FieldType))
                {
                    fieldName = null;
                    var uid = reader.ReadString();
                    var vm  = StateManager.Current.GetObject(uid);
                    if (vm != null)
                    {
                        Type logicType = field.FieldType;
                        if (logicType.IsInterface)
                        {
                            var logicAttr = vm.GetType().GetCustomAttribute(typeof(UpgradeHelpers.Helpers.LogicAttribute)) as UpgradeHelpers.Helpers.LogicAttribute;
                            if (logicAttr == null)
                            {
                                throw new InvalidOperationException("The logic type for the viewmodel could not be determined. Please decorate the ViewModel class type with the Logic Attribute. for example [Logic(Type = typeof(LogicClass)]");
                            }
                            logicType = logicAttr.Type;
                        }

                        var form = IocContainerImplWithUnity.Current.Resolve(logicType, null, IIocContainerFlags.NoView | IIocContainerFlags.RecoveredFromStorage) as ILogicView <IViewModel>;
                        form.SetPropertyValue("ViewModel", vm);
                        field.SetValue(instance, form);
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("The ViewModel for field {0} could not be restored ", field.Name));
                    }
                }
                else
                {
                    if (field.FieldType.IsSerializable && typeof(MulticastDelegate).IsAssignableFrom(field.FieldType))
                    {
                        RestoreDelegateField(reader, instance, field);
                    }
                    else if (SurrogatesDirectory.IsSurrogateRegistered(field.FieldType))
                    {
                        var uid = reader.ReadString();
                        if (!String.IsNullOrWhiteSpace(uid))
                        {
                            StateObjectSurrogate surrogate = StateManager.Current.surrogateManager.GetObject(uid);
                            field.SetValue(instance, surrogate.Value);
                        }
                    }
                    else if (field.FieldType.IsSerializable)
                    {
                        var fieldValue = formatter.Deserialize(reader.BaseStream);
                        field.SetValue(instance, fieldValue);
                    }
                    fieldName = null;
                }
            }
        }
    // Save character stats, types and moves
    internal void Save(string CharacterName, GameObject GameObjectToSave)
    {
        // Create a binary formatter and a new file
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Create(Application.persistentDataPath + "/" + CharacterName + ".dat");

        // Create an object to save information to
        CharacterData data = new CharacterData();

        // Temp character ref
        Character charRef = GameObjectToSave.GetComponent <Character>();

        // Save general stats
        data.Level          = charRef.Level;
        data.Experience     = charRef.Experience;
        data.Health         = charRef.Health;
        data.Happiness      = charRef.Happiness;
        data.Fullness       = charRef.CurrentFullness;
        data.EvolutionCount = charRef.CurrentEvolutionStage;

        // Save battle stats
        data.Attack      = charRef.Attack;
        data.Accuracy    = charRef.Accuracy;
        data.CritChance  = charRef.CritChance;
        data.Defence     = charRef.Defence;
        data.DodgeChance = charRef.DodgeChance;
        data.Speed       = charRef.Speed;

        // Save spec points
        data.AirPoints    = charRef.AirPoints;
        data.EarthPoints  = charRef.EarthPoints;
        data.FirePoints   = charRef.FirePoints;
        data.NaturePoints = charRef.NaturePoints;
        data.WaterPoints  = charRef.WaterPoints;

        // Save character types to int array
        data.CharacterTypes = new int[charRef.CharactersElementTypes.Count];
        for (int i = 0; i < data.CharacterTypes.Length; i++)
        {
            // Convert from Element.ElementType to int for serialization
            switch (charRef.CharactersElementTypes[i])
            {
            case Elements.ElementType.NonElemental:
                data.CharacterTypes[i] = 0;
                break;

            case Elements.ElementType.Air:
                data.CharacterTypes[i] = 1;
                break;

            case Elements.ElementType.Earth:
                data.CharacterTypes[i] = 2;
                break;

            case Elements.ElementType.Fire:
                data.CharacterTypes[i] = 3;
                break;

            case Elements.ElementType.Nature:
                data.CharacterTypes[i] = 4;
                break;

            case Elements.ElementType.Water:
                data.CharacterTypes[i] = 5;
                break;

            default:
                break;
            }
        }

        // Save character moves to int array
        data.CharacterMoves = new int[3];
        for (int i = 0; i < data.CharacterMoves.Length; i++)
        {
            switch (GameObjectToSave.GetComponent <Character>().MoveSlots[i])
            {
            case Elements.ElementalMoves.EmptyMoveSlot:
                data.CharacterMoves[i] = 0;
                break;

            case Elements.ElementalMoves.AirStrike:
                data.CharacterMoves[i] = 1;
                break;

            case Elements.ElementalMoves.EarthQuake:
                data.CharacterMoves[i] = 2;
                break;

            case Elements.ElementalMoves.FireBlaze:
                data.CharacterMoves[i] = 3;
                break;

            case Elements.ElementalMoves.NaturesWrath:
                data.CharacterMoves[i] = 4;
                break;

            case Elements.ElementalMoves.Tackle:
                data.CharacterMoves[i] = 5;
                break;

            case Elements.ElementalMoves.WaterBlast:
                data.CharacterMoves[i] = 6;
                break;

            default:
                Debug.Log("Error saving moves to file");
                break;
            }
        }

        // Write the object to file and close it
        bf.Serialize(file, data);
        file.Close();
    }