public override void OnHandleResponse(OperationResponse response)
    {

        NetworkManager view = _controller.ControlledView as NetworkManager;
        view.LogDebug("GOT A RESPONSE for KNOWN STARS");
        if (response.ReturnCode == 0)
        {
            view.LogDebug(response.Parameters[(byte)ClientParameterCode.KnownStars].ToString());

            // Deserialize
            var xmlData = response.Parameters[(byte)ClientParameterCode.KnownStars].ToString();
            XmlSerializer deserializer = new XmlSerializer(typeof(XmlStarPlayerList));
            TextReader reader = new StringReader(xmlData);
            object obj = deserializer.Deserialize(reader);
            XmlStarPlayerList starCollection = (XmlStarPlayerList)obj;
            reader.Close();

            List<KnownStar> stars = new List<KnownStar>();
            foreach (SanStarPlayer s in starCollection.StarPlayers)
                stars.Add(new KnownStar(s));

            // Update local data
            PlayerData.instance.UpdateKnownStars(stars);
        }
        else
        {
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
    }
    public override void OnHandleResponse(OperationResponse response)
    {
        NetworkManager view = _controller.ControlledView as NetworkManager;
        view.LogDebug("GOT A RESPONSE for KNOWN Planets");
        if (response.ReturnCode == 0)
        {
            // TODO FIX THIS FOR ONLY 1 PLANET??
            view.LogDebug(response.Parameters[(byte)ClientParameterCode.Planets].ToString());

            // Deserialize
            var xmlData = response.Parameters[(byte)ClientParameterCode.Planets].ToString();
            XmlSerializer deserializer = new XmlSerializer(typeof(XmlPlanetList));
            TextReader reader = new StringReader(xmlData);
            object obj = deserializer.Deserialize(reader);
            XmlPlanetList planetCollection = (XmlPlanetList)obj;
            reader.Close();

            // Update local data
            foreach (SanPlanet p in planetCollection.Planets) {
                var planet = PlayerData.instance.ownedPlanets.Find(x => x.starID == p.StarId && x.planetID == p.PlanetNum);
                if (planet != null)
                {
                    planet.planetpopulation = p.Population;
                }
            }              
                


        }
        else
        {
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
    }
Ejemplo n.º 3
0
    void NameEntered()
    {
        congratulationsUILabel.text = "";
        PlayerPrefs.SetString("name", playerName);

        StringReader reader = new StringReader(PlayerPrefs.GetString(Application.loadedLevel+"","600 IACONIC\n1200 IACONIC\n1800 IACONIC\n2400 IACONIC\n3000 IACONIC\n3600 IACONIC\n4200 IACONIC\n4800 IACONIC\n5400 IACONIC\n6000 IACONIC"));
        string output = "";
        bool counted = false;
        timeUILabel.text = "";
        nameUILabel.text = "";
        for(int i = 0; i < 10; i ++)
        {
            string input = reader.ReadLine();
            int timer = int.Parse(input.Split(' ')[0]);
            if(playTime<timer&&!counted)
            {
                timeUILabel.text += TimeToString(playTime) + "\n";
                nameUILabel.text += playerName + "\n";
                output += playTime + " " + playerName + "\n";
                i ++;
                counted = true;
            }
            timeUILabel.text += TimeToString(timer);
            nameUILabel.text += input.Split(' ')[1];
            if(i!=9)
            {
                timeUILabel.text +=  "\n";
                nameUILabel.text +=  "\n";
            }
            output += input + "\n";
        }
        reader.Close();
        PlayerPrefs.SetString(Application.loadedLevel+"",output);
    }
    /// <summary>
    /// Default method, that gets called upon loading the page.
    /// </summary>
    /// <param name="sender">object that invoked this method</param>
    /// <param name="e">Event arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        this.notificationDetailsFile = ConfigurationManager.AppSettings["notificationDetailsFile"];
        if (string.IsNullOrEmpty(this.notificationDetailsFile))
        {
            this.notificationDetailsFile = @"~\\notificationDetailsFile.txt";
        }
        Stream inputstream = Request.InputStream;
        int streamLength = Convert.ToInt32(inputstream.Length);
        byte[] stringArray = new byte[streamLength];
        inputstream.Read(stringArray, 0, streamLength);

        //string xmlString = System.Text.Encoding.UTF8.GetString(stringArray);
        string xmlString ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><ownershipEvent type=\"grant\" timestamp=\"2014-07-17T23:01:30+00:00\"><networkOperatorId>cingularmi</networkOperatorId><ownerIdentifier>T_NWS_PNW_1351286778000105651482</ownerIdentifier><purchaseDate>2014-07-17T23:01:19+00:00</purchaseDate><productIdentifier>Onetime_Cat3</productIdentifier><purchaseActivityIdentifier>SYusvaaFefcszswDAqAzY2LEVSMZ698NXjI5</purchaseActivityIdentifier><instanceIdentifier>dcce5466-2548-4fb7-b907-f16ab49ffb81-CSHARPUAT</instanceIdentifier><minIdentifier>2067472099</minIdentifier><sequenceNumber>6798</sequenceNumber><reasonCode>0</reasonCode><reasonMessage>Processed Normally</reasonMessage><vendorPurchaseIdentifier>CThuJul172014230053</vendorPurchaseIdentifier></ownershipEvent>";
        ownershipEvent notificationObj;
        if (!String.IsNullOrEmpty(xmlString))
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(ownershipEvent));
            TextReader textReader = new StringReader(xmlString);

            notificationObj = (ownershipEvent)deserializer.Deserialize(textReader);
            textReader.Close();

            string notificationDetails = string.Empty;
            foreach (var prop in notificationObj.GetType().GetProperties())
            {
                Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(notificationObj, null));
                notificationDetails += prop.Name + "%" + prop.GetValue(notificationObj, null) + "$";
            }
            this.WriteRecord(notificationDetails);
        }
    }
    public override void OnHandleResponse(OperationResponse response)
    {
        NetworkManager view = _controller.ControlledView as NetworkManager;
        if (response.ReturnCode == 0)
        {
            // TODO FIX THIS FOR ONLY 1 PLANET??
            view.LogDebug(response.Parameters[(byte)ClientParameterCode.Planets].ToString());
            DisplayManager.Instance.DisplayMessage("Planet Colonized!");

            // Deserialize
            var xmlData = response.Parameters[(byte)ClientParameterCode.Planets].ToString();
            XmlSerializer deserializer = new XmlSerializer(typeof(XmlPlanetList));
            TextReader reader = new StringReader(xmlData);
            object obj = deserializer.Deserialize(reader);
            XmlPlanetList planetCollection = (XmlPlanetList)obj;
            reader.Close();

            // Update local data
            foreach (SanPlanet p in planetCollection.Planets)
                PlayerData.instance.AddOwnedPlanet(new OwnedPlanet(p));
        }
        else
        {
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
    }
Ejemplo n.º 6
0
        public void Page_466()
        {
            try
            {
                strwtr = new StringWriter();

                for (int i = 0; i < 10; i++)
                {
                    strwtr.WriteLine("Meaning i equals: " + i);
                }

                strrdr = new StringReader(strwtr.ToString());

                string str = strrdr.ReadLine();
                while (str != null)
                {
                    str = strrdr.ReadLine();
                    Console.WriteLine(str);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("Error I/O " + e.Message);
            }
            finally
            {
                strrdr?.Close();
                strwtr?.Close();
            }
        }
Ejemplo n.º 7
0
    public static ScoreHistory Load()
    {
        try
        {
            string buffer = PlayerPrefs.GetString(key);
            TextReader stReader = null;
            XmlSerializer xmlSerializer;
            try
            {
                xmlSerializer = new XmlSerializer(typeof(ScoreHistory));
                stReader = new StringReader(buffer);
                return xmlSerializer.Deserialize(stReader) as ScoreHistory;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                if (stReader != null)
                    stReader.Close();
            }

        }
        catch (Exception)
        {

        }

        return null;
    }
Ejemplo n.º 8
0
        protected internal static IList <string> GetTranslations(string translation)
        {
            translation = string.Format("{0}", (object)translation).Trim();
            IList <string> stringList   = (IList <string>) new List <string>(16);
            StringReader   stringReader = new StringReader(translation);

            try
            {
                while (true)
                {
                    string str1;
                    do
                    {
                        string str2 = stringReader.ReadLine();
                        if (str2 != null)
                        {
                            str1 = string.Format("{0}", (object)str2).Trim();
                        }
                        else
                        {
                            goto label_4;
                        }
                    }while (string.IsNullOrEmpty(str1));
                    stringList.Add(str1);
                }
label_4:
                return(stringList);
            }
            finally
            {
                stringReader?.Close();
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 将Xml字符串反序列化成指定类型的对象。
        /// </summary>
        /// <typeparam name="T">对象的类型。</typeparam>
        /// <param name="xml">对象序列化后的字符串。</param>
        /// <returns></returns>
        public static T DeserializeFromXmlString <T>(string xml)
        {
            T            target = default;
            StringReader sr     = null;

            try
            {
                var xs = new XmlSerializer(typeof(T));

                sr = new StringReader(xml); // containing the XML data to read
                using (var xtr = new XmlTextReader(sr))
                {
                    sr = null;
                    var o = xs.Deserialize(xtr);
                    if (o is T variable)
                    {
                        target = variable;
                    }
                }
            }
            finally
            {
                sr?.Close();
            }

            return(target);
        }
Ejemplo n.º 10
0
        private static object DeserializeFromString(string objectData, Type type)
        {
            var    serializer = new XmlSerializer(type);
            object result;

            TextReader reader = null;

            try
            {
                reader = new StringReader(objectData);
                result = serializer.Deserialize(reader);
            }
            catch (InvalidOperationException e)
            {
                string error = e.Message + ": " + e.InnerException?.Message;
                _log.Error(error, e);
                throw new ArkadeException(error);
            }
            finally
            {
                reader?.Close();
            }

            return(result);
        }
Ejemplo n.º 11
0
 //this must be called only when we know that the dll is loaded and available
 //so it must be a hierarchical step by step procedure on a need to base and not
 //after load
 public void CreateDataModelFromXml()
 {
     if (!String.IsNullOrEmpty(xmlItemDataModel) && !String.IsNullOrEmpty(xmlMainType))
     {
         //itemDataModel = null;
         StringReader stringWriter = null;
         XmlReader    xmlWriter    = null;
         try
         {
             stringWriter = new StringReader(xmlItemDataModel);
             xmlWriter    = XmlReader.Create(stringWriter);
             DataModelPluginConfiguration obj = null;
             XmlSerializer ser = new XmlSerializer(Type.GetType(xmlMainType));//, allsertypes);
             obj = ser.Deserialize(xmlWriter) as DataModelPluginConfiguration;
             _serializationError = "XML Read OK";
             _itemDataModel      = obj;
         }
         catch (Exception ex)
         {
             _serializationError = ex.Message;
         }
         finally
         {
             if (xmlWriter != null)
             {
                 xmlWriter.Close();
             }
             else
             {
                 stringWriter?.Close();
             }
         }
     }
 }
Ejemplo n.º 12
0
    public Dictionary<string, float> getConfigMuret(string index)
    {
        Dictionary<string, float> conf = new Dictionary<string, float>();
        string fullpath = "shaders/configs/muret/" + index/* + ".txt"*/; // the file is actually ".txt" in the end

        TextAsset textAsset = (TextAsset) Resources.Load(fullpath, typeof(TextAsset));

        if(textAsset != null){
            StringReader reader = new StringReader(textAsset.text);

            if(reader != null)
            {
                string floatString = "";

                do
                {
                    floatString = reader.ReadLine();

                    if(floatString != null)
                    {
                        string szkey = floatString.Substring(0, floatString.IndexOf("="));
                        float fvalue = float.Parse(floatString.Substring(floatString.IndexOf("=") + 1));
                        conf.Add(szkey,fvalue);

                    }

                }while(floatString != null);

                reader.Close();
            }
            return conf;
        }else{
            return null;
        }
    }
Ejemplo n.º 13
0
 public static object deserialization(object o,string xml_text)
 {
     TextReader reader;
     XmlSerializer serialRead = new XmlSerializer (o.GetType());
     reader = new StringReader(xml_text);
     o = serialRead.Deserialize (reader);
     reader.Close ();
     return o;
 }
Ejemplo n.º 14
0
	public static ItemContainer Load(string path) {
		TextAsset _xml = Resources.Load<TextAsset>(path);
		StringReader reader = new StringReader(_xml.text);
		XmlSerializer serializer = new XmlSerializer(typeof(ItemContainer));
		ItemContainer items = serializer.Deserialize(reader) as ItemContainer;
		reader.Close();

		return items;
	}
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strLoc = "Loc_000oo";
		String strValue = String.Empty;
		try
		{
			StringReader sr;
			strLoc = "Loc_98yg7";
			iCountTestcases++;
			try {		
                sr = new StringReader(null);
                String strTemp = sr.ReadToEnd();
				iCountErrors++;
				printerr( "Error_18syx! StringReader should only hold null");
				sr.ReadLine();
				sr.Peek();
				sr.Read();
				sr.Close();
			} catch (ArgumentNullException exc) {
				printinfo("Expected exception thrown, exc=="+exc.Message);
			}catch (Exception exc) {
				iCountErrors++;
				printerr("Error_109xu! Unexpected exception thrown, exc=="+exc.ToString());
			}
			strLoc = "Loc_4790s";
			sr = new StringReader(String.Empty);
			iCountTestcases++;
			if(!sr.ReadToEnd().Equals(String.Empty)) {
				iCountErrors++;
				printerr( "Error_099xa! Incorrect construction");
			}		   		 
			strLoc = "Loc_8388x";
			sr = new StringReader("Hello\0World");
			iCountTestcases++;
			if(!sr.ReadToEnd().Equals("Hello\0World")) {
				iCountErrors++;
				printerr( "Error_1099f! Incorrect construction");
			}
		} catch (Exception exc_general ) {			
			++iCountErrors;
			Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Ejemplo n.º 16
0
	protected static void Parse(string filePath, string fileName, Dictionary<string, ParseHandler> handlers) 
	{
		string 		path = string.Format("{0}/{1}", filePath, fileName);
		Debug.Log(path);
		TextAsset 	asset = (TextAsset)Resources.Load(path, typeof(TextAsset));
		TextReader 	input = new StringReader(asset.text);
		string     	aLine;
		int 		lineCurrent = 0;
		
		if (!handlers.ContainsKey(kHandlerStart) || !handlers.ContainsKey(kHandlerDone)) {
			Debug.LogError(string.Format("Handlers must include keys `{0}' and `{1}'",
			                             kHandlerStart, kHandlerDone));
			input.Close();
			return;
		}
		handlers[kHandlerStart](lineCurrent, null);
		while ((aLine = input.ReadLine()) != null) {
			string trimmedLine = aLine.Trim();
			
			// Ignore blank lines
			if (trimmedLine.Length < 1 || trimmedLine.StartsWith(kTokenComment)) {
				++lineCurrent;
				continue;
			}
			
			// Get the tokens and update the current object.
			string[] tokens = aLine.Split(kTokenDelimiters, 
			                              System.StringSplitOptions.RemoveEmptyEntries);
			string tokenType = tokens[0].Trim(kTrimCharacters);
			if (handlers.ContainsKey(tokenType)) {
				if (!handlers[tokenType](lineCurrent+1, tokens)) break;
			}
			else {
				Debug.LogError(string.Format("Unknown token type `{0}' on line {1}.",
				                             tokenType, lineCurrent+1));
				break;
			}
			
			++lineCurrent;
		}
		handlers[kHandlerDone](lineCurrent, null);
		input.Close();
	}
    public void Load()
    {
        TextAsset _xml = Resources.Load<TextAsset>(_path);
        XmlSerializer serializer = new XmlSerializer(typeof(gvmPropertiesManager));
        StringReader reader = new StringReader(_xml.text);

        _instance = serializer.Deserialize(reader) as gvmPropertiesManager;

        reader.Close();
    }
Ejemplo n.º 18
0
    public static LevelData LoadFromFile(int zone, int level)
    {
        string levelFilePath = LevelUtils.GetPathForLevelLoad (zone, level);

        TextAsset textAsset = (TextAsset)Resources.Load(levelFilePath, typeof(TextAsset));
        XmlSerializer serializer = new XmlSerializer (typeof(LevelData));
        StringReader stream = new StringReader (textAsset.text);
        LevelData data = serializer.Deserialize (stream) as LevelData;
        stream.Close ();
        return data;
    }
Ejemplo n.º 19
0
    public static EmbedHandDataV1 DeserializeFromXML(string xmlData)
    {
        EmbedHandDataV1 data = null;

        StringReader stringReader = null;

        XmlSerializer deserializer = new XmlSerializer(typeof(EmbedHandDataV1));
        stringReader = new StringReader(xmlData);
        data = (EmbedHandDataV1)deserializer.Deserialize(stringReader);
        stringReader.Close();

        return data;
    }
    public static gvmSpellContainer Load(string path)
    {
        TextAsset _xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(gvmSpellContainer));
        StringReader reader = new StringReader(_xml.text);

        var data = serializer.Deserialize(reader) as gvmSpellContainer;

        reader.Close();

        return data;
    }
        public DataReader(string content, bool overrideOldData = false)
        {
            data = new Dictionary <string, string>();
            StringReader reader = null;
            string       line   = "";

            try
            {
                reader = new StringReader(content);
                while ((line = reader.ReadLine()) != null)
                {
                    if (!(line == string.Empty) && (line.Length <= 1 || !(line.Substring(0, 2) == "//")))
                    {
                        int    num = line.IndexOf(' ');
                        string text;
                        string value;
                        if (num != -1)
                        {
                            text  = line.Substring(0, num);
                            value = line.Substring(num + 1, line.Length - num - 1);
                        }
                        else
                        {
                            text  = line;
                            value = string.Empty;
                        }
                        if (data.ContainsKey(text))
                        {
                            App.Logger.Log("Multiple instances of '" + text + "'");
                            if (overrideOldData)
                            {
                                App.Logger.Log($"Overriding {text}...");
                            }
                        }
                        else
                        {
                            data.Add(text, value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                App.Logger.LogException("Failed to load data", ex: ex);
                data.Clear();
            }
            finally
            {
                reader?.Close();
            }
        }
    public override void OnHandleResponse(OperationResponse response)
    {
        NetworkManager view = _controller.ControlledView as NetworkManager;
        view.LogDebug("GOT A RESPONSE for KNOWN SHIPS");
        if (response.ReturnCode == 0)
        {
            view.LogDebug(response.Parameters[(byte)ClientParameterCode.PlayerShips].ToString());

            // Deserialize
            var xmlData = response.Parameters[(byte)ClientParameterCode.PlayerShips].ToString();
            XmlSerializer deserializer = new XmlSerializer(typeof(XmlShipList));
            TextReader reader = new StringReader(xmlData);
            object obj = deserializer.Deserialize(reader);
            XmlShipList shipCollection = (XmlShipList)obj;
            reader.Close();

            // Update local data
            foreach (SanShip s in shipCollection.Ships)
            {
                // Ship is an owned ship                    
                PlayerData.instance.AddNewShip(new ShipInfo(s));

                // Determine if ship is on a mission or just an owned ship
                if (s.DestStar != 0) {
                    // Ship has a destination - it's on a mission
                    PlayerData.instance.AddNewMission(new ShipInfo(s));

                    // Check if this mission should be completed
                    DateTime currenttime = DateTime.Now;
                    if (s.EndTime <= currenttime) {
                        XmlSerializer serializer = new XmlSerializer(typeof(DateTime));
                        var xmlCurrentTime = "";
                        using (StringWriter textWriter = new StringWriter())
                        {
                            serializer.Serialize(textWriter, DateTime.Now);
                            xmlCurrentTime = textWriter.ToString();
                        }
                        NetworkManager.instance._controller.SendMissionComplete(s.ShipId, xmlCurrentTime); // NETWORK STUFF
                    }       
                    
                }                
            }           


        }
        else
        {
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
    }
Ejemplo n.º 23
0
    public static ChampionContainer Load(string path)
    {
        TextAsset _xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(ChampionContainer));

        StringReader reader = new StringReader(_xml.text);

        ChampionContainer champions = serializer.Deserialize(reader) as ChampionContainer;

        reader.Close();

        return champions;
    }
Ejemplo n.º 24
0
        public void ParseXml(string serviceParametersXml)
        {
            this.Clear();

            if (string.IsNullOrEmpty(serviceParametersXml))
            {
                return;
            }

            StringReader xPathTextReader = null;

            try
            {
                xPathTextReader = new StringReader(serviceParametersXml);
                XPathDocument xPathDoc = new XPathDocument(xPathTextReader);

                XPathNavigator    xPathNavigator = xPathDoc.CreateNavigator();
                XPathNodeIterator xPathIter      =
                    xPathNavigator.Select("/ServiceParameters/Item");

                while (xPathIter.MoveNext())
                {
                    string key =
                        xPathIter.Current?.GetAttribute("key", xPathIter.Current.NamespaceURI);
                    if (string.IsNullOrEmpty(key))
                    {
                        continue;
                    }

                    string value = xPathIter.Current?.Value;

                    if (string.CompareOrdinal(key, "PublicKey") == 0)
                    {
                        this.PublicKey = value;

                        continue;
                    }

                    base[key] = value;
                }
            }
            catch (Exception)
            {
                // Just Handle Exceptions
            }
            finally
            {
                xPathTextReader?.Close();
            }
        }
    public static BackgroundProperties Load(string backgroundPath)
    {
        TextAsset xml = Resources.Load<TextAsset>(backgroundPath);

        XmlSerializer serializer = new XmlSerializer(typeof(BackgroundProperties));

        StringReader reader = new StringReader(xml.text);

        BackgroundProperties properties = serializer.Deserialize(reader) as BackgroundProperties;

        reader.Close();

        return properties;
    }
Ejemplo n.º 26
0
	public static NeutralEventContainer Load(string path)
	{
		
		TextAsset _xml = Resources.Load<TextAsset> (path);
		
		XmlSerializer serializer = new XmlSerializer (typeof(NeutralEventContainer));
		
		StringReader reader = new StringReader (_xml.text);
		
		NeutralEventContainer events = serializer.Deserialize (reader) as NeutralEventContainer;
		
		reader.Close ();
		
		return events;
	}
    public static LevelCollection Load(string path)
    {
        TextAsset _xml = Resources.Load<TextAsset>(path);

        XmlSerializer serializer = new XmlSerializer(typeof(LevelCollection));

        StringReader reader = new StringReader(_xml.text);

        LevelCollection text = serializer.Deserialize(reader) as LevelCollection;

        reader.Close();

        return text;

    }
Ejemplo n.º 28
0
    public static LevelData LoadLevelData(int lvlId)
    {
#if UNITY_WEBPLAYER
        TextAsset asset = Resources.Load<TextAsset>("Levels/Level_" + lvlId.ToString("D2"));

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(LevelData));
        StringReader reader = new StringReader(asset.text);
        return (LevelData)xmlSerializer.Deserialize(reader);
        reader.Close();
#else
        FileInfo fInfo = new FileInfo("Levels/Level_" + lvlId.ToString("D2") + ".xml");
        if (fInfo.Exists)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(LevelData));
            StreamReader reader = File.OpenText(fInfo.FullName);
            return (LevelData)xmlSerializer.Deserialize(reader);
            reader.Close();
        }
        else
        {
            return new LevelData();
        }
#endif
    }
Ejemplo n.º 29
0
    public static DataReaderTextContainer Load(string path)
    {
        TextAsset _xml = Resources.Load <TextAsset> (path);

        XmlSerializer serializer = new XmlSerializer (typeof(DataReaderTextContainer));

        StringReader reader = new StringReader (_xml.text);

        DataReaderTextContainer audioLogs = serializer.Deserialize(reader) as DataReaderTextContainer;
        //DataReaderTextContainer logTexts = serializer.Deserialize(reader) as DataReaderTextContainer;

        reader.Close();

        return audioLogs;
    }
Ejemplo n.º 30
0
    public static AllMosterDataBase LoadFronXmlFile(string _path)
    {
        TextAsset xml = (TextAsset)Resources.Load(_path);
        Debug.Log (xml);
        XmlSerializer xmlSerialzer = new XmlSerializer(typeof(AllMosterDataBase));
        StringReader reader = new StringReader (xml.text);
        AllMosterDataBase buffer = xmlSerialzer.Deserialize (reader) as AllMosterDataBase;
        reader.Close ();

        #if UNITY_EDITOR
        foreach(MosterDataBase item in  buffer.mosterArray){
            Debug.Log (item.HP);
        }
        #endif
        return buffer;
    }
Ejemplo n.º 31
0
    public void Load(string name)
    {
        //nameはファイル名(.csvはいらない)
        TextAsset csv = Resources.Load("CSV/"+name) as TextAsset;
        StringReader reader = new StringReader(csv.text);

        while (reader.Peek() > -1) { //最後の行を読むまで
            //行読み込み
            string line = reader.ReadLine();
            //カンマで区切られた要素を格納
            string[] values = line.Split(',');
            for(int i=0;i<values.Length;i++){
                strData.Add (values[i]);
            }
        }
        reader.Close ();
    }
    public static MapProperties Load(string mapPath)
    {
        TextAsset xml = Resources.Load<TextAsset>(mapPath + "_properties");

        if(xml == null){
            ErrorLogger.Log("Map Properties file not found: " + mapPath+"_properties.xml", "When referencing maps in your area xml file, make sure that same name exists in the map data directory");
        }
        XmlSerializer serializer = new XmlSerializer(typeof(MapProperties));

        StringReader reader = new StringReader(xml.text);

        MapProperties properties = serializer.Deserialize(reader) as MapProperties;

        reader.Close();

        return properties;
    }
    public static ScriptDustItemsContainer LoadDust(string path)
    {
        TextAsset _xml = Resources.Load<TextAsset>( path);
            if (_xml == null)
            {
                return null;
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer (typeof(ScriptDustItemsContainer));
                StringReader reader = new StringReader (_xml.text);
                ScriptDustItemsContainer Item = serializer.Deserialize (reader) as ScriptDustItemsContainer;

                reader.Close ();
                return Item;
            }
    }
Ejemplo n.º 34
0
    public static Dictionary<string, EnemyDropList> deserializeEnemyDrops()
    {
        Dictionary<string, EnemyDropList> dropList = new Dictionary<string, EnemyDropList>();

        XmlSerializer serial = new XmlSerializer(typeof(EnemyDropModel));
        TextAsset file = (TextAsset)Resources.Load("xml/enemyDrop");
        StringReader stringReader = new StringReader(file.text);
        EnemyDropModel enemyDropContainer = (EnemyDropModel)serial.Deserialize(stringReader);
        stringReader.Close();

        foreach (EnemyDropList list in enemyDropContainer.DropList)
        {
            dropList.Add(list.EnemyId, list);
            //Debug.Log("Drop Importer -> Importing Enemy List " + list.EnemyId + list.ItemList.Count);
        }

        return dropList;
    }
    public override void OnHandleResponse(OperationResponse response)
    {
        NetworkManager view = _controller.ControlledView as NetworkManager;
        view.LogDebug("GOT A RESPONSE for CREATING SHIP");
        if (response.ReturnCode == 0)
        {
            view.LogDebug(response.Parameters[(byte)ClientParameterCode.PlayerShips].ToString());
            DisplayManager.Instance.DisplayMessage("Ship Created!");

            // Deserialize
            var xmlData = response.Parameters[(byte)ClientParameterCode.PlayerShips].ToString();
            XmlSerializer deserializer = new XmlSerializer(typeof(XmlShipList));
            TextReader reader = new StringReader(xmlData);
            object obj = deserializer.Deserialize(reader);
            XmlShipList shipCollection = (XmlShipList)obj;
            reader.Close();

            // Update local data - add this one ship
            foreach (SanShip s in shipCollection.Ships)
                PlayerData.instance.AddNewShip(new ShipInfo(s));

            // Update spacebux amount after creating this ship
            PlayerData.instance.UpdateSpacebux((int)response.Parameters[(byte)ClientParameterCode.Spacebux]); 

        }
        else if (response.ReturnCode == 6)
        {
            // Not enough population
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
        else if (response.ReturnCode == 7)
        {
            // You don't own this planet
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
        else
        {
            view.LogDebug("RESPONSE: " + response.DebugMessage);
            DisplayManager.Instance.DisplayMessage(response.DebugMessage);
        }
    }
Ejemplo n.º 36
0
 void Start()
 {
     cube = new GameObject ();
     //		UserData.STAY_WORLD = 1;
     //		SelectStage.num = 1;
     TextAsset csv = Resources.Load("CSV/World_"+UserData.STAY_WORLD+"/stage"+SelectStage.num) as TextAsset;
     StringReader reader = new StringReader(csv.text);
     length = 0;
         while (reader.Peek() > -1) {
         string line = reader.ReadLine();
         string[] values = line.Split(',');
         for(int i=0;i<values.Length;i++){
             strData.Add (values[i]);
             length++;
         }
     }
     setMap ();
     reader.Close ();
 }
Ejemplo n.º 37
0
 private void Refresh()
 {
     lock (m_Lock)
     {
         StringReader stringReader = null;
         try
         {
             m_Sections.Clear();
             m_Modified.Clear();
             stringReader = new StringReader(m_iniString);
             Dictionary <string, string> dictionary = null;
             string Key   = null;
             string Value = null;
             string text;
             while ((text = stringReader.ReadLine()) != null)
             {
                 text = text.Trim();
                 string text2 = ParseSectionName(text);
                 if (text2 != null)
                 {
                     if (m_Sections.ContainsKey(text2))
                     {
                         dictionary = null;
                     }
                     else
                     {
                         dictionary = new Dictionary <string, string>();
                         m_Sections.Add(text2, dictionary);
                     }
                 }
                 else if (dictionary != null && ParseKeyValuePair(text, ref Key, ref Value) && !dictionary.ContainsKey(Key))
                 {
                     dictionary.Add(Key, Value);
                 }
             }
         }
         finally
         {
             stringReader?.Close();
         }
     }
 }
Ejemplo n.º 38
0
        private static object DeserializeFromString(string objectData, Type type)
        {
            var    serializer = new XmlSerializer(type);
            object result;

            TextReader reader = null;

            try
            {
                reader = new StringReader(objectData);

                result = serializer.Deserialize(reader);
            }
            finally
            {
                reader?.Close();
            }

            return(result);
        }
Ejemplo n.º 39
0
    public static IEnumerator LoadDatabasesFromUrls()
    {
        loadingDatabases = true;
        progress = 0f;

        currentRequest = new WWW("http://appliedrationality.org/uploads/games/credence/Databases.txt");
        yield return currentRequest;
        if(currentRequest.error != null){
            resultLog = currentRequest.error;
        } else {
            TextReader reader = new StringReader(currentRequest.text);
            List<QuestionDatabase> newDatabases = LoadDatabasesFromStream(reader, false);
            reader.Close();
            int databasesAdded = 0;
            foreach(QuestionDatabase database in newDatabases){
                if(databases.Contains(database)) continue;
                database.fileIndex = globalFileIndex;
                globalFileIndex++;
                databases.Add(database);
                databasesAdded++;
            }

            foreach(QuestionDatabase database in databases){
                currentRequest = new WWW(database.url);
                yield return currentRequest;
                if(currentRequest.error != null){
                    resultLog = currentRequest.error;
                } else {
                    database.downloaded = true;
                    StreamWriter writer = new StreamWriter(database.FilePath);
                    writer.Write(currentRequest.text);
                    writer.Close();
                }
                progress += 1f / databases.Count;
            }

            resultLog = "Updated all databases successfully." + (databasesAdded > 0 ? (" Added " + databasesAdded + " new databases.") : "");
            justLoadedDatabases = true;
        }
        loadingDatabases = false;
    }
Ejemplo n.º 40
0
        public Reporter Deserialize(string str)
        {
            Reporter   repoter = null;
            TextReader sr      = null;

            try
            {
                sr      = new StringReader(str);
                repoter = (Reporter)xmlSerializer.Deserialize(sr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sr?.Close();
                sr?.Dispose();
            }
            return(repoter);
        }
Ejemplo n.º 41
0
        public List <User> XMLToUsers(string xml)
        {
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            Object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <User>));
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return((List <User>)obj);
        }
Ejemplo n.º 42
0
        public virtual string GetTranslatioinValue(string translation, IMapping mapping)
        {
            translation = string.Format("{0}", (object)translation).Trim();
            if (translation.ToLower().StartsWith("#define"))
            {
                int num1 = translation.IndexOf("{");
                int num2 = translation.LastIndexOf("}");
                translation = translation.Substring(num1 + 1, num2 - num1 - 1);
                return(this.Parser.ExecuteDefinition(translation, mapping));
            }
            StringReader stringReader = new StringReader(translation);

            try
            {
                string translation1;
                string result;
                string conditions;
                do
                {
                    string str = stringReader.ReadLine();
                    if (str != null)
                    {
                        translation1 = string.Format("{0}", (object)str).Trim();
                    }
                    else
                    {
                        goto label_6;
                    }
                }while (string.IsNullOrEmpty(translation1) || translation1.ToLower() == "else" || Translator.TryToParseIfTranslation(translation1, out result, out conditions) && !this._parser.Test(conditions, mapping));
                return(this._parser.GetResult(result, mapping));

label_6:
                return(string.Empty);
            }
            finally
            {
                stringReader?.Close();
            }
        }
Ejemplo n.º 43
0
        public List <UsersLogin> GetLoginsFromXML()
        {
            var               xml       = File.ReadAllText("login.xml");
            StringReader      strReader = null;
            XmlTextReader     xmlReader = null;
            List <UsersLogin> obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <UsersLogin>));
                xmlReader = new XmlTextReader(strReader);
                obj       = (List <UsersLogin>)serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return(obj ?? new List <UsersLogin>());
        }
Ejemplo n.º 44
0
        public static object XmlToObjects(string xml, Type object_type)
        {
            StringReader  str_reader = null;
            XmlTextReader xml_reader = null;
            object        obj;

            try {
                str_reader = new StringReader(xml);
                var serializer = new XmlSerializer(object_type);
                xml_reader = new XmlTextReader(str_reader);
                obj        = serializer.Deserialize(xml_reader);
            }
            catch (Exception e) {
                Console.WriteLine(e);
                throw;
            }
            finally {
                xml_reader?.Close();
                str_reader?.Close();
            }

            return(obj);
        }
Ejemplo n.º 45
0
        public static object ObjectToXML(string xml, Type objectType)
        {
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(objectType);
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception)
            {
                //Handle Exception Code
            }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return(obj);
        }
Ejemplo n.º 46
0
        public T DeSerializeObject <T>(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(default(T));
            }

            T objectOut = default(T);

            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fileName);
                string xmlString = xmlDocument.OuterXml;

                using (StringReader read = new StringReader(xmlString))
                {
                    Type outType = typeof(T);

                    XmlSerializer serializer = new XmlSerializer(outType);
                    using (XmlReader reader = new XmlTextReader(read))
                    {
                        objectOut = (T)serializer.Deserialize(reader);
                        reader.Close();
                    }

                    read.Close();
                }
            }
            catch
            {
            }


            return(objectOut);
        }
Ejemplo n.º 47
0
        private void InitValues()
        {
            XmlNode rNode = _Draw.GetReportNode();
            XmlNode cNode = _Draw.GetNamedChildNode(rNode, "Code");

            tbCode.Text = "";
            if (cNode == null)
            {
                return;
            }

            StringReader  tr = new StringReader(cNode.InnerText);
            List <string> ar = new List <string>();

            while (tr.Peek() >= 0)
            {
                string line = tr.ReadLine();
                ar.Add(line);
            }
            tr.Close();

            //    tbCode.Lines = ar.ToArray("".GetType()) as string[];
            tbCode.Lines = ar.ToArray();
        }
Ejemplo n.º 48
0
        public List <Package> XMLToPackages()
        {
            var           xml       = File.ReadAllText("packages.xml");
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            Object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <Package>));
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }

            obj = obj ?? new List <Package>();
            return((List <Package>)obj);
        }
Ejemplo n.º 49
0
        private static object DeserializeFromString(string objectData, Type type)
        {
            var    serializer = new XmlSerializer(type);
            object result;

            TextReader reader = null;

            try
            {
                reader = new StringReader(objectData);

                result = serializer.Deserialize(reader);
            }
            catch (Exception e)
            {
                throw new Exception("Error while deserializing xml file: " + objectData, e);
            }
            finally
            {
                reader?.Close();
            }

            return(result);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Deserializes an xml file into an object list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T DeSerializeObject <T>(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(default(T));
            }

            T objectOut = default(T);

            try
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(fileName);
                var xmlString = xmlDocument.OuterXml;

                using (StringReader read = new StringReader(xmlString))
                {
                    Type outType = typeof(T);

                    var serializer = new XmlSerializer(outType);
                    using (var reader = new XmlTextReader(read))
                    {
                        objectOut = (T)serializer.Deserialize(reader);
                        reader.Close();
                    }

                    read.Close();
                }
            }
            catch (Exception ex)
            {
                //Log exception here
            }

            return(objectOut);
        }
Ejemplo n.º 51
0
        public HeliosVisual CreateInstance()
        {
            HeliosVisual control = ConfigManager.ModuleManager.CreateControl(_typeIdentifier);

            if (control != null)
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments   = true;
                settings.IgnoreWhitespace = true;
                settings.CloseInput       = true;

                StringReader templateReader = new StringReader(_templateControl);
                XmlReader    xmlReader      = XmlReader.Create(templateReader, settings);
                xmlReader.ReadStartElement("TemplateValues");
                control.ReadXml(xmlReader);
                xmlReader.ReadEndElement();
                xmlReader.Close();
                templateReader.Close();

                control.Name = Name;
            }

            return(control);
        }
Ejemplo n.º 52
0
        public static Attribute Load(string path)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlSerializer serializer = new XmlSerializer(typeof(ChummerCharacter));

                StringReader reader = new StringReader(doc.OuterXml);

                Attribute attr = serializer.Deserialize(reader) as Attribute;
                reader.Close();

                return(attr);
            }
            catch (FileNotFoundException e)
            {
                if (e.Source != null)
                {
                    Console.WriteLine("FileNotFoundException source: {0}", e.Source);
                }
                throw;
            };
        }
Ejemplo n.º 53
0
        public void StartAnalysis()
        {
            AssetBundlePackage package   = HFResourceManager.Instance.LoadAssetBundleFromFile("Config");
            TextAsset          textAsset = package.LoadAssetWithCache <TextAsset>("UI");
            StringReader       reader    = new StringReader(textAsset.text);

            reader.ReadLine();
            reader.ReadLine();
            reader.ReadLine();
            reader.ReadLine();
            reader.ReadLine();
            while (true)
            {
                string row = reader.ReadLine();
                if (string.IsNullOrEmpty(row))
                {
                    break;
                }
                string[] strs = row.Split(split, StringSplitOptions.None);
                if (strs.Length > 0)
                {
                    UI       config = new UI();
                    string[] air    = null;
                    config.Type = strs[0];
                    int.TryParse(strs[1], out config.LayerIndex);
                    config.AssetbundleName = strs[2];
                    config.AssetName       = strs[3];
                    config.ShowAnimation   = strs[4];
                    config.HideAnimation   = strs[5];
                    config.ClassName       = strs[6];
                    dic.Add(config.Type, config);
                    list.Add(config);
                }
            }
            reader.Close();
        }
Ejemplo n.º 54
0
        private Assembly GetAssembly()
        {
            // Generate the proxy source code
            List <string> lines = new List <string>();            // hold lines in array in case of error

            VBCodeProvider vbcp = new VBCodeProvider();
            StringBuilder  sb   = new StringBuilder();
            //  Generate code with the following general form

            //Imports System
            //Imports Microsoft.VisualBasic
            //Imports System.Convert
            //Imports System.Math
            //Namespace fyiReporting.vbgen
            //Public Class MyClassn	   // where n is a uniquely generated integer
            //Sub New()
            //End Sub
            //  ' this is the code in the <Code> tag
            //End Class
            //End Namespace
            string unique = Interlocked.Increment(ref Parser.Counter).ToString();

            lines.Add("Imports System");
            lines.Add("Imports Microsoft.VisualBasic");
            lines.Add("Imports System.Convert");
            lines.Add("Imports System.Math");
            lines.Add("Imports fyiReporting.RDL");
            lines.Add("Namespace fyiReporting.vbgen");
            _Classname = "MyClass" + unique;
            lines.Add("Public Class " + _Classname);
            lines.Add("Private Shared _report As CodeReport");
            lines.Add("Sub New()");
            lines.Add("End Sub");
            lines.Add("Sub New(byVal def As Report)");
            lines.Add(_Classname + "._report = New CodeReport(def)");
            lines.Add("End Sub");
            lines.Add("Public Shared ReadOnly Property Report As CodeReport");
            lines.Add("Get");
            lines.Add("Return " + _Classname + "._report");
            lines.Add("End Get");
            lines.Add("End Property");
            // Read and write code as lines
            StringReader tr = new StringReader(_Source);

            while (tr.Peek() >= 0)
            {
                string line = tr.ReadLine();
                lines.Add(line);
            }
            tr.Close();
            lines.Add("End Class");
            lines.Add("End Namespace");
            foreach (string l in lines)
            {
                sb.Append(l);
                sb.Append("\r\n");
            }

            string vbcode = sb.ToString();

            // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//						StreamWriter tsw = File.CreateText(@"c:\temp\vbcode.txt");
//						tsw.Write(vbcode);
//						tsw.Close();
            // debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            // Create Assembly
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("System.dll");
            string re;

            //AJM GJL 250608 - Try the Bin Directory too, for websites
            if (RdlEngineConfig.DirectoryLoadedFrom == null)
            {
                if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "RdlEngine.dll"))
                {
                    re = AppDomain.CurrentDomain.BaseDirectory + "RdlEngine.dll";   // this can fail especially in web scenarios
                }
                else
                {
                    re = AppDomain.CurrentDomain.BaseDirectory + "Bin\\RdlEngine.dll";   // this can work especially in web scenarios
                }
            }
            else
            {
                re = RdlEngineConfig.DirectoryLoadedFrom + "RdlEngine.dll";     // use RdlEngineConfig.xml directory when available
            }
            cp.ReferencedAssemblies.Add(re);
            // also allow access to classes that have been added to report
            if (this.OwnerReport.CodeModules != null)
            {
                foreach (CodeModule cm in this.OwnerReport.CodeModules.Items)
                {
                    //Changed from Forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905
                    string modulePath = Path.Combine(Path.GetDirectoryName(re), cm.CdModule);
                    cp.ReferencedAssemblies.Add(modulePath);
                }
            }
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;                         // just loading into memory causes problems when instantiating
            cp.IncludeDebugInformation = false;
            CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);

            if (cr.Errors.Count > 0)
            {
                StringBuilder err = new StringBuilder(string.Format("Code element has {0} error(s).  Line numbers are relative to Code element.", cr.Errors.Count));
                foreach (CompilerError ce in cr.Errors)
                {
                    string l;
                    if (ce.Line >= 1 && ce.Line <= lines.Count)
                    {
                        l = lines[ce.Line - 1] as string;
                    }
                    else
                    {
                        l = "Unknown";
                    }
                    err.AppendFormat("\r\nLine {0} '{1}' : {2} {3}", ce.Line - 5, l, ce.ErrorNumber, ce.ErrorText);
                }
                this.OwnerReport.rl.LogError(4, err.ToString());
                return(null);
            }

            return(Assembly.LoadFrom(cr.PathToAssembly));               // We need an assembly loaded from the file system
            //   or instantiation of object complains
        }
Ejemplo n.º 55
0
        /// <summary>
        ///   Reify/deserialize landData
        /// </summary>
        /// <param name = "serializedLandData"></param>
        /// <returns></returns>
        /// <exception cref = "System.Xml.XmlException"></exception>
        public static LandData Deserialize(string serializedLandData)
        {
            LandData landData = new LandData();

            StringReader  sr  = new StringReader(serializedLandData);
            XmlTextReader xtr = new XmlTextReader(sr);

            xtr.ReadStartElement("LandData");

            landData.Area           = Convert.ToInt32(xtr.ReadElementString("Area"));
            landData.AuctionID      = Convert.ToUInt32(xtr.ReadElementString("AuctionID"));
            landData.AuthBuyerID    = UUID.Parse(xtr.ReadElementString("AuthBuyerID"));
            landData.Category       = (ParcelCategory)Convert.ToSByte(xtr.ReadElementString("Category"));
            landData.ClaimDate      = Convert.ToInt32(xtr.ReadElementString("ClaimDate"));
            landData.ClaimPrice     = Convert.ToInt32(xtr.ReadElementString("ClaimPrice"));
            landData.GlobalID       = UUID.Parse(xtr.ReadElementString("GlobalID"));
            landData.GroupID        = UUID.Parse(xtr.ReadElementString("GroupID"));
            landData.IsGroupOwned   = Convert.ToBoolean(xtr.ReadElementString("IsGroupOwned"));
            landData.Bitmap         = Convert.FromBase64String(xtr.ReadElementString("Bitmap"));
            landData.Description    = xtr.ReadElementString("Description");
            landData.Flags          = Convert.ToUInt32(xtr.ReadElementString("Flags"));
            landData.LandingType    = Convert.ToByte(xtr.ReadElementString("LandingType"));
            landData.Name           = xtr.ReadElementString("Name");
            landData.Status         = (ParcelStatus)Convert.ToSByte(xtr.ReadElementString("Status"));
            landData.LocalID        = Convert.ToInt32(xtr.ReadElementString("LocalID"));
            landData.MediaAutoScale = Convert.ToByte(xtr.ReadElementString("MediaAutoScale"));
            landData.MediaID        = UUID.Parse(xtr.ReadElementString("MediaID"));
            landData.MediaURL       = xtr.ReadElementString("MediaURL");
            landData.MusicURL       = xtr.ReadElementString("MusicURL");
            landData.OwnerID        = UUID.Parse(xtr.ReadElementString("OwnerID"));

            landData.ParcelAccessList = new List <ParcelManager.ParcelAccessEntry>();
            xtr.Read();
            if (xtr.Name != "ParcelAccessList")
            {
                throw new XmlException(String.Format("Expected \"ParcelAccessList\" element but got \"{0}\"", xtr.Name));
            }

            if (!xtr.IsEmptyElement)
            {
                while (xtr.Read() && xtr.NodeType != XmlNodeType.EndElement)
                {
                    ParcelManager.ParcelAccessEntry pae = new ParcelManager.ParcelAccessEntry();

                    xtr.ReadStartElement("ParcelAccessEntry");
                    pae.AgentID = UUID.Parse(xtr.ReadElementString("AgentID"));
                    pae.Time    = Convert.ToDateTime(xtr.ReadElementString("Time"));
                    pae.Flags   = (AccessList)Convert.ToUInt32(xtr.ReadElementString("AccessList"));
                    xtr.ReadEndElement();

                    landData.ParcelAccessList.Add(pae);
                }
            }
            xtr.Read();

            landData.PassHours    = Convert.ToSingle(xtr.ReadElementString("PassHours"));
            landData.PassPrice    = Convert.ToInt32(xtr.ReadElementString("PassPrice"));
            landData.SalePrice    = Convert.ToInt32(xtr.ReadElementString("SalePrice"));
            landData.SnapshotID   = UUID.Parse(xtr.ReadElementString("SnapshotID"));
            landData.UserLocation = Vector3.Parse(xtr.ReadElementString("UserLocation"));
            landData.UserLookAt   = Vector3.Parse(xtr.ReadElementString("UserLookAt"));
            // No longer used here
            xtr.ReadElementString("Dwell");
            landData.OtherCleanTime = Convert.ToInt32(xtr.ReadElementString("OtherCleanTime"));

            xtr.ReadEndElement();

            xtr.Close();
            sr.Close();

            return(landData);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Will load the referenced schema files and use them to validate the given NIEM xml message.  Returns null
        /// if an error occurs.
        /// </summary>
        /// <param name="xmldata">NIEM message as xml</param>
        /// <param name="errorString">The error list</param>
        /// <returns>True if the message is valid, false otherwise</returns>
        /// <exception cref="IOException">Their was a problem loading the schema files</exception>
        /// <exception cref="FormatException">The schema files could not be parsed</exception>
        public static bool ValidateNiemSchema(string xmldata, out List <string> errorString)
        {
            /*
             * NOTE: When flattening the schema files XMLSpy it will add an "xs:appinfo" element
             * to some of the files.  If this element contains a child element "term:" then the
             * appinfo element must be removed.  Otherwise, visual studio cannot
             * load the schema file properly.
             */

            #region Initialize Readers and Error list

            errorString = null;
            XmlReader         vr      = null;
            XmlReaderSettings xs      = new XmlReaderSettings();
            XmlSchemaSet      coll    = new XmlSchemaSet();
            StringReader      xsdsr   = null;
            StringReader      xmlsr   = new StringReader(xmldata);
            XmlReader         xsdread = null;
            #endregion

            try
            {
                #region Load Schema Files
                string currentFile = ""; // For Error logging, holds schema file being added

                try
                {
                    currentFile = "temporalObjects";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.temporalObjects);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.TEMPORALOBJECTS, xsdread);


                    currentFile = "xs";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.xs);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.XS, xsdread);


                    currentFile = "emlc";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.emlc);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.EMLC, xsdread);


                    currentFile = "fips_10_4";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.fips_10_4);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.FIPS_10_4, xsdread);


                    currentFile = "census_uscounty";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.census_uscounty);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.CENSUS_USCOUNTY, xsdread);


                    currentFile = "mo";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.mo);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.MO, xsdread);


                    currentFile = "em_base";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.em_base);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.EM_BASE, xsdread);


                    currentFile = "fema_rtlt1";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.fema_rtlt1);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.FEMA_RTLT1, xsdread);


                    currentFile = "maid";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.maid);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.MAID, xsdread);


                    currentFile = "emcl";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.emcl);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.EMCL, xsdread);


                    currentFile = "unece_rec20_misc";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.unece_rec20_misc);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.UNECE_REC20_MISC, xsdread);


                    currentFile = "geospatial";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.geospatial);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.GEOSPATIAL, xsdread);


                    currentFile = "fips_5_2";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.fips_5_2);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.FIPS_5_2, xsdread);


                    currentFile = "spatialReferencing";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.spatialReferencing);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.SPATIALREFERENCING, xsdread);


                    currentFile = "core_misc";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.core_misc);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.CORE_MISC, xsdread);


                    currentFile = "niem_core";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.niem_core);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.NIEM_CORE, xsdread);


                    currentFile = "geometry";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.geometry);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.GEOMETRY, xsdread);


                    currentFile = "ols";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.ols);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.OLS, xsdread);


                    currentFile = "structures";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.structures);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.STRUCTURES, xsdread);


                    currentFile = "basicTypes";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.basicTypes);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.BASICTYPES, xsdread);


                    currentFile = "fema_rtlt";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.fema_rtlt);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.FEMA_RTLT, xsdread);


                    currentFile = "xlinks";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.xlinks);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.XLINKS, xsdread);


                    currentFile = "referenceSystems";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.referenceSystems);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.REFERENCESYSTEMS, xsdread);


                    currentFile = "dataQuality";
                    xsdsr       = new StringReader(Fresh.Global.Properties.Resources.dataQuality);
                    xmlsr       = new StringReader(xmldata);
                    xsdread     = XmlReader.Create(xsdsr);
                    coll.Add(ValidationConstants.DATAQUALITY, xsdread);

                    xs.Schemas.Add(coll);
                    currentFile = "";
                }
                catch (Exception Ex)
                {
                    throw new FormatException("There was an error parsing the schema files", Ex);
                    currentFile = "";
                }

                #endregion

                // Will Hold errors found
                List <string> errors = null;

                xs.ValidationType          = ValidationType.Schema;
                xs.ValidationFlags        |= XmlSchemaValidationFlags.ProcessInlineSchema;
                xs.ValidationFlags        |= XmlSchemaValidationFlags.ReportValidationWarnings;
                xs.ValidationEventHandler += new ValidationEventHandler((object sender, ValidationEventArgs args) =>
                {
                    if (args.Severity == XmlSeverityType.Error)
                    {
                        if (errors == null)
                        {
                            errors = new List <string>();
                        }

                        errors.Add(args.Message);
                    }
                });

                vr = XmlReader.Create(xmlsr, xs);
                while (vr.Read())
                {
                }

                // Setting the return value
                errorString = errors;
            }
            catch (IOException Ex)
            {
                DEUtilities.LogMessage(string.Format("[{0}] {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, Ex.Message), DEUtilities.LogLevel.Error, Ex);
                throw;
            }
            catch (FormatException Ex)
            {
                DEUtilities.LogMessage(string.Format("[{0}] {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, Ex.Message), DEUtilities.LogLevel.Error, Ex);
                throw;
            }
            catch (Exception Ex)
            {
                DEUtilities.LogMessage(string.Format("[{0}] {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, Ex.Message), DEUtilities.LogLevel.Error, Ex);

                throw new Exception(string.Format("[{0}] {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, Ex.Message), Ex);
            }
            finally
            {
                // Closing
                if (vr != null)
                {
                    vr.Close();
                }
                if (xmlsr != null)
                {
                    xmlsr.Close();
                }
                if (xsdread != null)
                {
                    xsdread.Close();
                }
                if (xsdsr != null)
                {
                    xsdsr.Close();
                }
            }

            return(errorString == null);
        }
Ejemplo n.º 57
0
        ///<summary>
        ///分析响应流,去掉响应头
        ///</summary>
        ///<param name="buffer"></param>
        private void GetResponseHeader(byte[] buffer, out int startIndex)
        {
            responseHeaders.Clear();
            string       html = encoding.GetString(buffer);
            StringReader sr   = new StringReader(html);

            int start = html.IndexOf("\r\n\r\n") + 4;      //找到空行位置

            strResponseHeaders = html.Substring(0, start); //获取响应头文本

            //获取响应状态码
            //
            if (sr.Peek() > -1)
            {
                //读第一行字符串
                string line = sr.ReadLine();

                //分析此行字符串,获取服务器响应状态码
                Match M = RE.Match(line, @"\d\d\d");
                if (M.Success)
                {
                    statusCode = int.Parse(M.Value);
                }
            }

            //获取响应头
            //
            while (sr.Peek() > -1)
            {
                //读一行字符串
                string line = sr.ReadLine();

                //若非空行
                if (line != "")
                {
                    //分析此行字符串,获取响应标头
                    Match M = RE.Match(line, "([^:]+):(.+)");
                    if (M.Success)
                    {
                        try
                        {        //添加响应标头到集合
                            responseHeaders.Add(M.Groups[1].Value.Trim(), M.Groups[2].Value.Trim());
                        }
                        catch
                        { }


                        //获取Cookie
                        if (M.Groups[1].Value == "Set-Cookie")
                        {
                            M       = RE.Match(M.Groups[2].Value, "[^=]+=[^;]+");
                            cookie += M.Value.Trim() + ";";
                        }
                    }
                }
                //若是空行,代表响应头结束响应实体开始。(响应头和响应实体间用一空行隔开)
                else
                {
                    //如果响应头中没有实体大小标头,尝试读响应实体第一行获取实体大小
                    if (responseHeaders["Content-Length"] == null && sr.Peek() > -1)
                    {
                        //读响应实体第一行
                        line = sr.ReadLine();

                        //分析此行看是否包含实体大小
                        Match M = RE.Match(line, "~[0-9a-fA-F]{1,15}");

                        if (M.Success)
                        {
                            //将16进制的实体大小字符串转换为10进制
                            int length = int.Parse(M.Value, System.Globalization.NumberStyles.AllowHexSpecifier);
                            responseHeaders.Add("Content-Length", length.ToString());//添加响应标头
                            strResponseHeaders += M.Value + "\r\n";
                        }
                    }
                    break;//跳出循环
                }//End If
            }//End While

            sr.Close();

            //实体开始索引
            startIndex = encoding.GetBytes(strResponseHeaders).Length;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            error.Text           = "";
            exito.Text           = "";
            alerta_exito.Visible = false;
            alerta.Visible       = false;

            //ddlComuna.Enabled = false;
            //ddlRegion.Enabled = false;
            //Cargando DDL Pais
            Service1      service = new Service1();
            string        paises  = service.ListarPais();
            XmlSerializer ser     = new XmlSerializer(typeof(Modelo.PaisCollection));
            StringReader  reader  = new StringReader(paises);

            Modelo.PaisCollection coleccionPais = (Modelo.PaisCollection)ser.Deserialize(reader);
            reader.Close();

            //Cargando DDL Regiones
            string        regiones = service.ListarRegion();
            XmlSerializer ser1     = new XmlSerializer(typeof(Modelo.RegionCollection));
            StringReader  reader1  = new StringReader(regiones);

            coleccionRegion = (Modelo.RegionCollection)ser1.Deserialize(reader1);
            reader1.Close();

            //Cargando DDL Comunas
            string        comunas = service.ListarComuna();
            XmlSerializer ser2    = new XmlSerializer(typeof(Modelo.ComunaCollection));
            StringReader  reader2 = new StringReader(comunas);

            coleccionComuna = (Modelo.ComunaCollection)ser2.Deserialize(reader2);
            reader2.Close();

            //Cargando DDL Tipo Proveedor
            string        tipos   = service.ListarTipoProveedor();
            XmlSerializer ser3    = new XmlSerializer(typeof(Modelo.TipoProveedorCollection));
            StringReader  reader3 = new StringReader(tipos);

            Modelo.TipoProveedorCollection coleccionTipo = (Modelo.TipoProveedorCollection)ser3.Deserialize(reader3);
            reader.Close();

            if (!IsPostBack)
            {
                alerta.Visible         = false;
                ddlPais.DataSource     = coleccionPais;
                ddlPais.DataTextField  = "NOMBRE_PAIS";
                ddlPais.DataValueField = "ID_PAIS";
                ddlPais.DataBind();

                ddlRegion.DataSource     = coleccionRegion;
                ddlRegion.DataTextField  = "Nombre";
                ddlRegion.DataValueField = "Id_Region";
                ddlRegion.DataBind();

                ddlComuna.DataSource     = coleccionComuna;
                ddlComuna.DataTextField  = "Nombre";
                ddlComuna.DataValueField = "Id_Comuna";
                ddlComuna.DataBind();

                ddlTipoProveedor.DataSource     = coleccionTipo;
                ddlTipoProveedor.DataTextField  = "NOMBRE_TIPO";
                ddlTipoProveedor.DataValueField = "ID_TIPO_PROVEEDOR";
                ddlTipoProveedor.DataBind();

                ddlTipo.Items.Add("Cliente");
                ddlTipo.Items.Add("Proveedor");
                ddlTipo.Items.Add("Empleado");

                ddlTipo.SelectedIndex = 0;
                //Deshabilitar un Atributo del Dropdown list, con esto se puede hacer el atributo de ReadOnly.
                //ddlTipo.Items[0].Attributes.Add("disabled", "disabled");
            }
        }
Ejemplo n.º 59
0
        private void CanadaPostGetRates(Shipments AllShipments, out string RTShipRequest, out string RTShipResponse, decimal ExtraFee, Decimal MarkupPercent, decimal ShippingTaxRate, ref ShippingMethodCollection shippingMethods)
        {
            RTShipRequest  = String.Empty;
            RTShipResponse = String.Empty;

            if (!AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency", StoreId, true).Trim().Equals("cad", StringComparison.InvariantCultureIgnoreCase))
            {
                RTShipResponse += "Localization.StoreCurrency == CAD required to use Canada Post as a carrier.";
                return;
            }

            if (!AppConfigProvider.GetAppConfigValue("Localization.WeightUnits", StoreId, true).Equals("kg", StringComparison.InvariantCultureIgnoreCase))
            {
                RTShipResponse += "Localization.WeightUnits == kg required to use Canada Post as a carrier.";
                return;
            }

            foreach (Packages Shipment in AllShipments)
            {
                HasFreeItems    = false;
                PackageQuantity = 1;

                if (Shipment.Weight > AppConfigProvider.GetAppConfigValueUsCulture <decimal>("RTShipping.CanadaPost.MaxWeight", StoreId, true))
                {
                    shippingMethods.ErrorMsg = string.Format("{0} {1}", CanadaPostName, AppConfigProvider.GetAppConfigValue("RTShipping.CallForShippingPrompt", StoreId, true));
                    return;
                }

                // create a rate request
                CanadaPost.ratesAndServicesRequest rateRequest = new CanadaPost.ratesAndServicesRequest();
                rateRequest.merchantCPCID = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.MerchantID", StoreId, true);                  // Canada Post merchant credentials

                // ship-to address
                rateRequest.city        = Shipment.DestinationCity;
                rateRequest.provOrState = Shipment.DestinationStateProvince;
                rateRequest.country     = Shipment.DestinationCountryCode;
                rateRequest.postalCode  = Shipment.DestinationZipPostalCode;

                // create one lineitem request per package in shipment
                rateRequest.lineItems.item = new CanadaPost.item[Shipment.Count];

                int packageIndex = 0;
                foreach (Package p in Shipment)
                {
                    if (p.IsFreeShipping)
                    {
                        HasFreeItems = true;
                    }
                    if (p.IsShipSeparately)
                    {
                        PackageQuantity = p.Quantity;
                    }

                    // shipment details
                    rateRequest.itemsPrice = p.InsuredValue.ToString("#####.00");
                    rateRequest.lineItems.item[packageIndex]        = new CanadaPost.item();
                    rateRequest.lineItems.item[packageIndex].weight = p.Weight.ToString("####.0");

                    // dimensions
                    if (p.Length + p.Width + p.Height == 0)                     // if package has no dimensions, we use default
                    {
                        string dimensions = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.DefaultPackageSize", StoreId, true);
                        p.Width  = Convert.ToDecimal(dimensions.Split('x')[0].Trim());
                        p.Height = Convert.ToDecimal(dimensions.Split('x')[1].Trim());
                        p.Length = Convert.ToDecimal(dimensions.Split('x')[2].Trim());
                    }
                    rateRequest.lineItems.item[packageIndex].length = p.Length.ToString("###.0");
                    rateRequest.lineItems.item[packageIndex].width  = p.Width.ToString("###.0");
                    rateRequest.lineItems.item[packageIndex].height = p.Height.ToString("###.0");

                    packageIndex++;
                }

                // initialize eParcel request
                CanadaPost.eparcel request = new CanadaPost.eparcel();

                // choose language for reply text
                request.language = AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Language", StoreId, true).Trim();
                if (request.language.Equals("auto", StringComparison.InvariantCultureIgnoreCase))                 // set the language based on the customers locale
                {
                    Customer ThisCustomer = System.Web.HttpContext.Current.GetCustomer();
                    if (ThisCustomer.LocaleSetting.Trim().StartsWith("fr", StringComparison.InvariantCultureIgnoreCase))
                    {
                        request.language = "fr";
                    }
                    else
                    {
                        request.language = "en";
                    }
                }

                request.Items    = new CanadaPost.ratesAndServicesRequest[1];
                request.Items[0] = rateRequest;

                // serialize eParcel request class
                XmlSerializer serRequest = new XmlSerializer(typeof(CanadaPost.eparcel));
                StringWriter  swRequest  = new StringWriter();

                serRequest.Serialize(swRequest, request);
                string req = swRequest.ToString().Replace(@" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""", "");

                // open a TCP socket with Canada Post server
                Socket     socCanadaPost = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint remoteEndPoint;

                socCanadaPost.ReceiveTimeout = 10000;                 // milliseconds to wait for a response

                try
                {
                    remoteEndPoint = new IPEndPoint(Dns.GetHostAddresses(AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Server", StoreId, true))[0],
                                                    AppLogic.AppConfigNativeInt("RTShipping.CanadaPost.ServerPort"));
                    socCanadaPost.Connect(remoteEndPoint);
                }
                catch (SocketException e)
                {
                    RTShipResponse += "Tried to reach Canada Post Server (" + AppConfigProvider.GetAppConfigValue("RTShipping.CanadaPost.Server", StoreId, true) +
                                      ":" + AppLogic.AppConfigNativeInt("RTShipping.CanadaPost.ServerPort") + "): " + e.Message;
                    return;
                }


                // send request to Canada Post
                byte[] data = System.Text.Encoding.ASCII.GetBytes(req);
                socCanadaPost.Send(data);

                //receive response from Canada Post
                string resp   = String.Empty;
                byte[] buffer = new byte[8192];
                int    iRx    = 0;

                while (!resp.Contains("<!--END_OF_EPARCEL-->"))
                {
                    try
                    {
                        iRx += socCanadaPost.Receive(buffer, iRx, 8192 - iRx, SocketFlags.None);
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode == SocketError.TimedOut)
                        {
                            break;
                        }
                        else
                        {
                            throw e;
                        }
                    }
                    resp = new string((System.Text.Encoding.UTF8.GetChars(buffer, 0, iRx)));                      // decode byte array to string
                }

                // close socket
                socCanadaPost.Close();

                // create an eParcel response class
                CanadaPost.eparcel response = new CanadaPost.eparcel();

                // deserialize the xml response into the eParcel response
                XmlSerializer serResponse = new XmlSerializer(typeof(CanadaPost.eparcel));
                StringReader  srResponse  = new StringReader(resp);

                try
                {
                    response = (CanadaPost.eparcel)serResponse.Deserialize(srResponse);
                }
                catch (InvalidOperationException e)                 // invalid xml, or no reply received from Canada Post
                {
                    RTShipResponse += "Canada Post error: Could not parse response from Canada Post server: " + e.Message
                                      + " Response received: " + resp;
                    return;
                }

                srResponse.Close();

                // Check the response object for Faults
                if (response.Items[0] is CanadaPost.error)
                {
                    CanadaPost.error respError = (CanadaPost.error)response.Items[0];
                    RTShipResponse += respError.statusMessage[0];
                    return;
                }

                // Check the response object for Ratings
                if (!(response.Items[0] is CanadaPost.ratesAndServicesResponse))
                {
                    RTShipResponse += "Canada Post Error: No rating responses returned from Canada Post";
                    return;
                }

                // no faults, so extract rate information
                CanadaPost.ratesAndServicesResponse ratesResp = (CanadaPost.ratesAndServicesResponse)response.Items[0];
                foreach (CanadaPost.product product in ratesResp.product)
                {
                    decimal total = Localization.ParseUSDecimal(product.rate);

                    // ignore zero-cost methods, and methods not allowed
                    if (total != 0 && ShippingMethodIsAllowed(product.name, CanadaPostName))
                    {
                        total = total * PackageQuantity * (1.00M + (MarkupPercent / 100.0M));

                        decimal vat = Decimal.Round(total * ShippingTaxRate);

                        if (!shippingMethods.MethodExists(product.name))
                        {
                            var s_method = new ShippingMethod();
                            s_method.Carrier    = CanadaPostName;
                            s_method.Name       = product.name;
                            s_method.Freight    = total;
                            s_method.VatRate    = vat;
                            s_method.IsRealTime = true;
                            s_method.Id         = Shipping.GetShippingMethodID(s_method.Name);

                            if (HasFreeItems)
                            {
                                s_method.FreeItemsRate = total;
                            }

                            shippingMethods.Add(s_method);
                        }
                        else
                        {
                            int IndexOf  = shippingMethods.GetIndex(product.name);
                            var s_method = shippingMethods[IndexOf];
                            s_method.Freight += total;
                            s_method.VatRate += vat;

                            if (HasFreeItems)
                            {
                                s_method.FreeItemsRate += total;
                            }

                            shippingMethods[IndexOf] = s_method;
                        }
                    }
                }
                RTShipRequest  += req;                // stash request & response for this shipment
                RTShipResponse += resp;
            }

            // Handling fee should only be added per shipping address not per package
            // let's just compute it here after we've gone through all the packages.
            // Also, since we can't be sure about the ordering of the method call here
            // and that the collection SM includes shipping methods from all possible carriers
            // we'll need to filter out the methods per this carrier to avoid side effects on the main collection
            foreach (ShippingMethod shipMethod in shippingMethods.PerCarrier(CanadaPostName))
            {
                if (shipMethod.Freight != System.Decimal.Zero)                //Don't add the fee to free methods.
                {
                    shipMethod.Freight += ExtraFee;
                }
            }
        }
Ejemplo n.º 60
0
        //does the formatting job
        private string FormatCode(string source, bool lineNumbers,
                                  bool alternate, bool embedStyleSheet, bool subCode)
        {
            //replace special characters
            StringBuilder sb = new StringBuilder(source);

            if (!subCode)
            {
                sb.Replace("&", "&amp;");
                sb.Replace("<", "&lt;");
                sb.Replace(">", "&gt;");
                sb.Replace("\t", string.Empty.PadRight(TabSpaces));
            }

            //color the code
            source = CodeRegex.Replace(sb.ToString(), MatchEval);

            sb = new StringBuilder();

            if (embedStyleSheet)
            {
                sb.AppendFormat("<style type=\"{0}\">\n", MimeTypes.TextCss);
                sb.Append(GetCssString());
                sb.Append("</style>\n");
            }

            if (lineNumbers || alternate) //we have to process the code line by line
            {
                if (!subCode)
                {
                    sb.Append("<div class=\"csharpcode\">\n");
                }

                StringReader reader = new StringReader(source);
                int          i      = 0;
                const string spaces = "    ";
                string       line;
                while ((line = reader.ReadLine()) != null)
                {
                    i++;
                    if (alternate && i % 2 == 1)
                    {
                        sb.Append("<pre class=\"alt\">");
                    }
                    else
                    {
                        sb.Append("<pre>");
                    }

                    if (lineNumbers)
                    {
                        int order = (int)Math.Log10(i);
                        sb.Append("<span class=\"lnum\">"
                                  + spaces.Substring(0, 3 - order) + i
                                  + ":  </span>");
                    }

                    sb.Append(line.Length == 0 ? "&nbsp;" : line);
                    sb.Append("</pre>\n");
                }

                reader.Close();

                if (!subCode)
                {
                    sb.Append("</div>");
                }
            }
            else
            {
                //have to use a <pre> because IE below ver 6 does not understand
                //the "white-space: pre" CSS value
                if (!subCode)
                {
                    sb.Append("<pre class=\"csharpcode\">\n");
                }

                sb.Append(source);
                if (!subCode)
                {
                    sb.Append("</pre>");
                }
            }

            return(sb.ToString());
        }