Deserialize() публичный Метод

public Deserialize ( Stream stream ) : object
stream Stream
Результат object
Пример #1
1
 public WMIBMySQL()
 {
     string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
     Core.RecoverFile(file);
     if (File.Exists(file))
     {
         Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
         XmlDocument document = new XmlDocument();
         using (TextReader sr = new StreamReader(file))
         {
             document.Load(sr);
             using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
             {
                 XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
                 Unwritten un = (Unwritten)xs.Deserialize(reader);
                 lock (unwritten.PendingRows)
                 {
                     unwritten.PendingRows.AddRange(un.PendingRows);
                 }
             }
         }
     }
     Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
     Core.ThreadManager.RegisterThread(reco);
     reco.Start();
 }
Пример #2
0
        public void Resume()
        {
            string FileName = "";
            if (sign == 'o')
                FileName = "snake.xml";
            if (sign == '*')
                FileName = "food.xml";
            if (sign == '=')
                FileName = "wall.xml";

            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite);
            XmlSerializer xs = new XmlSerializer(GetType());
            //BinaryFormatter bf = new BinaryFormatter();

            if (sign == '*')
                Game.food = xs.Deserialize(fs) as Food;
            if (sign == '=')
                Game.wall = xs.Deserialize(fs) as Wall;

            if (sign == 'o')
                Game.snake = xs.Deserialize(fs) as Snake;

            fs.Close();

        }
        public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile)
        {
            var serializer = new XmlSerializer(typeof(DataSchemaModel));
            var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative));

            var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream());
            var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream());

            var outputFileSql = new List<string>();

            foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name))
            {
                var createPublicationStep = new CreatePublicationStep(publicationToCreate);
                outputFileSql.AddRange(createPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name))
            {
                var sqlPublicationComparer = new SqlPublicationComparer();
                var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name);

                var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget));
                outputFileSql.AddRange(alterPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name))
            {
                var dropPublicationStep = new DropPublicationStep(publicationToDrop);
                outputFileSql.AddRange(dropPublicationStep.GenerateTSQL());
            }
        }
        public void TestDeserializedObjects()
        {
            XmlSerializer ser = new XmlSerializer(typeof(OpenSearchDescription));

            // Base OpenSearch description document
            OpenSearchDescription osd1 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest1.osd.xml"));
            OpenSearchParameterValueSet vs1 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd1, "application/atom+xml");

            // Equivalent OpenSearch description document where parameter names are changed
            OpenSearchDescription osd2 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest2.osd.xml"));
            OpenSearchParameterValueSet vs2 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd2, "application/atom+xml");

            // Equivalent OpenSearch description document where parameter names and namespace prefixes are changed
            OpenSearchDescription osd3 = (OpenSearchDescription)ser.Deserialize(XmlReader.Create("../Samples/ParametersTest3.osd.xml"));
            OpenSearchParameterValueSet vs3 = OpenSearchParameterValueSet.FromOpenSearchDescription(osd3, "application/atom+xml");

            // Set values
            vs1.SetValueByIdentifier("http://a9.com/-/opensearch/extensions/geo/1.0/", "box", "5,5,6,6");
            vs1.SetValueByIdentifier("searchTerms", "test search");

            // Verify search query string correctness
            Assert.AreEqual("format=atom&count=&startPage=&startIndex=&q=test search&start=&stop=&trel=&bbox=5,5,6,6&uid=", vs1.GetQueryString(true));
            Assert.AreEqual("format=atom&q=test search&bbox=5,5,6,6", vs1.GetQueryString(false));

            // Translate value set by basic identifier matching
            vs2.TranslateFrom(vs1);
            Assert.AreEqual("format=atom&count2=&startPage2=&startIndex2=&q2=test search&start2=&stop2=&trel2=&bbox2=5,5,6,6&uid2=", vs2.GetQueryString(true));
            Assert.AreEqual("format=atom&q2=test search&bbox2=5,5,6,6", vs2.GetQueryString(false));

            // Translate value set by advanced identifier matching (verify namespace URIs)
            vs3.TranslateFrom(vs1, true);
            Assert.AreEqual("format=atom&count3=&startPage3=&startIndex3=&q3=test search&start3=&stop3=&trel3=&bbox3=5,5,6,6&uid3=", vs3.GetQueryString(true));
            Assert.AreEqual("format=atom&q3=test search&bbox3=5,5,6,6", vs3.GetQueryString(false));
        }
Пример #5
0
        /// <summary>
        /// プログラムのエントリーポイント。
        /// </summary>
        /// <param name="args">コマンドライン引数。</param>
        public static void Main(string[] args)
        {
            var password = "******";
            var serializer = new XmlSerializer(typeof(UserMan));
            UserMan userMan;

            // XML ファイルの内容をオブジェクトに読み込みます。
            using (var userManStream = new FileStream("UserMan.xml", FileMode.Open, FileAccess.Read))
            {
                userMan = serializer.Deserialize(userManStream) as UserMan;
                foreach (var user in userMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
            // オブジェクトを暗号化して保存します。
            using (var encryptor = new Encryptor("userMan.xml.enc", password))
            {
                serializer.Serialize(encryptor.EncryptStream, userMan);
            }
            // 暗号化したファイルを復号化して、オブジェクトに読み込みます。
            using (var decryptor = new Decryptor("UserMan.xml.enc", password))
            {
                UserMan decryptedUserMan = serializer.Deserialize(decryptor.DecryptStream) as UserMan;
                foreach (var user in decryptedUserMan.UserList)
                {
                    Console.WriteLine("User ID: {0}", user.UserID);
                    Console.WriteLine("User Name: {0}", user.UserName);
                }
            }
        }
Пример #6
0
        public static void Main(string[] args)
        {
            XmlSerializer x = new XmlSerializer(typeof(Configuration));

              Configuration Cf;
              string xmlfile;
              string shefile;
              if (args.Length == 2)
              {
            if (Path.GetExtension(args[0]).ToLower() == ".xml")
            {
              xmlfile = args[0];
              shefile = args[1];
            }
            else
            {
              xmlfile = args[1];
              shefile = args[0];
            }

            using (FileStream fs = new FileStream(xmlfile, System.IO.FileMode.Open))
              Cf = (Configuration)x.Deserialize(fs);

            Cf.SheFile = shefile;
              }
              else
            Cf = (Configuration)x.Deserialize(new FileStream(args[0], System.IO.FileMode.Open));

              Controller C = new Controller(Cf);
              C.Run();
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType));
            var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType));

            var responseMessage = new HttpResponseMessage();
            var stream = new MemoryStream();
            var localPath = request.RequestUri.LocalPath;

            // GET /orders/notshipped
            if (localPath.EndsWith("/orders/notshipped"))
                ordersSerializer.Serialize(stream, repository.GetNotShipped());

            // GET /orders/shipped
            if (localPath.EndsWith("/orders/shipped"))
                ordersSerializer.Serialize(stream, repository.GetShipped());

            // POST /orders/{id}/ship
            if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post)
            {
                var shipUrl = localPath;
                var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty);
                var shipOrder = repository.Get(shipId);
                shipOrder.shipped = true;
                repository.Update(shipOrder);
            }

            // POST /orders
            if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Add(newOrder);
            }

            // PUT /orders
            if (request.Method == HttpMethod.Put)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Update(orderToUpdate);
            }

            if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped"))
            {
                // GET /orders/{id}
                var url = localPath;
                var id = url.Replace("/api/orders/", string.Empty);
                var order = repository.Get(id);
                orderSerializer.Serialize(stream, order);
            }

            var content = Encoding.UTF8.GetString(stream.GetBuffer());
            content = content.Substring(content.IndexOf(Environment.NewLine) + 1);
            responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml");

            return Task.FromResult(responseMessage);
        }
Пример #8
0
        public void Resume(Game game)
        {
            string fileName = "";
            switch (sign)
            {
                case '#':
                    fileName = "wall.xml";
                    break;
                case '$':
                    fileName = "food.xml";
                    break;
                case 'o':
                    fileName = "snake.xml";
                    break;
            }
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            XmlSerializer xs = new XmlSerializer(this.GetType());

            switch (sign)
            {
                case '#':
                    game.wall.body.Clear();
                    game.wall = xs.Deserialize(fs) as Wall;
                    break;
                case '$':
                    game.food.body.Clear();
                    game.food = xs.Deserialize(fs) as Food;
                    break;
                case 'o':
                    game.snake.body.Clear();
                    game.snake = xs.Deserialize(fs) as Snake;
                    break;
            }
            fs.Close();
        }
Пример #9
0
        public void Resume()
        {
            string fname = "snake.xml";
            if (sign == '@')
                fname = "food.xml";
            if (sign == '#')
                fname = "wall.xml";
            string path = @"C:\Users\Zhandos\Documents\Visual Studio 2012\Projects\SNAKE\SNAKE\SNAKE\xml\" + fname;
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            XmlSerializer xs = new XmlSerializer(GetType());

            if (sign == 'o')
            {
                Game.snake.body.Clear();
                Game.snake = xs.Deserialize(fs) as Snake;
            }
            if (sign == '#')
            {
                Game.wall.body.Clear();
                Game.wall = xs.Deserialize(fs) as Wall;
            }
            if (sign == '@')
            {
                Game.food.body.Clear();
                Game.food = xs.Deserialize(fs) as Food;
            }
            fs.Close();
        }
        /// <summary>
        /// Retreaves StringDictionary object from database or file system
        /// </summary>
        /// <param name="extensionType">
        /// Extension Type
        /// </param>
        /// <param name="extensionId">
        /// Extension Id
        /// </param>
        /// <returns>
        /// StringDictionary object as Stream
        /// </returns>
        public object GetSettings(ExtensionType extensionType, string extensionId)
        {
            SerializableStringDictionary ssd;
            var sd = new StringDictionary();
            var serializer = new XmlSerializer(typeof(SerializableStringDictionary));

            if (Section.DefaultProvider == "XmlBlogProvider")
            {
                var stm = (Stream)BlogService.LoadFromDataStore(extensionType, extensionId);
                if (stm != null)
                {
                    ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
                    stm.Close();
                    sd = ssd;
                }
            }
            else
            {
                var o = BlogService.LoadFromDataStore(extensionType, extensionId);
                if (!string.IsNullOrEmpty((string)o))
                {
                    using (var reader = new StringReader((string)o))
                    {
                        ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
                    }

                    sd = ssd;
                }
            }

            return sd;
        }
        /// <summary>
        /// Retreaves StringDictionary object from database or file system
        /// </summary>
        /// <param name="exType">Extension Type</param>
        /// <param name="exId">Extension Id</param>
        /// <returns>StringDictionary object as Stream</returns>
        public object GetSettings(ExtensionType exType, string exId)
        {
            SerializableStringDictionary ssd = null;
              StringDictionary sd = new StringDictionary();
              XmlSerializer serializer = new XmlSerializer(typeof(SerializableStringDictionary));

              if (_section.DefaultProvider == "XmlTrainProvider")
              {
            Stream stm = (Stream)TrainService.LoadFromDataStore(exType, exId);
            if (stm != null)
            {
              ssd = (SerializableStringDictionary)serializer.Deserialize(stm);
              stm.Close();
              sd = (StringDictionary)ssd;
            }
              }
              else
              {
            object o = TrainService.LoadFromDataStore(exType, exId);
            if (!string.IsNullOrEmpty((string)o))
            {
              using (StringReader reader = new StringReader((string)o))
              {
            ssd = (SerializableStringDictionary)serializer.Deserialize(reader);
              }
              sd = (StringDictionary)ssd;
            }
              }
              return sd;
        }
Пример #12
0
        public HopsRepository()
        {
            if (hopses == null)
            {
                Assembly assembly = typeof(HopsRepository).Assembly;
                XmlSerializer serializer = new XmlSerializer(typeof(HopsData));
                HopsData loadedObject;
                var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                HopsDataLocalPath = String.Format("{0}\\{1}\\{2}", path, assembly.GetName().Name, HOPS_DATA_FILENAME);
                if (File.Exists(HopsDataLocalPath))
                {
                   FileStream loadStream = new FileStream(HopsDataLocalPath, FileMode.Open, FileAccess.Read);
                    loadedObject = (HopsData)serializer.Deserialize(loadStream);
                    loadStream.Close();
                }
                else
                {

                    var resourceName = "WpfApplication1.Resources.hopses.xml";
                    var stream =
                        assembly.GetManifestResourceStream(resourceName);
                    var reader = new System.IO.StreamReader(stream);
                    loadedObject = (HopsData)serializer.Deserialize(reader);

                }
                hopses = loadedObject.Hopses;
            }
        }
Пример #13
0
    static async Task RunAsync()
    {
      try
      {
        using (var client = new HttpClient())
        {
          client.BaseAddress = new Uri(s_wepApiServer);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
          MitchellClaimType claim = null;
          HttpResponseMessage response;

          // Get all Claims
          List<MitchellClaimType> claims = Claims(client).Result;
          XmlSerializer xmlSerializer = new XmlSerializer(typeof(MitchellClaimType));
          string[] files = Directory.GetFiles("../../NewClaims", "*.xml");

          // Add New Claims
          foreach (string fileName in files)
          {
            using (StreamReader reader = new StreamReader(fileName))
            {
              claim = (MitchellClaimType)xmlSerializer.Deserialize(reader);
              response = await client.PostAsJsonAsync<MitchellClaimType>(autoClaimApi, claim).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
            }
          }
          claims = Claims(client).Result;
          claim = Claim(client, claims.First().MitchellClaimTypeId).Result;

          // Update Claims
          files = Directory.GetFiles("../../ClaimUpdates", "*.xml");
          foreach (string fileName in files)
          {
            using (StreamReader reader = new StreamReader(fileName))
            {
              MitchellClaimType claimUpdates = (MitchellClaimType)xmlSerializer.Deserialize(reader);
              claim = (from c in claims where c.ClaimNumber == claimUpdates.ClaimNumber select c).FirstOrDefault();
              if (claimUpdates.MitchellClaimTypeId != claim.MitchellClaimTypeId)
                claimUpdates.MitchellClaimTypeId = claim.MitchellClaimTypeId;
              // more to do response = await client.PutAsJsonAsync<MitchellClaimType>(autoClaimApi + "/" + claim.MitchellClaimTypeId, claimUpdates).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
            }
          }

          // Read a Claim
          claim = Claim(client, claim.MitchellClaimTypeId).Result;

          // Delete a claim
          // more to do response = await client.DeleteAsync(autoClaimApi + "/" + claim.MitchellClaimTypeId).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());

          claim = Claim(client, claim.MitchellClaimTypeId).Result;
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
      }
    }
        public override async Task ExecuteAsync(Update update, Dictionary<string, string> parsedMessage)
        {
            var responseStream = new StreamReader(await GetCurrencyRates());
            var xmlDeserializer = new XmlSerializer(typeof(CurrencyContainerXml.DailyExRates));
            var currencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };

            // Get data for previous date for comparison
            if (_previousDayCurrencyContainer == null ||
                DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(1) !=
                DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null))
            {
                var ondate = DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).AddDays(-1);
                // Rates do not update on weekend (at least here, duh)
                if (ondate.DayOfWeek == DayOfWeek.Sunday)
                {
                    ondate = ondate.AddDays(-2);
                }
                var ondatestring = ondate.ToString(@"MM\/dd\/yyyy");
                responseStream = new StreamReader(await GetCurrencyRates(OnDateParam + ondatestring));
                _previousDayCurrencyContainer = new CurrencyContainerXml() { DailyRates = xmlDeserializer.Deserialize(responseStream) as CurrencyContainerXml.DailyExRates };
            }

            var sb = new StringBuilder();
            sb.Append("Курсы валют на ");
            sb.AppendLine(DateTime.ParseExact(currencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.Append("По отношению к ");
            sb.AppendLine(DateTime.ParseExact(_previousDayCurrencyContainer.DailyRates.Date, "MM/dd/yyyy", null).ToShortDateString());
            sb.AppendLine();

            List<string> currenciesList = new List<string>();
            if (parsedMessage.ContainsKey("message"))
            {
                var names = parsedMessage["message"].Split(',').ToList();
                currenciesList.AddRange(names.Select(cname => cname.ToUpper()));
            }
            if (currenciesList.Count == 0)
                currenciesList = _defaultCurrenciesList;

            foreach (var currency in currencyContainer.DailyRates.Currency.Where(x => currenciesList.Contains(x.CharCode)))
            {
                sb.Append(currency.CharCode + ": " + currency.Rate);
                if (_previousDayCurrencyContainer != null)
                {
                    var diff = currency.Rate -
                               _previousDayCurrencyContainer.DailyRates.Currency.First(
                                   x => x.CharCode == currency.CharCode).Rate;
                    sb.Append(" _(");
                    sb.Append(diff > 0 ? "+" : "-");
                    sb.Append(Math.Abs(diff));
                    sb.Append(")_");
                }
                sb.AppendLine();
            }

            await Bot.SendTextMessage(update.Message.Chat.Id, sb.ToString(), false, update.Message.MessageId, null, true);
        }
Пример #15
0
 public void Resume()
 {
     Type t = GetType();
     FileStream fs = new FileStream(string.Format("{0}.xml", t.Name), FileMode.Open, FileAccess.Read);
     XmlSerializer xs = new XmlSerializer(t); // сериализация жасайды
     if (t == typeof(Wall)) Game.wall = xs.Deserialize(fs) as Wall;
     if (t == typeof(Snake)) Game.snake = xs.Deserialize(fs) as Snake;
     if (t == typeof(Food)) Game.food = xs.Deserialize(fs) as Food;
     fs.Close();
 }
        public void Compare()
        {
            var comparer = new SqlPublicationComparer();

            var serializer = new XmlSerializer(typeof (Element));
            var source = (Element)serializer.Deserialize(new FileStream(@"Samples\Compiled Model.xml", FileMode.Open));
            var target = (Element)serializer.Deserialize(new FileStream(@"Samples\Extracted Model.xml", FileMode.Open));

            comparer.Compare(source, target);
        }
Пример #17
0
 public void Resume()
 {
     Type t = this.GetType();
     FileStream fs = new FileStream(string.Format("{0}.xml", t.Name), FileMode.Open, FileAccess.Read);
     XmlSerializer xs = new XmlSerializer(t);
     if (t == typeof(Snake)) Game.s = xs.Deserialize(fs) as Snake;
     if (t == typeof(Food)) Game.f = xs.Deserialize(fs) as Food;
     if (t == typeof(Wall)) Game.w = xs.Deserialize(fs) as Wall;
     fs.Close();
 }
Пример #18
0
 public void loadActigoHistoricalStocks(string filename1, string filename2, string filename3)
 {
     FileStream file1 = File.Open(filename1, FileMode.OpenOrCreate);
     FileStream file2 = File.Open(filename2, FileMode.OpenOrCreate);
     FileStream file3 = File.Open(filename3, FileMode.OpenOrCreate);
     XmlSerializer serializer = new XmlSerializer(typeof(List<HistoricalStock>));
     EuroStoxx50 = ((List<HistoricalStock>)serializer.Deserialize(file1));
     Sp500 = ((List<HistoricalStock>)serializer.Deserialize(file2));
     SpAsx200 = ((List<HistoricalStock>)serializer.Deserialize(file3));
     file1.Close();
     file2.Close();
     file3.Close();
 }
Пример #19
0
        static int Main(string[] args)
        {
            var exitCode = 1;

            try
            {
                var cmdOptions = PowerArgs.Args.Parse<CommandLineOptions>(args);

                if (string.Compare(cmdOptions.Baseline, cmdOptions.Live, StringComparison.OrdinalIgnoreCase) == 0)
                    throw new ArgumentException("The values of baseline and live parameters cannot be identical.");

                var xmls = new XmlSerializer(typeof(AggregateEventsData));

                AggregateEventsData baseline = null;
                AggregateEventsData live = null;

                using (StreamReader reader = new StreamReader(cmdOptions.Baseline))
                {
                    baseline = (AggregateEventsData)xmls.Deserialize(reader);
                }

                using (StreamReader reader = new StreamReader(cmdOptions.Live))
                {
                    live = (AggregateEventsData)xmls.Deserialize(reader);
                }

                var dataComparer = new AggregateEventsDataComparer(baseline, live);

                if (dataComparer.CompareResults())
                {
                    Console.WriteLine("PASS: perf results are ok");
                    exitCode = 0;
                }
                else
                {
                    Console.WriteLine("FAIL: perf results out of tolerance");
                }
            }
            catch (PowerArgs.ArgException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(PowerArgs.ArgUsage.GenerateUsageFromTemplate<CommandLineOptions>());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return exitCode;
        }
        public object Create(object parent, object configContext, XmlNode section)
        {
            var serializer = new XmlSerializer(GetType());
            var config = (WebConfigurationSectionHandler)serializer.Deserialize(new XmlNodeReader(section));
            var path = config.FilePath;
            if(string.IsNullOrEmpty(path))
                return config;
            var httpConfig = configContext as HttpConfigurationContext;
            if(httpConfig != null)
                path = HttpContext.Current.Server.MapPath(httpConfig.VirtualPath + "/" + path);

            using(var file = File.OpenRead(path))
                return serializer.Deserialize(file);
        }
Пример #21
0
        public ViewModelLocator()
        {
            #if DEBUG
            if (ViewModelBase.IsInDesignModeStatic)
            {
                LocationDescriptionsTestValues = new ObservableCollection<LocationDescription>();
                TransitDescriptionsTestValues = new ObservableCollection<TransitDescription>();

                var bingMapsResponseSerializer = new XmlSerializer(typeof(Response));
                var bingSearchResponseSerializer = new XmlSerializer(typeof(SearchResponse));

                var bmlocresx = new Uri("TestData/bingmapslocations.xml", UriKind.Relative);
                var bmbusresx = new Uri("TestData/bingmapstransit.xml", UriKind.Relative);
                var bsphoresx = new Uri("TestData/bingservicephonebook.xml", UriKind.Relative);

                var sr1 = new StreamReader(System.Windows.Application.GetResourceStream(bmlocresx).Stream);
                var sr2 = new StreamReader(System.Windows.Application.GetResourceStream(bsphoresx).Stream);
                var sr3 = new StreamReader(System.Windows.Application.GetResourceStream(bmbusresx).Stream);

                var locRsp = (Response)bingMapsResponseSerializer.Deserialize(sr1);
                foreach (Location location in locRsp.ResourceSets[0].Resources)
                {
                    LocationDescriptionsTestValues.Add(new LocationDescription(location));
                }

                var phoRsp = (SearchResponse)bingSearchResponseSerializer.Deserialize(sr2);
                foreach (PhonebookResult phone in phoRsp.Phonebook.Results)
                {
                    LocationDescriptionsTestValues.Add(new LocationDescription(phone));
                }

                var busRsp = (Response)bingMapsResponseSerializer.Deserialize(sr3);
                foreach (Route route in busRsp.ResourceSets[0].Resources)
                {
                    TransitDescriptionsTestValues.Add(new TransitDescription(route, TransitDescription.DirectionType.Transit));
                }

                sr1.Dispose();
                sr2.Dispose();
                sr3.Dispose();
            }
            #endif

            CreateMainMapViewModel();
            CreateLocationSelectionViewModel();
            CreateDirectionsViewModel();
            CreateSettingsViewModel();
        }
Пример #22
0
		public static TriviaMessage Deserialize(string dataReceived)
		{
            /*
bool correctEnding = (dataReceived.EndsWith("</TriviaMessage>"));
if (!correctEnding)
{
	throw new InvalidOperationException("Deserialization will fail...");
}
             */
			XmlSerializer serializer = new XmlSerializer(typeof(TriviaMessage));
			StringReader reader = new StringReader(dataReceived);

			TriviaMessage message = null;

            try
            {
                message = (TriviaMessage)(serializer.Deserialize(reader));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("Failed to deserialize this data received '{0}'", dataReceived), ex);
            }

			reader.Close();
			
			return message;
		}
Пример #23
0
        public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem));
            StringReader textReader = new StringReader(s);

            return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem;
        }
Пример #24
0
        public static object DeserializeAudioTracks(string tracksString)
        {
            XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(List<BackgroundTrackItem>));
            StringReader textReader = new StringReader(tracksString);

            return xmlDeSerializer.Deserialize(textReader) as List<BackgroundTrackItem>;
        }
Пример #25
0
        private async Task<Device> GetXml(Dictionary<string, string> headers)
        {
            if (headers.ContainsKey("location"))
            {
                WebRequest request = WebRequest.Create(new Uri(headers["location"]));

                var r = (HttpWebResponse) await request.GetResponseAsync();
                if (r.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        var ser = new XmlSerializer(typeof (Device));
                        return (Device) ser.Deserialize(r.GetResponseStream());
                    }
                    catch (InvalidOperationException ex)
                    {
                        Debug.WriteLine(ex.Message);
                        return null;
                    }
                }

                throw new Exception("Cannot connect to service");
            }

            throw new Exception("No service Uri defined");
        }
Пример #26
0
        public config GetDefault()
        {
            config config;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.buy4.com/api/toolbar/config.xml");

            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlSerializer serializer = new XmlSerializer(typeof(config));
            Stream stream = response.GetResponseStream();

            using (XmlReader reader = XmlReader.Create(stream))
                {
                config = (config)serializer.Deserialize(reader);

                }

            stream.Close();

            return config;
        }
Пример #27
0
        /// <summary>
        /// Initialise the forums element from the server.
        /// </summary>
        private void Initialise()
        {
            string url = string.Format("cix.svc/user/{0}/topics.xml", _data.Name);
            WebRequest wrGeturl = WebRequest.Create(CIXOAuth.GetUri(url));
            wrGeturl.Method = "GET";

            try
            {
                Stream objStream = wrGeturl.GetResponse().GetResponseStream();
                if (objStream != null)
                {
                    using (XmlReader reader = XmlReader.Create(objStream))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(UserTopicResultSet));
                        UserTopicResultSet listOfTopics = (UserTopicResultSet)serializer.Deserialize(reader);

                        _topics = new Topics();
                        foreach (UserTopicResultSetUserTopicsUserTopic topic in listOfTopics.UserTopics)
                        {
                            Topic newTopic = new Topic(topic, this);
                            _topics.Add(newTopic);
                        }
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Message.Contains("401"))
                {
                    throw new AuthenticationException("Authentication Failed", e);
                }
            }
            _initialised = true;
        }
Пример #28
0
        public static void Serialization1(Human human)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Human));
            StringBuilder sb = new StringBuilder();

            /* SERIALIZATION */
            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, human);
            }
            // XML file
            //Console.WriteLine("SB: " +sb.ToString());
            /* END SERIALIZATION */



            /* DESERIALIZATION */
            Human newMartin = new Human();
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                newMartin = serializer.Deserialize(reader) as Human;
            }
            Console.WriteLine(newMartin.ToString() + Environment.NewLine);
            /* END DESERIALIZATION */
        }
Пример #29
0
        /// <summary>
        /// Deserializes an xml file into an object list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        static public T Load <T>(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(default(T));
            }

            var objectOut    = default(T);
            var attributeXml = string.Empty;

            // load xml file
            var xmlDocument = new XmlDocument();

            xmlDocument.Load(fileName);
            var xmlString = xmlDocument.OuterXml;

            // deserialize string to object
            var serializer = new Serialization.XmlSerializer(typeof(T));

            using (var reader = new XmlTextReader(new StringReader(xmlString)))
            {
                objectOut = (T)serializer.Deserialize(reader);
            }

            return(objectOut);
        }
 public async Task<SummaryTemperatureData> GetStdAsync()
 {
     // var uri = new Uri("http://jeffa.org:81/ha/SummaryData.php");
     //var uri = new Uri(App.SummaryDataUrl);
     //var client = new HttpClient();
     //var opContent = (await client.GetAsync(uri)).Content;
     //string foo = await opContent.ReadAsStringAsync();
     //var fooo = JsonConvert.DeserializeObjectAsync<SummaryTemperatureData>(foo);
     //return await fooo;
     var applicationDataSettingsService = new ApplicationDataSettingsService();
     try
     {
     // ToDo need to wrap this a bit. error checking. disposal....
     WebHeaderCollection headers = new WebHeaderCollection();
     WebRequest request = WebRequest.Create(new Uri(applicationDataSettingsService.SummaryDataUrl));
     request.ContentType = "application/xml";
     WebResponse response = await request.GetResponseAsync();
     // response.Close(); // ?? hmmm
     Debug.WriteLine("\nThe HttpHeaders are \n{0}", request.Headers);
     Stream inputStream = response.GetResponseStream();
     XmlReader xmlReader = XmlReader.Create(inputStream);
     XmlSerializer xml = new XmlSerializer(typeof(SummaryTemperatureData));
     var stdXml = (SummaryTemperatureData)xml.Deserialize(xmlReader);
     return stdXml;
     }
     catch (Exception e)
     {
         Utility.Log(this, e.ToString());
         return null;
     }
 }
Пример #31
0
        public email()
        {
            Data rx=null;
            XmlSerializer reader = new XmlSerializer(typeof(Data));
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            using (FileStream input = File.OpenRead(appPath+@"\data.xml"))
            {
                if(input.Length !=0)
                   rx = reader.Deserialize(input) as  Data;
            }

            if (rx != null)
            {
                try
                {
                    emaila = rx.userName;
                    passwd = UnprotectPassword(rx.passwd);
                    loginInfo = new NetworkCredential(emaila, passwd);
                    msg = new MailMessage();
                    smtpClient = new SmtpClient(rx.outGoing, rx.port);
                    smtpClient.EnableSsl = rx.ssl;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    this.createMessage();
                    Environment.Exit(0);
                }
                catch (SmtpException sysex)
                {

                    MessageBox.Show("Taxi Notification App Has Encountered a Problem " +sysex.Message + " Please Check Your Configuration Settings", "Taxi Notification Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            else Environment.Exit(0);
        }
Пример #32
0
 private bool start()
 {
     for (int i = 0; i < numberOfIter; ++i)
     {
         if (file.FileExists(@"buFile" + i + ".txt"))
         {
             fileStream = file.OpenFile(@"buFile" + i + ".txt", System.IO.FileMode.Open);
         }
         else
         {
             throw new FileNotFoundException();
         }
         rf      = new StreamReader(fileStream);
         bufList = (List <buffer>)reader.Deserialize(rf);
         // (new Thread(delegate() { func(bufList, i); })).Start();
         func(bufList, i);
     }
     return(true);
 }
Пример #33
0
        public void main()
        {
            StreamWriter sw = new StreamWriter(@"C:\revature\quintana-richard-project0\RestaurantReviews\RestaurantDB\Properties\Serialization.txt");

            restaurant.restaurant_id = 5;
            restaurant.names         = "Taco Bell";
            restaurant.address       = "16162 Loki Lane";
            restaurant.city          = "Tampa";
            restaurant.state         = "Fl";
            restaurant.zipcode       = "33604";
            restaurant.avg_rating    = 4;

            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(restaurant.GetType());
            x.Serialize(sw, restaurant);
            sw.Close();
            Restaurants restOut = (Restaurants)x.Deserialize(new StreamReader(@"C:\revature\quintana-richard-project0\RestaurantReviews\RestaurantDB\Properties\Serialization.txt"));

            Console.WriteLine(restOut.names);
        }
Пример #34
0
    public void LoadLevelData()
    {
        TextAsset textAsset  = Resources.Load("Data/Levels/LevelData") as TextAsset;
        var       serializer = new System.Xml.Serialization.XmlSerializer(typeof(LevelDataCollection));

        using (var reader = new System.IO.StringReader(textAsset.text))
        {
            this.levelDataCollection = (LevelDataCollection)serializer.Deserialize(reader);
        }

        for (int i = 0; i < levelDataCollection.ListLevelData.Count; i++)
        {
            levelDataCollection.ListLevelData[i].LevelIndex = i + 1;
        }

        lastLevel  = ObscuredPrefs.GetInt("LastLevel", 0);
        totalLevel = levelDataCollection.ListLevelData.Count;
        // lastLevel = 2;
    }
Пример #35
0
        /// <summary>
        /// Deserializes Indico.BusinessObjects.PackingListCartonItemBO object from an XML representation
        /// </summary>
        /// <param name="strXML">a XML string serialized representation</param>
        public Indico.BusinessObjects.PackingListCartonItemBO DeserializeObject(string strXML)
        {
            Indico.BusinessObjects.PackingListCartonItemBO objTemp = null;
            System.Xml.XmlDocument objXML = new System.Xml.XmlDocument();

            objXML.LoadXml(strXML);
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            System.IO.MemoryStream objStream = new System.IO.MemoryStream();
            byte[] b = encoding.GetBytes(objXML.OuterXml);

            objStream.Write(b, 0, (int)b.Length);
            objStream.Position = 0;
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(this.GetType());

            objTemp = (Indico.BusinessObjects.PackingListCartonItemBO)x.Deserialize(objStream);
            objStream.Close();
            return(objTemp);
        }
Пример #36
0
        /// <summary>
        /// Deserializes a XML file.
        /// </summary>
        /// <param name="filename">The filename of the XML file to deserialize</param>
        /// <param name="settings">XML serialization settings. <see cref="System.Xml.XmlReaderSettings"/></param>
        /// <returns>An object of type <c>T</c></returns>
        public static T DeserializeFromFile(string filename, XmlReaderSettings settings)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentException("filename", "XML filename cannot be null or empty");
            }

            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("Cannot find XML file to deserialize", filename);
            }

            // Create the stream writer with the specified encoding
            using (XmlReader reader = XmlReader.Create(filename, settings))
            {
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return((T)xmlSerializer.Deserialize(reader));
            }
        }
Пример #37
0
        public static MetalStyle LoadStyle(string fileName)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MetalStyle));

                System.IO.Stream stream = System.IO.File.OpenRead(fileName);
                MetalStyle       style  = (MetalStyle)serializer.Deserialize(stream);
                stream.Close();
                stream = null;

                return(style);
            }
            catch
            {
                // TODO: Log
                return(new MetalStyle());
            }
        }
        public static List <T> Deserializer <T>(StreamReader reader, string root) where T : class
        {
            try
            {
                var deserializer = new System.Xml.Serialization.XmlSerializer
                                   (
                    typeof(List <T>),
                    new XmlRootAttribute(root)
                                   );

                var obj = (List <T>)deserializer.Deserialize(reader);
                return(obj);
            }
            catch (Exception e)
            {
                LogHelper.PrintLog($"Error during deserializing, due to: {e}");
                throw;
            }
        }
Пример #39
0
        public void Load()
        {
            if (File.Exists("SettingBackup.xml"))
            {
                XmlSerializer       reader = new System.Xml.Serialization.XmlSerializer(typeof(ConfigurationBackup));
                StreamReader        file   = new System.IO.StreamReader(pathModule + @"\SettingBackup.xml");
                ConfigurationBackup config = new ConfigurationBackup();
                config = (ConfigurationBackup)reader.Deserialize(file);

                this.activate             = config.activate;
                this.general_Log          = config.general_Log;
                this.import_Log           = config.import_Log;
                this.export_Log           = config.export_Log;
                this.export_Log           = config.export_Log;
                this.import_files_success = config.import_files_success;
                this.import_files_error   = config.import_files_error;
                this.backup_files         = config.backup_files;
                file.Close();
            }
        }
Пример #40
0
        public static List <T> DeserializeParamsListOf <T>(string xmlFilename)
        {
            List <T>  result;
            XDocument xdoc = XDocument.Load(xmlFilename);

            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                    new System.Xml.Serialization.XmlSerializer(typeof(List <T>));

                System.Xml.XmlReader reader = xdoc.CreateReader();

                result = (List <T>)serializer.Deserialize(reader);
                reader.Close();
            }
            finally
            {
            }
            return(result);
        }
Пример #41
0
        public static TMSDictionary DeserializeTMSItemData(string fileName)
        {
            TMSDictionary  dict = null;
            List <TMSItem> list = null;

            using (var reader = new StreamReader(fileName))
            {
                System.Xml.Serialization.XmlSerializer deserializer = new System.Xml.Serialization.XmlSerializer(typeof(List <TMSItem>),
                                                                                                                 new System.Xml.Serialization.XmlRootAttribute("ArrayOfTMSItem"));
                list = (List <TMSItem>)deserializer.Deserialize(reader);
            }

            if (list != null)
            {
                dict = new TMSDictionary();
                list.ForEach(x => dict.Add(x.TMS, x));
            }

            return(dict);
        }
Пример #42
0
        public static object LoadFromXml(string filePath, Type type)
        {
            object result = null;

            try
            {
                if (File.Exists(filePath))
                {
                    using (StreamReader streamReader = new StreamReader(filePath))
                    {
                        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
                        result = xmlSerializer.Deserialize(streamReader);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Пример #43
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pXmlStr"></param>
        private static BitmapFont FromXml(byte[] pData, Texture2D pFontImage)
        {
            System.Xml.Serialization.XmlSerializer deserializer = new System.Xml.Serialization.XmlSerializer(typeof(BitmapFont));
            System.IO.MemoryStream strm       = new System.IO.MemoryStream(pData);
            System.IO.TextReader   textReader = new System.IO.StreamReader(strm);
            BitmapFont             file       = (BitmapFont)deserializer.Deserialize(textReader);

            file.mFontImage = pFontImage;

            file.mCharsDictionary.Clear();
            foreach (FontChar chr in file.Chars)
            {
                char c = Convert.ToChar(chr.ID);
                chr.Init(file.Info.Size, pFontImage.width, pFontImage.height, c);
                file.mCharsDictionary.Add(c, chr);
            }

            textReader.Close();
            return(file);
        }
Пример #44
0
 public static Favorite Load()
 {
     if (File.Exists(FileName) == true)
     {
         System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Favorite));
         using (TextReader strm = new StreamReader(FileName, Encoding.UTF8))
         {
             try
             {
                 //valorizzo l'oggetto con le proprietà lette dal file
                 Favorite f = (Favorite)xs.Deserialize(strm);
                 f.FileFound = true;
                 f.TextInput = f.TextInput.Replace("\n", "\r\n");
                 return(f);
             }
             catch { }
         }
     }
     return(new Favorite());
 }
Пример #45
0
        public T Deserialize <T>(string input) where T : class
        {
            /* Converts an XML string into a typed object
             *
             * Usage:
             *
             * var _obj = new <CLASS>();
             * using (var _reader = new StringReader(XML))
             *  {
             *      _obj = new Utilities.Text.XML().Deserialize<CLASS>(_reader.ReadToEnd());
             *  }
             *
             */
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
            {
                return((T)ser.Deserialize(sr));
            }
        }
Пример #46
0
        /// <summary>
        /// 将一个字符串反序列化为一个对象
        /// </summary>
        /// <param name="objType">要反序列化的对象类型</param>
        /// <param name="str">要反序列化的字符串</param>
        /// <returns>反序列化得到的对象</returns>
        public object Deserialize(Type objType, string str)
        {
            if (objType == null)
            {
                throw new ArgumentNullException(nameof(objType));
            }
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(nameof(str));
            }

            System.Xml.Serialization.XmlSerializer mySerializer = new System.Xml.Serialization.XmlSerializer(objType);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {
                using (StreamReader sr = new StreamReader(ms))
                {
                    return(mySerializer.Deserialize(sr));
                }
            }
        }
Пример #47
0
        public static Configuration Deserialize(string filename)
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Configuration));

            try
            {
                using (var reader = new StreamReader(filename))
                {
                    var config = (Configuration)serializer.Deserialize(reader);
                    config.OnPostDeserialize();
                    return(config);
                }
            }
            catch (System.Exception ex)
            {
                Debug.Log(ex.ToString());
            }

            return(null);
        }
Пример #48
0
        public static List <BaiHoc> Get_Ds_NoiOChu()
        {
            List <BaiHoc> data;

            try
            {
                System.Xml.Serialization.XmlSerializer reader =
                    new System.Xml.Serialization.XmlSerializer(typeof(List <BaiHoc>));
                System.IO.StreamReader file = new System.IO.StreamReader(path_NoiCau);

                data = (List <BaiHoc>)reader.Deserialize(file);
                file.Close();

                return(data.OrderBy(x => x.thutu).ToList());
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Пример #49
0
        public static T ToDeserializeObject <T>(this string xmlstring)
        {
            if (string.IsNullOrEmpty(xmlstring))
            {
                return(default(T));
            }

            try
            {
                System.Xml.Serialization.XmlSerializer deserializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                System.IO.StringReader textReader = new System.IO.StringReader(xmlstring);
                object obj = deserializer.Deserialize(textReader);
                textReader.Close();
                return((T)obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #50
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start parsing....");

            string filename = @"..\..\..\Files\Monsieur et Madame TROCHARD Gilles et Antoinette - Nouvelle étude.xml";

            System.IO.StreamReader str = new System.IO.StreamReader(filename);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(AdresseMap));
            AdresseMap res = (AdresseMap)xSerializer.Deserialize(str);

            //foreach (ResultSetResult r in res)
            //{
            //    Console.WriteLine(r.Title);
            //    Console.WriteLine(r.Summary);
            //    Console.WriteLine();
            //}
            //str.Close();

            Console.ReadLine();
        }
        public IRestResponse Call(string resource, IDictionary <string, object> parameters = null, IDictionary <string, object> headers = null)
        {
            Assertion.NotEmpty(resource);

            var request  = CreateRequest(resource, parameters);
            var response = restClient.Post(request);

            if (response.ErrorException != null || response.StatusCode != HttpStatusCode.OK)
            {
                throw new TranslatorException(new Error((int)response.StatusCode, response.ErrorMessage ?? response.StatusDescription), response.ErrorException);
            }

            IError error = null;

            try
            {
                switch (request.RequestFormat)
                {
                case DataFormat.Json:
                    error = response.Content.Json <Error>();
                    break;

                case DataFormat.Xml:
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Error), new XmlRootAttribute("result"));
                    using (var source = new StringReader(response.Content))
                    {
                        error = serializer.Deserialize(source).To <Error>();
                    }
                    break;
                }
            }
            catch
            {
            }
            if (error != null && !error.Text.IsEmpty())
            {
                throw new TranslatorException(error);
            }

            return(response);
        }
Пример #52
0
        private static void DeSerializeUploadedDemoData()
        {
            if (File.Exists(filename))
            {
                try
                {
                    System.Xml.Serialization.XmlSerializer xmlReader =
                        new System.Xml.Serialization.XmlSerializer(typeof(List <UploadedDemoData>));

                    System.IO.StreamReader streamReader = new System.IO.StreamReader(filename);

                    uploadedDemoDataList = (List <UploadedDemoData>)xmlReader.Deserialize(streamReader);

                    streamReader.Close();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #53
0
        //public static void TestXML()
        //{
        //TestXML entity = new USeFuturesSpirit.TestXML();
        //entity.TestBase1 = new XMLTestSubClass1()
        //{
        //    Name = "test1",
        //    MyProperty = "propert1"
        //};
        ////entity.TestBase2 = new XMLTestSubClass2() {
        ////    Name = "test2",
        ////    MySex = "sex2"
        ////};

        ////entity.TestBase1 = new XMLTestSubClass2() {
        ////    Name = "test2aaa",
        ////    MySex = "sex2aaa"
        ////};
        //entity.TestBase2 = new XMLTestSubClass2()
        //{
        //    Name = "test2",
        //    MySex = "sex2"
        //};

        //HanYuTest hanyu = new HanYuTest()
        //{
        //    MyTest = entity
        //};
        //try
        //{
        //    //string Json = JsonHelper.JsonSerializer<TestXML>(entity);
        //    string fileFullName = @"D:\test.xml";
        //    XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        //    // Create the XmlAttributes class.
        //    XmlAttributes attrs = new XmlAttributes();
        //    XmlElementAttribute attr = new XmlElementAttribute("sub1", typeof(XMLTestSubClass1));
        //    attrs.XmlElements.Add(attr);

        //    XmlElementAttribute attr2 = new XmlElementAttribute("sub2", typeof(XMLTestSubClass2));
        //    attrs.XmlElements.Add(attr2);

        //    /* Add the XmlAttributes to the XmlAttributeOverrides.
        //    "Students" is the name being overridden. */
        //    attrOverrides.Add(typeof(TestXML), "TestBase1", attrs);

        //    XmlAttributes attrs22 = new XmlAttributes();
        //    XmlElementAttribute attr22 = new XmlElementAttribute("ym1", typeof(XMLTestSubClass1));
        //    attrs22.XmlElements.Add(attr22);

        //    XmlElementAttribute attr222 = new XmlElementAttribute("ym2", typeof(XMLTestSubClass2));
        //    attrs22.XmlElements.Add(attr222);

        //    attrOverrides.Add(typeof(TestXML), "TestBase2", attrs22);

        //    SaveToXml(fileFullName, hanyu, attrOverrides);


        //    HanYuTest result = LoadFromXml<HanYuTest>(fileFullName, attrOverrides);

        //    string s = "";



        //}
        //catch (Exception ex)
        //{
        //    throw new Exception("SaveGlobalFontServerConfig failed,Error:" + ex.Message);
        //}

        //}

        public static T LoadFromXml <T>(string filePath, XmlAttributeOverrides attrOverrides)
        {
            if (File.Exists(filePath) == false)
            {
                return(default(T));
            }

            object result = null;

            using (StreamReader reader = new StreamReader(filePath))
            {
                if (reader.EndOfStream)
                {
                    return(default(T));
                }
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T), attrOverrides);
                result = xmlSerializer.Deserialize(reader);
            }

            return((T)result);
        }
Пример #54
0
        public static List <software> LoadSoftwares()
        {
            try
            {
                System.Xml.Serialization.XmlSerializer reader =
                    new System.Xml.Serialization.XmlSerializer(typeof(List <software>), new Type[] { typeof(software) });

                using (
                    StreamReader sr =
                        new StreamReader(Application.StartupPath + Path.DirectorySeparatorChar + "fwversions.xml"))
                {
                    return((List <software>)reader.Deserialize(sr));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return(new List <software>());
        }
Пример #55
0
    public void ReadXmlFile()
    {
        Setting overview = new Setting();

        try
        {
            System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(Setting));

            System.IO.StreamReader file = new System.IO.StreamReader(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "configLog.xml"));
            overview = (Setting)reader.Deserialize(file);
            file.Close();
            file.Dispose();

            InsertScriptTag("var keeplog =" + overview.keeplog + ";" + "var strLogpath ='" + string.Join("|", overview.logpath) + "';");
        }
        catch (Exception ex)
        {
            string defaultLogPath = System.IO.Path.Combine(System.IO.Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName, "logs");
            InsertScriptTag("var keeplog =" + "90" + ";" + "var strLogpath ='" + defaultLogPath.Replace("\\", "/") + "';");
        }
    }
Пример #56
0
 /// <summary>
 /// 从XML文件加载对象
 /// </summary>
 /// <param name="path">XML文件路径</param>
 /// <param name="type">类型</param>
 /// <returns></returns>
 public static T LoadFromXml <T>(this string path) where T : class
 {
     try
     {
         T result = null;
         if (System.IO.File.Exists(path))
         {
             using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
             {
                 System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                 result = xmlSerializer.Deserialize(reader) as T;
             }
         }
         return(result);
     }
     catch
     {
         // TODO 异常处理
         return(null);
     }
 }
Пример #57
0
        public static Settings LoadSettings()
        {
            string path = string.Format("{0}\\data\\settings.xml", Application.UserAppDataPath);

            if (System.IO.File.Exists(path))
            {
                try
                {
                    TextReader    reader     = new StreamReader(path);
                    XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Settings));
                    Settings      settings   = (Settings)serializer.Deserialize(reader);
                    reader.Close();
                    return(settings);
                }
                catch
                {
                    return(new Settings());
                }
            }
            return(new Settings());
        }
Пример #58
0
        public static TResponse LoadFromXml <TResponse, TResponseBody>(string filePath)
            where TResponse : Response <TResponseBody>, new()
            where TResponseBody : class, new()
        {
            TResponse response = default(TResponse);

            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TResponse));
                    response = (TResponse)xmlSerializer.Deserialize(reader);
                    if (response != null)
                    {
                        response.status = (response.head.stateCode == Constants.OK_STATE_CODE) ? Status.OK : Status.ERROR;
                    }
                }
            }

            return(response);
        }
Пример #59
0
 public static object XmlRead(System.IO.Stream stream, Type type)
 {
     try
     {
         if (stream.CanSeek)
         {
             stream.Seek(0, System.IO.SeekOrigin.Begin);
         }
         object result;
         using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8, true))
         {
             System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
             result = serializer.Deserialize(reader);
         }
         return(result);
     }
     catch (Exception exc)
     {
         throw new Exception(String.Format("Cannot deserialize stream to '{0}'.", type.FullName), exc);
     }
 }
Пример #60
0
            public static List <LocalSettings> LoadAll(string filename)
            {
                try
                {
                    string asmPath      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string settingsPath = Path.Combine(asmPath, filename);
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List <LocalSettings>));

                    using (TextReader reader = File.OpenText(settingsPath))
                    {
                        List <LocalSettings> userSettings = (List <LocalSettings>)serializer.Deserialize(reader);
                        return(userSettings);
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Problem loading " + filename);
                    Console.Error.WriteLine(e.Message);
                    return(new List <LocalSettings>());
                }
            }